### Play From First Scene example using EditorApplication Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityeditor/editorapplication A complete example that creates a custom menu item to start the game from the first scene in the build profile. It saves the current scene setup, opens the first scene, enters play mode, and restores the previous scene setup when returning to edit mode. ```csharp using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine.SceneManagement; [InitializeOnLoad] public static class PlayFromFirstScene { static SceneSetup[] s_PreviousAuthoringSceneSetup; [MenuItem("Examples/Play From First Scene", isValidateFunction: true)] static bool CanExecute() { return SceneManager.sceneCountInBuildSettings > 0 && !EditorApplication.isPlayingOrWillChangePlaymode; } [MenuItem("Examples/Play From First Scene")] static void Execute() { if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) return; s_PreviousAuthoringSceneSetup = EditorSceneManager.GetSceneManagerSetup(); EditorSceneManager.OpenScene(SceneUtility.GetScenePathByBuildIndex(0), OpenSceneMode.Single); EditorApplication.EnterPlaymode(); } static PlayFromFirstScene() { EditorApplication.playModeStateChanged += OnPlaymodeStateChanged; } static void OnPlaymodeStateChanged(PlayModeStateChange state) { if (state == PlayModeStateChange.EnteredEditMode && s_PreviousAuthoringSceneSetup != null) { EditorSceneManager.RestoreSceneManagerSetup(s_PreviousAuthoringSceneSetup); s_PreviousAuthoringSceneSetup = null; } } } ``` -------------------------------- ### public static string userId { get; } Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityeditor/editoranalyticssessioninfo/userid Gets a random GUID that uniquely identifies an Editor installation. The GUID is generated immediately after installation and is only regenerated if the Editor is re-installed. ```APIDOC ## Property: userId ### Description Gets a random GUID that uniquely identifies an Editor installation. The GUID is generated immediately after installation and is only regenerated if the Editor is re-installed. ### Definition - **Type:** Property - **Namespace:** UnityEditor - **Assembly:** UnityEditor.CoreModule ### Syntax ```csharp public static string userId { get; } ``` ### Remarks Unity generates the userId GUID immediately after installation. The userId value is only regenerated if the user re-installs the Unity Editor. Each instance of Unity on the same computer generates its own userId. Note that this userId is not connected to the Unity account login or username. It is only used to identify which sessions were produced by the same install of the Editor. ``` -------------------------------- ### -buildOSXUniversalPlayer example path Source: https://docs.unity.com/en-us/engine/6000.6/manual/unity-editor/command-line-arguments/editor Example usage of -buildOSXUniversalPlayer with a target path ending in .app. ```bash -buildOSXUniversalPlayer path/to/your/build.app ``` -------------------------------- ### Example startup timing log output Source: https://docs.unity.com/en-us/engine/6000.6/manual/platform-specific/embedded-systems/embedded-linux/develop/optional-features Example output from Player.log showing startup timing entries for various initialization steps, with Real and User times in milliseconds. ```plaintext [TIMING::STARTUP] Initial probing done: Real: 19 ms | User: 11 ms [TIMING::STARTUP] SDL Initialized: Real: 64 ms | User: 54 ms [TIMING::STARTUP] Scripting runtime loaded: Real: 97 ms | User: 86 ms [TIMING::STARTUP] Plugins loaded: Real: 97 ms | User: 87 ms [TIMING::STARTUP] Engine initialized (nogfx): Real: 104 ms | User: 94 ms [TIMING::STARTUP] Player Prefs loaded: Real: 104 ms | User: 94 ms [TIMING::STARTUP] Screen initialized: Real: 139 ms | User: 112 ms [TIMING::STARTUP] Engine initialized (gfx): Real: 187 ms | User: 161 ms [TIMING::STARTUP] Gfx initialized: Real: 190 ms | User: 163 ms [TIMING::STARTUP] Input initialized: Real: 190 ms | User: 163 ms [TIMING::STARTUP] SPLASH - Begin: Real: 190 ms | User: 164 ms [TIMING::STARTUP] SPLASH - Primary scene assets loaded (async): Real: 2197 ms | User: 1670 ms [TIMING::STARTUP] SPLASH - All engine initial states established: Real: 2197 ms | User: 1670 ms ``` -------------------------------- ### buildProfileGuid Property Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityeditor/build/reporting/buildsummary/buildprofileguid Gets the AssetDatabase GUID of the BuildProfile that was active when the build started. This property is read-only and returns a GUID value. ```APIDOC ## buildProfileGuid Property ### Description Gets the AssetDatabase GUID of the BuildProfile that was active when the build started. ### Definition - **Type:** Property - **Namespace:** UnityEditor.Build.Reporting - **Assembly:** UnityEditor.CoreModule ### Syntax ```csharp public readonly GUID buildProfileGuid { get; } ``` ### Remarks A default-valued GUID when no profile was recorded. Otherwise it matches the AssetDatabase GUID of the asset at BuildSummary.buildProfilePath. Useful for tracking the profile across renames or moves. ``` -------------------------------- ### Example: AddForce to attachedRigidbody Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/collider/attachedrigidbody Example usage of attachedRigidbody. In Start, it gets the Collider component and applies an upward force to the attached rigidbody. ```csharp using UnityEngine; public class Example : MonoBehaviour { void Start() { // Lift the rigidbody attached to the collider. GetComponent().attachedRigidbody.AddForce(0, 1, 0); } } ``` -------------------------------- ### Disable detectCollisions in Start Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/charactercontroller/detectcollisions Example MonoBehaviour that gets the CharacterController component and sets detectCollisions to false in Start, disabling collision detection for the controller. ```csharp using UnityEngine; public class Example : MonoBehaviour { CharacterController controller; void Start() { controller = GetComponent(); controller.detectCollisions = false; } } ``` -------------------------------- ### Enable custom keystore and configure settings Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityeditor/playersettings/android/usecustomkeystore Demonstrates enabling useCustomKeystore and setting keyaliasName, keyaliasPass, keystoreName, and keystorePass. Includes logging for each value. ```csharp using UnityEngine; using UnityEditor; public class CustomKeystoreSample : MonoBehaviour { [MenuItem("Build/Custom Keystore Sample")] public static void UseCustomKeystoreSample() { // Set useCustomKeystore value to true PlayerSettings.Android.useCustomKeystore = true; // Log the useCustomKeystore value Debug.Log($"useCustomKeystore: {PlayerSettings.Android.useCustomKeystore}"); // Sign in settings // Set keyaliasName PlayerSettings.Android.keyaliasName = "keyalias"; // Log the keyalias name Debug.Log($"keyaliasName: {PlayerSettings.Android.keyaliasName}"); // Set keyaliasPass PlayerSettings.Android.keyaliasPass = "keyAliasPass"; // Log the keyalias password Debug.Log($"keyaliasPass: {PlayerSettings.Android.keyaliasPass}"); // Set keystoreName PlayerSettings.Android.keystoreName = "keystoreName"; // Log the keystore name Debug.Log($"keystoreName: {PlayerSettings.Android.keystoreName}"); // Set keystorePass PlayerSettings.Android.keystorePass = "keyStorePass"; // Log the keystore password Debug.Log($"keystorePass: {PlayerSettings.Android.keystorePass}"); } } ``` -------------------------------- ### Example: Start WebCamTexture and log isPlaying Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/webcamtexture/isplaying Creates a WebCamTexture, calls Play(), and logs the isPlaying value to the console. The comment notes it tries to start the camera and outputs whether it was successful. ```csharp using UnityEngine; public class Example : MonoBehaviour { // Tries to start the camera and outputs to the console if is was sucessful or not. void Start() { WebCamTexture webcamTexture = new WebCamTexture(); webcamTexture.Play(); Debug.Log(webcamTexture.isPlaying); } } ``` -------------------------------- ### Example: Lift the articulation body attached to the collider Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/collider/attachedarticulationbody In the Start method, this example gets the Collider component and calls AddForce on its attachedArticulationBody to lift it upward. ```csharp using UnityEngine; public class Example : MonoBehaviour { void Start() { // Lift the articulation body attached to the collider. GetComponent().attachedArticulationBody.AddForce(Vector3.up); } } ``` -------------------------------- ### Example: Activate Unity license with specific paths Source: https://docs.unity.com/en-us/engine/6000.6/manual/get-started/install-and-upgrade/licenses-and-activation/manual-license-activation/manual-activation-cmd-win Example command using a Unity Editor installed at "C:\Program Files\Unity\Hub\Editor\2022.2.0b4\Editor\Unity.exe" and a .ulf file at "C:\Users\myAccount\Downloads\Unity_v2017.x.ulf". ```batch "C:\Program Files\Unity\Hub\Editor\2022.2.0b4\Editor\Unity.exe" -batchmode -manualLicenseFile "C:\Users\myAccount\Downloads\Unity_v2017.x.ulf" -logfile ``` -------------------------------- ### Set Projector.fieldOfView in C# Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/projector/fieldofview Example MonoBehaviour that gets a Projector component and sets its fieldOfView to 80.0f in Start(). ```csharp using UnityEngine; public class Example : MonoBehaviour { void Start() { // Get the projector Projector proj = GetComponent(); // Use it proj.fieldOfView = 80.0f; } } ``` -------------------------------- ### BuildPlayer with build profile example Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityeditor/buildpipeline/buildplayer Example showing how to load a build profile, create BuildPlayerWithProfileOptions, call BuildPipeline.BuildPlayer, and check the build result. ```csharp using UnityEditor; using UnityEditor.Build.Reporting; using UnityEditor.Build.Profile; using UnityEngine; namespace BuildDocExamples { public class BuildPipeline_BuildPlayerWithBuildProfileExample { [MenuItem("BuildDocExamples/Build/Build iOS Demo")] public static void MyBuild() { BuildProfile buildProfile = AssetDatabase.LoadAssetAtPath("Assets/Settings/Build Profiles/iOSDemo.asset"); BuildPlayerWithProfileOptions options = new BuildPlayerWithProfileOptions() { buildProfile = buildProfile, locationPathName = "iOSDemoBuild", options = BuildOptions.None, }; BuildReport report = BuildPipeline.BuildPlayer(options); BuildSummary summary = report.summary; // Output the build size or a failure depending on BuildPlayer. if (summary.result == BuildResult.Succeeded) { Debug.Log("Build succeeded: " + summary.totalSize + " bytes"); } if (summary.result == BuildResult.Failed) { Debug.Log("Build failed"); } } } } ``` -------------------------------- ### Example: Get importer type for matching assets Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityeditor/assetdatabase/getimportertype Shows how to use AssetDatabase.GetImporterType with a GUID obtained from AssetDatabase.FindAssets. The example logs the importer type for the first matching asset. ```csharp using UnityEngine; using UnityEditor; public class AssetDatabaseExamples { [MenuItem("AssetDatabase/GetMatchingAssetType")] public static void GetMatchingAssetType() { var matchingAssets = AssetDatabase.FindAssets("Powerup"); var matchingAssetGuid = new GUID(matchingAssets[0]); Debug.Log($"Importer type: {AssetDatabase.GetImporterType(matchingAssetGuid)}"); } } ``` -------------------------------- ### Example: Using StartActivityIndicator with coroutine Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/handheld/startactivityindicator Example showing how to start the activity indicator, wait for the end of the frame, and load a scene. Includes platform-specific style setup for iOS and Android. ```csharp using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Example2 : MonoBehaviour { IEnumerator Load() { #if UNITY_IPHONE Handheld.SetActivityIndicatorStyle(iOS.ActivityIndicatorStyle.Gray); #elif UNITY_ANDROID Handheld.SetActivityIndicatorStyle(AndroidActivityIndicatorStyle.Small); #endif Handheld.StartActivityIndicator(); yield return new WaitForSeconds(0); SceneManager.LoadScene("My Next Scene"); } void OnGUI() { if (GUI.Button(new Rect(10, 10, 200, 200), "Load!")) StartCoroutine(Load()); } } ``` -------------------------------- ### -buildWindows64Player example path Source: https://docs.unity.com/en-us/engine/6000.6/manual/unity-editor/command-line-arguments/editor Example usage of -buildWindows64Player with a target path ending in .exe. ```bash -buildWindows64Player path/to/your/build.exe ``` -------------------------------- ### -buildWindowsPlayer example path Source: https://docs.unity.com/en-us/engine/6000.6/manual/unity-editor/command-line-arguments/editor Example usage of -buildWindowsPlayer with a target path ending in .exe. ```bash -buildWindowsPlayer path/to/your/build.exe ``` -------------------------------- ### Rotate Rigidbody2D every frame starting at 45 degrees Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/rigidbody2d/rotation Example MonoBehaviour that gets a Rigidbody2D component, sets its rotation to 45 degrees in Start, and increments it by 1.0 in FixedUpdate to rotate every frame. ```csharp using UnityEngine; // Rotate rigidBody2D every frame. Start at 45 degrees. public class ExampleScript : MonoBehaviour { public Rigidbody2D rigidBody2D; void Start() { rigidBody2D = GetComponent(); rigidBody2D.rotation = 45f; } void FixedUpdate() { rigidBody2D.rotation += 1.0f; } } ``` -------------------------------- ### Get current system memory usage with ProfilerRecorder Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unity/profiling/profilerrecorder/currentvalue Example showing how to get the current value of a profiler counter without starting the recorder or allocating sample storage. Uses capacity 0 when creating the ProfilerRecorder. ```csharp using UnityEngine; using Unity.Profiling; public class Example { public static void LogCurrentSystemMemoryUsage() { var systemMemoryRecorder = new ProfilerRecorder(ProfilerCategory.Memory, "System Used Memory", 0); Debug.Log("System Used Memory (bytes): " + systemMemoryRecorder.CurrentValue); } } ``` -------------------------------- ### Sample services-config.json with both keys Source: https://docs.unity.com/en-us/engine/6000.6/manual/get-started/install-and-upgrade/ent-deployment/ent-unpriv-install Complete sample configuration file using the values from the procedure. Includes hubDisableElevate and machineWideSecondaryInstallLocation. ```json { "hubDisableElevate": true, "machineWideSecondaryInstallLocation": "C:\\UnityEditors" } ``` -------------------------------- ### C# example using VideoPlayer.isPrepared Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/video/videoplayer/isprepared Example script that uses UnityEngine.Video.VideoPlayer and checks the isPrepared property. The example is incomplete in the source; only the using directives are shown. ```csharp using UnityEngine; using UnityEngine.Video; using System.Collections; // In the Inspector of the VideoPlayer, set the Video Clip to the content you want to play. ``` -------------------------------- ### Example: Determine if target is on left or right side of screen Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/camera/worldtoviewportpoint This example uses WorldToViewportPoint to check if a target is on the left or right side of the screen. It gets the camera component in Start and checks the viewport x coordinate in Update. ```csharp // Finds out whether target is on the left or right side of the screen using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { public Transform target; Camera cam; void Start() { cam = GetComponent(); } void Update() { Vector3 viewPos = cam.WorldToViewportPoint(target.position); if (viewPos.x > 0.5F) print("target is on the right side!"); else print("target is on the left side!"); } } ``` -------------------------------- ### -build example path Source: https://docs.unity.com/en-us/engine/6000.6/manual/unity-editor/command-line-arguments/editor Example usage of -build with a target path ending in .exe. ```bash -build path/to/your/build.exe ``` -------------------------------- ### Example: Checkout selected assets with MakeEditable Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityeditor/assetdatabase/makeeditable A Unity Editor menu item example that gets selected asset GUIDs, converts them to paths, and calls AssetDatabase.MakeEditable with a prompt. Logs an error if any files could not be made editable. ```csharp using System.Linq; using UnityEngine; using UnityEditor; public class ExampleScript : MonoBehaviour { [MenuItem("Example/Checkout Selected Assets")] public static void MenuExample() { var guids = Selection.assetGUIDs; var paths = guids.Select(AssetDatabase.GUIDToAssetPath).ToArray(); var ok = AssetDatabase.MakeEditable(paths, "These files need to be checked out"); if (!ok) Debug.LogError("Could not make some files editable"); } } ``` -------------------------------- ### Example: Open custom project settings and preferences Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityeditor/settingsservice/openprojectsettings Example class showing how to use SettingsService.OpenProjectSettings and SettingsService.OpenUserPreferences in an EditorWindow's OnGUI method. ```csharp using UnityEditor; using UnityEngine; class MyCustomWindow : EditorWindow { void OnGUI() { if (GUILayout.Button("Open my custom preference")) { SettingsService.OpenUserPreferences("Preferences/MyCustomPref"); } if (GUILayout.Button("Open my custom project settings")) { SettingsService.OpenProjectSettings("Project/MyCustomSettings"); } } } ``` -------------------------------- ### Set start delay and lifetime using ParticleSystem.main Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/particlesystem/main Example MonoBehaviour that gets the main module and sets startDelay to 5 seconds and startLifetime to 2 seconds. ```csharp // Create a Particle System // Set a 5 second start delay for the system, and a 2 second lifetime for each particle using UnityEngine; using System.Collections; [RequireComponent(typeof(ParticleSystem))] public class ExampleClass : MonoBehaviour { void Start() { ParticleSystem ps = GetComponent(); var main = ps.main; main.startDelay = 5.0f; main.startLifetime = 2.0f; } } ``` -------------------------------- ### -buildLinux64Player example path Source: https://docs.unity.com/en-us/engine/6000.6/manual/unity-editor/command-line-arguments/editor Example usage of -buildLinux64Player with a target path. ```bash -buildLinux64Player path/to/your/build ``` -------------------------------- ### Unity Editor -logFile example (Windows) Source: https://docs.unity.com/en-us/engine/6000.6/manual/unity-editor/command-line-arguments/editor Command-line example for launching Unity Editor on Windows with -projectPath and -logFile. Wrap paths with spaces in double quotes. ```bash "C:\Program Files\Unity\Hub\Editor\\Editor\Unity.exe" -projectPath "C:\Projects\MyGame" -logFile "C:\Logs\Editor.log" ``` -------------------------------- ### Example: Calling Optimize() on a mesh Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/mesh/optimize A MonoBehaviour example that gets the mesh from a MeshFilter component and calls Optimize() in the Start method. Use this on procedurally generated meshes, as regular mesh assets are optimized automatically by the import pipeline when 'Optimize Mesh' is enabled. ```csharp using UnityEngine; public class Example : MonoBehaviour { void Start() { Mesh mesh = gameObject.GetComponent().mesh; mesh.Optimize(); } } ``` -------------------------------- ### Example command for macOS with Unity 2022.2.0b4 Source: https://docs.unity.com/en-us/engine/6000.6/manual/get-started/install-and-upgrade/licenses-and-activation/manual-license-activation/manual-activation-cmd-mac Example command using a specific Unity installation path and license file path. Assumes Unity is installed at /Applications/Unity/Hub/Editor/2022.2.0b4/Unity.app and the license file is at /Users/myAccount/Downloads/Unity_v2017.x.ulf. ```bash /Applications/Unity/Hub/Editor/2022.2.0b4/Unity.app/Contents/MacOS/Unity -batchmode -manualLicenseFile /Users/myAccount/Downloads/Unity_v2017.x.ulf -logfile ``` -------------------------------- ### Example: Adjusting minParticleSize and maxParticleSize with GUI sliders Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/particlesystemrenderer/maxparticlesize A complete C# example that gets the ParticleSystem and ParticleSystemRenderer components, sets the main start size to a MinMaxCurve, and updates minParticleSize and maxParticleSize in Update based on GUI sliders. Requires a ParticleSystem component on the same GameObject. ```csharp using UnityEngine; using System.Collections; [RequireComponent(typeof(ParticleSystem))] public class ExampleClass : MonoBehaviour { private ParticleSystem ps; private ParticleSystemRenderer psr; public float minSize = 0.0f; public float maxSize = 1.0f; void Start() { ps = GetComponent(); psr = GetComponent(); var main = ps.main; main.startSize = new ParticleSystem.MinMaxCurve(0.1f, 5.0f); } void Update() { psr.minParticleSize = minSize; psr.maxParticleSize = maxSize; } void OnGUI() { GUI.Label(new Rect(25, 40, 200, 30), "Minimum Screen Space Size"); GUI.Label(new Rect(25, 80, 200, 30), "Maximum Screen Space Size"); minSize = GUI.HorizontalSlider(new Rect(245, 45, 100, 30), minSize, 0.0f, 1.0f); maxSize = GUI.HorizontalSlider(new Rect(245, 85, 100, 30), maxSize, 0.0f, 1.0f); } } ``` -------------------------------- ### Example implementation of IPostBuildPlayerScriptDLLs Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityeditor/build/ipostbuildplayerscriptdlls/onpostbuildplayerscriptdlls Example class implementing IPostBuildPlayerScriptDLLs. It logs the build platform and output path in the OnPostBuildPlayerScriptDLLs callback. ```csharp using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; using UnityEngine; class MyCustomBuildProcessor : IPostBuildPlayerScriptDLLs { public int callbackOrder { get { return 0; } } public void OnPostBuildPlayerScriptDLLs(BuildReport report) { Debug.Log("MyCustomBuildProcessor.OnPostBuildPlayerScriptDLLs for target " + report.summary.platform + " at path " + report.summary.outputPath); } } ``` -------------------------------- ### shadowCascade4Split Property Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/qualitysettings/shadowcascade4split Gets or sets the normalized cascade start position for a 4 cascade setup. Each member of the vector defines the normalized position of the corresponding cascade with respect to Zero. ```APIDOC ## shadowCascade4Split ### Description Gets or sets the normalized cascade start position for a 4 cascade setup. Each member of the vector defines the normalized position of the corresponding cascade with respect to Zero. ### Definition - **Type:** Property - **Namespace:** UnityEngine - **Assembly:** UnityEngine.CoreModule ### Syntax ```csharp public static Vector3 shadowCascade4Split { get; set; } ``` ### Remarks Additional Resources: Quality Settings. ``` -------------------------------- ### Create launchUnityHub.cmd (Windows) Source: https://docs.unity.com/en-us/engine/6000.6/manual/get-started/install-and-upgrade/ent-deployment/ent-web-proxies/ent-proxy-cmd-file Batch file to set HTTP_PROXY, HTTPS_PROXY, and optionally NO_PROXY and NODE_EXTRA_CA_CERTS, then launch the Unity Hub. Include only the required variables, add the proxy lines only when not using Automatic Proxy Configuration, and add the SSL certificate line only if the proxy uses SSL inspection. Ensure the Hub path matches the installation and use double quotes if the path contains spaces. ```batch @echo off REM *** NOTE: Add the next 3 lines only if you’re not using Automatic Proxy Configuration set HTTP_PROXY=http://:@:8080 set HTTPS_PROXY=http://:@:8080 set NO_PROXY= REM *** NOTE: Add the following line only if your web proxy uses SSL inspection set NODE_EXTRA_CA_CERTS= start "" "C:\Program Files\Unity Hub\Unity Hub.exe" ``` -------------------------------- ### Set LensFlare fadeSpeed in C# Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/lensflare/fadespeed Sets the fadeSpeed property of a LensFlare component to 0.5f in the Start method. The example is intended to increment the strength of the lens flare as a Transform gets closer to it. ```csharp using UnityEngine; public class Example : MonoBehaviour { // Increments the strenght of the Lensflare lf when the Transform tr // gets closer to the Lens flare public LensFlare lf; public Transform tr; void Start() { lf.fadeSpeed = 0.5f; } } ``` -------------------------------- ### Example coroutine using AsyncOperation Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/asyncoperation A MonoBehaviour example that starts a coroutine, loads a resource asynchronously, yields on the AsyncOperation, and logs the start and end of the example. ```csharp using System.Collections; using UnityEngine; public class ExampleClass : MonoBehaviour { public void Start() { StartCoroutine(Example_AsyncTests()); } public IEnumerator Example_AsyncTests() { Debug.Log("Start of AsyncLoad Example"); var load = UnityEngine.Resources.LoadAsync(""); yield return load; yield return null; Debug.Log("End of AsyncLoad Example"); } } ``` -------------------------------- ### Linux: Example path to Unity Editor Source: https://docs.unity.com/en-us/engine/6000.6/manual/get-started/install-and-upgrade/licenses-and-activation/managing-your-unity-license Example of the full path to the Unity Editor application when installed to the home directory. ```command /home//Unity/Hub/Editor//Unity ``` -------------------------------- ### WebCamTexture.deviceName Property Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/webcamtexture/devicename Sets or gets the name of the device to use for the WebCamTexture. This property only has an effect when set while the camera is not running. The example shows how to set the device name to the first available device and start playing. ```APIDOC ## WebCamTexture.deviceName Property ### Description Sets or gets the name of the device to use for the WebCamTexture. This property only has an effect when set while the camera is not running. The example shows how to set the device name to the first available device and start playing. ### Definition - **Type:** Property - **Namespace:** UnityEngine - **Assembly:** UnityEngine.AudioModule ### Syntax ```csharp public string deviceName { get; set; } ``` ### Remarks This only has an effect when set while the camera is not running. **Note:** If you want to use WebCamTexture to get the camera stream from a device connected through Unity Remote, you must initialize it through the constructor. It's not possible to change the device using WebCamTexture.deviceName from regular to remote devices and vice versa. ### Example ```csharp // Sets the device of the WebCamTexture to the first one available and starts playing it using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { void Start() { WebCamDevice[] devices = WebCamTexture.devices; WebCamTexture webcamTexture = new WebCamTexture(); if (devices.Length > 0) { webcamTexture.deviceName = devices[0].name; webcamTexture.Play(); } } } ``` ``` -------------------------------- ### Example: Using Client.Add to install a package Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityeditor/packagemanager/client/add A MonoBehaviour example that calls Client.Add with a package name, then polls the AddRequest status in Update to log progress, success, or failure. ```csharp using System; using UnityEngine; using UnityEditor.PackageManager; using UnityEditor.PackageManager.Requests; [ExecuteInEditMode] public class PackageManagerClientAddExample : MonoBehaviour { AddRequest m_AddRequest; const string k_ValidPackageName = "com.unity.textmeshpro"; void Start() { Debug.Log("Adding a package via Client.Add..."); m_AddRequest = Client.Add(k_ValidPackageName); } void Update() { if (m_AddRequest != null) { switch (m_AddRequest.Status) { case StatusCode.InProgress: Debug.Log("Operation in progress..."); return; case StatusCode.Success: Debug.Log($"Successfully installed {k_ValidPackageName}"); m_AddRequest = null; break; case StatusCode.Failure: Debug.LogError($"Operation failed: {m_AddRequest.Error.message}"); m_AddRequest = null; break; } } } } ``` -------------------------------- ### Example: Creating custom settings and registering AssetSettingsProviders Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityeditor/assetsettingsprovider/ctor This example shows how to create a custom ScriptableObject settings asset, define a custom editor, and register three AssetSettingsProviders using different creation methods: from file path, from settings object, and from a functor. It also demonstrates how to register search keywords from the settings properties. ```csharp using UnityEditor; using UnityEngine; // Create a new type of Settings Asset. class MyCustomSettings : ScriptableObject { public const string k_MyCustomSettingsPath = "Assets/Editor/MyCustomSettings.asset"; [SerializeField] private int m_Number; [SerializeField] private string m_SomeString; internal static SerializedObject GetSettings() { var settings = AssetDatabase.LoadAssetAtPath(k_MyCustomSettingsPath); if (settings == null) { settings = ScriptableObject.CreateInstance(); settings.m_Number = 42; settings.m_SomeString = "The answer to the universe"; AssetDatabase.CreateAsset(settings, k_MyCustomSettingsPath); } return new SerializedObject(settings); } } [CustomEditor(typeof(MyCustomSettings))] class MyCustomSettingsEditor : Editor { // Nothing to do. This uses the Generic Editor to display MyCustomSettings properties } class AssetSettingsProviderRegister { [SettingsProvider] public static SettingsProvider CreateFromFilePath() { // Create an AssetSettingsProvider from a file path: var provider = AssetSettingsProvider.CreateProviderFromAssetPath("Project/AssetSettings/FromFile", MyCustomSettings.k_MyCustomSettingsPath); // Register keywords from the properties of MyCustomSettings provider.keywords = SettingsProvider.GetSearchKeywordsFromSerializedObject(new SerializedObject(AssetDatabase.LoadAllAssetsAtPath(MyCustomSettings.k_MyCustomSettingsPath))); return provider; } [SettingsProvider] public static SettingsProvider CreateFromSettingsObject() { // Create an AssetSettingsProvider from a settings object (UnityEngine.Object): var settingsObj = AssetDatabase.LoadAssetAtPath(MyCustomSettings.k_MyCustomSettingsPath); var provider = AssetSettingsProvider.CreateProviderFromObject("Project/AssetSettings/FromObject", settingsObj); // Register keywords from the properties of MyCustomSettings provider.keywords = SettingsProvider.GetSearchKeywordsFromSerializedObject(new SerializedObject(settingsObj)); return provider; } [SettingsProvider] public static SettingsProvider CreateFromSettingsFromFunctor() { // Create an AssetSettingsProvider from a functor that must return a UnityEngine.Object: var provider = new AssetSettingsProvider("Project/AssetSettings/FromFunctor", () => Editor.CreateEditor(AssetDatabase.LoadAssetAtPath(MyCustomSettings.k_MyCustomSettingsPath))); // Register keywords from the properties of MyCustomSettings provider.keywords = SettingsProvider.GetSearchKeywordsFromSerializedObject(new SerializedObject(AssetDatabase.LoadAllAssetsAtPath(MyCustomSettings.k_MyCustomSettingsPath))); return provider; } } ``` -------------------------------- ### BeginTrace() usage example Source: https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/rendering/graphicsstatecollection/begintrace Example MonoBehaviour that creates a GraphicsStateCollection, starts tracing in Start(), and ends tracing in OnDestroy(). ```csharp using UnityEngine; using UnityEngine.Rendering; public class BeginTraceExample : MonoBehaviour { public GraphicsStateCollection graphicsStateCollection; void Start() { graphicsStateCollection = new GraphicsStateCollection(); graphicsStateCollection.BeginTrace(); } void OnDestroy() { graphicsStateCollection.EndTrace(); } } ``` -------------------------------- ### Example: Create .alf file on macOS Source: https://docs.unity.com/en-us/engine/6000.6/manual/get-started/install-and-upgrade/licenses-and-activation/manual-license-activation/manual-activation-cmd-mac Example command for a 2022.2.0b4 Editor installed at /Applications/Unity/Hub/Editor/2022.2.0b4/Unity.app. The full path includes /Contents/MacOS/Unity. ```bash /Applications/Unity/Hub/Editor/2022.2.0b4/Unity.app/Contents/MacOS/Unity -batchmode -createManualActivationFile -logfile ``` -------------------------------- ### Built-In Render Pipeline Unlit Shader Example Source: https://docs.unity.com/en-us/engine/6000.6/manual/render-pipelines/universal-render-pipeline/introduction/installing-and-configuring-urp/upgrading-from-birp/birp-urp-custom-shader-upgrade-guide A simple unlit shader for the Built-In Render Pipeline, using a main texture and color property. This is the starting point for the upgrade guide to make it compatible with URP. ```ShaderLab Shader "Custom/UnlitShader" { Properties { [NoScaleOffset] _MainTex("Main Texture", 2D) = "white" {} _Color("Color", Color) = (1,1,1,1) } SubShader { Tags { "RenderType" = "Opaque" } Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct v2f { float4 position : SV_POSITION; float2 uv: TEXCOORD0; }; float4 _Color; sampler2D _MainTex; v2f vert(appdata_base v) { v2f o; o.position = UnityObjectToClipPos(v.vertex); o.uv = v.texcoord; return o; } fixed4 frag(v2f i) : SV_Target { fixed4 texel = tex2D(_MainTex, i.uv); return texel * _Color; } ENDCG } } } ```