### OS X: Install Example Projects via Command Line Source: https://docs.unity.cn/cn/current/Manual/InstallingUnity Installs Unity Example Projects to '/Users/Shared/Unity/Standard-Assets' on OS X using the `installer` command. ```bash sudo installer [-dumplog] -package Examples.pkg -target / ``` -------------------------------- ### Windows: Silent Example Project Installation Source: https://docs.unity.cn/cn/current/Manual/InstallingUnity Installs Unity example projects silently. The default installation path is provided for reference. ```bash UnityExampleProjectSetup.exe /S /D=E:\Development\Unity ``` -------------------------------- ### Example Git Repository URLs Source: https://docs.unity.cn/cn/current/Manual/UnityCloudBuildVcsGit Provides example URLs for accessing repositories on GitHub, Bitbucket, and GitLab. These examples illustrate the standard URL formats used for Git interactions. ```text https://github.com/youraccount/yourrepo git@bitbucket.org:youraccount/yourrepo.git git@gitlab.com:youracccount/yourrepo.git ``` -------------------------------- ### OS X: Install Standard Assets via Command Line Source: https://docs.unity.cn/cn/current/Manual/InstallingUnity Installs Unity Standard Assets to '/Applications/Unity/Standard Assets' on OS X using the `installer` command. ```bash sudo installer [-dumplog] -package StandardAssets.pkg -target / ``` -------------------------------- ### 修改 NetworkManager 连接配置 (C#) Source: https://docs.unity.cn/cn/current/Manual/UNetManager 通过在 NetworkManager 的派生类中修改 `Start()` 方法,可以在代码中提前设置自定义的网络连接参数,例如最大可靠消息数量、大小和发送队列大小,以及线程唤醒超时。这些参数可以覆盖 Inspector 中的默认设置。 ```csharp using UnityEngine; using UnityEngine.Networking; public class CustomManager : NetworkManager { // 尽早设置自定义连接参数,确保不会太晚实施这些参数 void Start() { customConfig = true; connectionConfig.MaxCombinedReliableMessageCount = 40; connectionConfig.MaxCombinedReliableMessageSize = 800; connectionConfig.MaxSentMessageQueueSize = 2048; connectionConfig.IsAcksLong = true; globalConfig.ThreadAwakeTimeout = 1; } } ``` -------------------------------- ### OS X: Install Unity Editor via Command Line Source: https://docs.unity.cn/cn/current/Manual/InstallingUnity Installs the Unity Editor package to the default '/Applications/Unity' folder on OS X using the `installer` command. ```bash sudo installer [-dumplog] -package Unity.pkg -target / ``` -------------------------------- ### Windows: Silent Unity Editor Installation Source: https://docs.unity.cn/cn/current/Manual/InstallingUnity Installs the Unity Editor silently without user prompts and specifies a custom installation directory. Useful for automated deployments. ```bash UnitySetup64.exe /S /D=E:\Development\Unity ``` -------------------------------- ### Discover and Start Display Subsystem in C# Source: https://docs.unity.cn/cn/current/Manual/xrsdk-runtime-discovery This script demonstrates how to find and start XR display subsystems at runtime. It scans for subsystem descriptors, filters them by a specified ID, and attempts to create and start matching display subsystems. Ensure the XR Subsystem package is installed. ```csharp using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.XR; using UnityEngine.XR; public class Display : MonoBehaviour { public string match = "Display0"; // Use this for initialization void Start () { List displays = new List(); SubsystemManager.GetSubsystemDescriptors(displays); Debug.Log("Number of display providers found: " + displays.Count); foreach (var d in displays) { Debug.Log("Scanning display id: " + d.id); if (d.id.Contains(match)) { Debug.Log("Creating display " + d.id); XRDisplaySubsystem dispInst = d.Create(); if (dispInst != null) { Debug.Log("Starting display " + d.id); dispInst.Start(); } } } } } ``` -------------------------------- ### Windows: Silent Standard Assets Installation Source: https://docs.unity.cn/cn/current/Manual/InstallingUnity Installs Unity Standard Assets silently, allowing specification of the Unity root folder. Ensure the path points to the directory containing the 'Editor' folder. ```bash UnityStandardAssetsSetup.exe /S /D=E:\Development\Unity ``` -------------------------------- ### Unity Accelerator CLI Help Source: https://docs.unity.cn/cn/current/Manual/UnityAccelerator Example output from running the Unity Accelerator command-line tool without any arguments, showing basic usage and version information. ```bash $ unity-accelerator Unity Accelerator v1.0.524+g96c5e18 Run on a local network to speed up transactions with Unity Services. ..... ``` -------------------------------- ### Example USS Selector for Hover State Source: https://docs.unity.cn/cn/current/Manual/UIB-getting-started-workflow Demonstrates how to create a USS selector to apply styles to elements when a specific condition, like hovering, is met. This example targets elements with the class '.my-button' and changes their color to blue on hover. ```uss .my-button:hover { color: blue; } ``` -------------------------------- ### Install AppX file via PowerShell Source: https://docs.unity.cn/cn/current/Manual/windowsstore-faq Instructions on how to install an AppX file on a Windows machine using Windows PowerShell. It includes the command to execute and notes on reinstalling or updating existing packages. ```powershell Add-AppxPackage .appx ``` -------------------------------- ### RangeInt.end Property Source: https://docs.unity.cn/cn/current/ScriptReference/RangeInt-end The 'end' property of the RangeInt struct represents the exclusive end index of the range. It is calculated by adding the 'length' to the 'start' index. For example, to get characters 'cde' from 'abcdef', the 'end' would be 2 (start) + 3 (length) = 5. ```csharp public int end ; ``` -------------------------------- ### Create AppX Package using Visual Studio Source: https://docs.unity.cn/cn/current/Manual/windowsstore-faq This guide explains how to create an AppX package from a Unity-built project using Visual Studio. It details the process of selecting 'Create App Packages', choosing build options, and preparing the package for deployment. ```powershell Add-AppDevPackage.ps1 ``` -------------------------------- ### StartUp Method Source: https://docs.unity.cn/cn/current/Manual/Tilemap-ScriptableTiles-Tile Handles the startup process for a tile. ```APIDOC ## StartUp Method ### Description Handles any special startup functionality for the Tile class. By default, this method has no special startup functionality. If `tileData.gameobject` is set, the tilemap will still instantiate and place it at the tile's position during startup. ### Method `public bool StartUp(Vector3Int location, ITilemap tilemap, GameObject go)` ### Parameters #### Path Parameters - **location** (Vector3Int) - The coordinates of the tile. - **tilemap** (ITilemap) - The ITilemap interface. - **go** (GameObject) - The GameObject associated with the tile. ### Endpoint N/A (This is a method within the Tile class) ### Request Example N/A ### Response - **return** (bool) - Returns false by default. ### Error Handling N/A ``` -------------------------------- ### Private Git Submodule SSH URL Configuration (Git) Source: https://docs.unity.cn/cn/current/Manual/UnityCloudBuildVcsGit When using private Git submodules, it's crucial to use SSH URLs in the .gitmodules file for authentication. This example shows the correct syntax for GitHub, Bitbucket, and GitLab. ```git git@github.com:youraccount/yourrepo.git ``` ```git git@bitbucket.org:youraccount/yourrepo.git ``` ```git git@gitlab.com:youracccount/yourrepo.git ``` -------------------------------- ### Install Unity Accelerator via Command Line (Linux/Mac) Source: https://docs.unity.cn/cn/current/Manual/UnityAccelerator This snippet demonstrates how to install the Unity Accelerator from the command line on Linux or Mac, including unattended installation with specified storage directories and registration tokens. It highlights the use of the `--help` flag for available options. ```bash sh --help sh --storagedir /path/to/storage --registration-token YOUR_TOKEN --mode unattended ``` -------------------------------- ### Create and Execute Unity Hub Launch Script (Bash) Source: https://docs.unity.cn/cn/current/Manual/upm-config-network This script creates a `launchUnityHub.command` file that sets proxy environment variables (HTTP_PROXY, HTTPS_PROXY) and launches Unity Hub. It then makes the script executable. Ensure you replace `proxy-url` with your actual proxy server URL and adjust the Unity Hub path if necessary. Paths with spaces must be enclosed in double quotes. ```bash #!/bin/bash export HTTP_PROXY=proxy-url export HTTPS_PROXY=proxy-url nohup "/Applications/Unity Hub.app/Contents/MacOS/Unity Hub" &>/dev/null & ``` -------------------------------- ### Getting Selected Asset GUIDs in Unity Source: https://docs.unity.cn/cn/current/ScriptReference/Selection This C# code snippet demonstrates how to get the GUIDs of the currently selected assets in the Unity Editor's Project window. It uses the `Selection.assetGUIDs` property. ```csharp using UnityEditor; public class AssetSelection { public static void PrintSelectedAssetGUIDs() { string[] guids = Selection.assetGUIDs; if (guids.Length > 0) { Debug.Log("Selected Asset GUIDs:"); foreach (string guid in guids) { Debug.Log("- " + guid); } } else { Debug.Log("No assets selected."); } } } ``` -------------------------------- ### Unity Accelerator CLI All Help Source: https://docs.unity.cn/cn/current/Manual/UnityAccelerator Command to display all available help text for the Unity Accelerator CLI. Recommended to pipe output to 'less' or redirect to a file. ```bash unity-accelerator --all-help ``` -------------------------------- ### Analyzing Unity Startup Time: UnityInitApplicationGraphics and UnityLoadApplication Source: https://docs.unity.cn/cn/current/Manual/performance-profiler-traces Investigates the Unity startup process by examining UnityInitApplicationGraphics and UnityLoadApplication methods. These methods are crucial for understanding how configuration, assets, and scripts impact application start-up time. UnityInitApplicationGraphics initializes graphics devices and Unity systems, including the Resources system. UnityLoadApplication handles loading the first scene, deserializing data, compiling shaders, and executing Awake callbacks. ```text UnityInitApplicationGraphics UnityLoadApplication ``` -------------------------------- ### Start Coroutine with Parameter - Unity C# Example Source: https://docs.unity.cn/cn/current/ScriptReference/Coroutine Shows how to initiate a coroutine 'WaitAndPrint' with a float parameter for the wait time. This example highlights starting a coroutine directly with an IEnumerator instance and executing functions in parallel. ```csharp using UnityEngine; using System.Collections; // In this example we show how to invoke a coroutine and execute // the function in parallel. Start does not need IEnumerator. public class ExampleClass : MonoBehaviour { private IEnumerator coroutine; void Start() { // - After 0 seconds, prints "Starting 0.0 seconds" // - After 0 seconds, prints "Coroutine started" // - After 2 seconds, prints "Coroutine ended: 2.0 seconds" print("Starting " + Time.time + " seconds"); // Start function WaitAndPrint as a coroutine. coroutine = WaitAndPrint(2.0f); StartCoroutine(coroutine); print("Coroutine started"); } private IEnumerator WaitAndPrint(float waitTime) { yield return new WaitForSeconds(waitTime); print("Coroutine ended: " + Time.time + " seconds"); } } ``` -------------------------------- ### DownloadHandlerBuffer Example: Get Text from Server Source: https://docs.unity.cn/cn/current/Manual/UnityWebRequest-CreatingDownloadHandlers This example demonstrates how to use DownloadHandlerBuffer to retrieve text data from a server. It sends a GET request and logs the downloaded text or any errors encountered. The downloaded data can be accessed as a string or a byte array. ```csharp using UnityEngine; using UnityEngine.Networking; using System.Collections; public class MyBehaviour : MonoBehaviour { void Start() { StartCoroutine(GetText()); } IEnumerator GetText() { UnityWebRequest www = new UnityWebRequest("https://www.my-server.com"); www.downloadHandler = new DownloadHandlerBuffer(); yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) { Debug.Log(www.error); } else { // 以文本形式显示结果 Debug.Log(www.downloadHandler.text); // 或者获取二进制数据形式的结果 byte[] results = www.downloadHandler.data; } } } ``` -------------------------------- ### Device Simulator Setup Source: https://docs.unity.cn/cn/current/Manual/UpgradeGuide2021LTS Instructions on how to set up and use the Device Simulator in the Unity Editor. ```APIDOC ## Device Simulator Setup ### Description Instructions on how to set up and use the Device Simulator in the Unity Editor by adding the `UnityEngine.Device` namespace. ### Method N/A (Configuration Guide) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ### Usage Details Add the `UnityEngine.Device` namespace to the Screen, Application, and SystemInfo classes: `UnityEngine.Device.Screen;` `UnityEngine.Device.Application;` `UnityEngine.Device.SystemInfo;` To switch to `UnityEngine.Device`, add the following logic to each script you want to use with the simulator: ` using Screen = UnityEngine.Device.Screen; using Application = UnityEngine.Device.Application; using SystemInfo = UnityEngine.Device.SystemInfo; ` The new namespace `UnityEngine.Device` transitions smoothly from Simulator (when in Editor) to actual device API with a runtime build. ``` -------------------------------- ### Unity Accelerator Dashboard CLI Commands Source: https://docs.unity.cn/cn/current/Manual/UnityAccelerator Examples of using the Unity Accelerator CLI for dashboard-related operations, including setting a new account password and listing existing accounts. ```bash $ unity-accelerator dashboard password newaccount Password: **** Again: **** $ unity-accelerator dashboard list admin newaccount $ unity-accelerator dashboard url http://172.18.37.249:8080/dashboard/ ``` -------------------------------- ### Get Installer Name - Unity C# Source: https://docs.unity.cn/cn/current/ScriptReference/Application-installerName Retrieves the name of the installer (store or package) for the Unity application. This is a read-only property and does not require any external dependencies. ```csharp public static string installerName; ``` -------------------------------- ### SceneView.currentDrawingSceneView Source: https://docs.unity.cn/cn/current/ScriptReference/SceneView-currentDrawingSceneView Gets the SceneView that is currently drawing. This is useful for multi-SceneView setups. ```APIDOC ## SceneView.currentDrawingSceneView ### Description Gets the SceneView that is currently drawing. This is useful for multi-SceneView setups. ### Property `public static SceneView currentDrawingSceneView` ### Example ```csharp // Get the currently drawing SceneView SceneView sv = SceneView.currentDrawingSceneView; if (sv != null) { Debug.Log("Current SceneView is: " + sv.title); } ``` ``` -------------------------------- ### Windows: Silent Unity Editor Uninstallation Source: https://docs.unity.cn/cn/current/Manual/InstallingUnity Uninstalls the Unity Editor silently from the command line. Ensure the current working directory is not within the Unity installation path to avoid issues. ```bash Uninstall.exe /S ``` -------------------------------- ### Sample Object Example Source: https://docs.unity.cn/cn/current/Manual/upm-manifestPkg Defines an example included in the package, specifying its display name, a brief description, and its path relative to the 'Samples~' folder. ```json { "displayName": "", "description": "", "path": "Samples~/" } ``` -------------------------------- ### Get Application Build GUID Source: https://docs.unity.cn/cn/current/ScriptReference/Application-buildGUID Retrieves the unique identifier (GUID) for the current Unity build. This property is read-only and does not require any parameters. It's useful for identifying specific build versions. ```csharp public static string buildGUID; ``` -------------------------------- ### Initialize Unity Application and Setup Source: https://docs.unity.cn/cn/current/Manual/windowsstore-appcallbacks Initializes the Unity application, sets up orientation, and establishes the AppCallbacks instance. It handles the launching of the application and initializes the Unity engine with provided arguments, including suppressing system overlays for a fullscreen experience. ```cpp App::App() { InitializeComponent(); SetupOrientation(); m_AppCallbacks = ref new AppCallbacks(); } void App::OnLaunched(LaunchActivatedEventArgs^ e) { m_SplashScreen = e->SplashScreen; InitializeUnity(e->Arguments); } void App::InitializeUnity(String^ args) { ApplicationView::GetForCurrentView()->SuppressSystemOverlays = true; m_AppCallbacks->SetAppArguments(args); auto rootFrame = safe_cast(Window::Current->Content); // 当窗口已包含内容时,请勿重复初始化应用程序, // 仅确保窗口处于活动状态 if (rootFrame == nullptr && !m_AppCallbacks->IsInitialized()) { rootFrame = ref new Frame(); Window::Current->Content = rootFrame; # if !UNITY_HOLOGRAPHIC Window::Current->Activate(); # endif rootFrame->Navigate(TypeName(MainPage::typeid )); } Window::Current->Activate(); } ``` -------------------------------- ### Install InputSystem Package (Unity) Source: https://docs.unity.cn/cn/current/Manual/class-PlayerSettingsAndroid Installs the preview Input System package for Unity, which offers a newer approach to handling user input compared to the default Input Manager. ```bash Install the InputSystem package. ``` -------------------------------- ### Unity iOS Target GUID: Old vs. New Methods Source: https://docs.unity.cn/cn/current/Manual/StructureOfXcodeProject Demonstrates the deprecated methods for getting Unity iOS target GUIDs and their recommended replacements in C#. ```csharp // Deprecated methods string targetGuid = proj.TargetGuidByName("Unity-iPhone"); string targetGuid = proj.TargetGuidByName(PBXProject.GetUnityTargetName()); // Use one of the following calls instead string targetGuid = proj.GetUnityFrameworkTargetGuid(); string targetGuid = proj.GetUnityMainTargetGuid(); ``` -------------------------------- ### Unity Integrations - General Information Source: https://docs.unity.cn/cn/current/Manual/UnityIntegrations Overview of Unity Integrations, including prerequisites, supported tools, and limitations. ```APIDOC ## Unity Integrations Unity Integrations allow connecting Unity services to non-Unity tools. To add an integration, you must be a project Owner or Manager. ### Supported Non-Unity Tools - Webhooks - Discord - Slack - Email - JIRA - Trello ### Integration Limitations - **Unity Personal:** Limited to one integration for all events. - **Unity Teams, Plus, Pro:** Up to 100 integrations. Integrations are disabled if the subscription expires but can be re-enabled. ### Adding an Integration 1. Log in to the Unity Services Dashboard. 2. Select your project. 3. Navigate to **Settings** > **Integrations**. 4. Click the **NEW INTEGRATION** button. 5. Select the integration and the trigger events. 6. Configure integration-specific options. ``` -------------------------------- ### Get Camera Count in Scene (C#) Source: https://docs.unity.cn/cn/current/ScriptReference/Camera-allCamerasCount This C# script demonstrates how to access the Camera.allCamerasCount property to get the number of cameras in the current Unity scene. It prints the count to the console when the script starts. ```csharp using UnityEngine; public class ExampleScript : MonoBehaviour { private int count; void Start() { count = Camera.allCamerasCount; print("We've got " + count + " cameras"); } } ``` -------------------------------- ### Unity Package Manifest Example Source: https://docs.unity.cn/cn/current/Manual/upm-manifestPkg A comprehensive example of a Unity package manifest file, demonstrating the usage of various optional properties like name, version, displayName, description, unity, unityRelease, URLs, dependencies, keywords, and author. ```json { "name": "com.[company-name].[package-name]", "version": "1.2.3", "displayName": "Package Example", "description": "This is an example package", "unity": "2019.1", "unityRelease": "0b5", "documentationUrl": "https://example.com/", "changelogUrl": "https://example.com/changelog.html", "licensesUrl": "https://example.com/licensing.html", "dependencies": { "com.[company-name].some-package": "1.0.0", "com.[company-name].other-package": "2.0.0" }, "keywords": [ "keyword1", "keyword2", "keyword3" ], "author": { "name": "Unity", "email": "unity@example.com", "url": "https://www.unity3d.com" } } ``` -------------------------------- ### Device Layout Example - Unity Input System Source: https://docs.unity.cn/cn/current/Manual/xrsdk-input An example demonstrating how to provide a device layout description as part of an input provider to allow users to bind and access device properties via the new input system. ```json { "name": "MyControllerLayout", "extend": "GenericController", "controls": { "leftStick": { "type": "Stick", "path": "/MyController/LeftStick", "axis": { "x": {"type": "Vector2", "path": "/MyController/LeftStick/x"}, "y": {"type": "Vector2", "path": "/MyController/LeftStick/y"} } }, "trigger": { "type": "Button", "path": "/MyController/Trigger" } } } ``` -------------------------------- ### Get Application Install Mode (C#) Source: https://docs.unity.cn/cn/current/ScriptReference/Application-installMode This C# code snippet shows how to access the `installMode` property of the `Application` class to retrieve the current installation mode of the Unity application. This property is read-only. ```csharp public static ApplicationInstallMode installMode; ``` -------------------------------- ### InitializeOnLoad 回调时序更改示例 (C#) Source: https://docs.unity.cn/cn/current/Manual/UpgradeGuide20172 演示了 Unity 2017.2 中 InitializeOnLoad 回调时序的变化。在 2017.2 之前,静态构造函数可能在对象构造函数之前调用。更改后,对象构造函数总是在静态构造函数之前调用,解决了潜在的无效对象状态问题。 ```csharp using UnityEngine; [System.Serializable] public class SomeClass { public SomeClass() { Debug.Log("SomeClass constructor"); } } public class SomeMonoBehaviour : MonoBehaviour { public SomeClass SomeClass; } [InitializeOnLoad] public class SomeStaticClass { static SomeStaticClass() { Debug.Log("SomeStaticClass static constructor"); } } ``` -------------------------------- ### Start Coroutine - Unity C# Example Source: https://docs.unity.cn/cn/current/ScriptReference/Coroutine Demonstrates how to start and yield a coroutine named 'WaitAndPrint' using Unity's MonoBehaviour.StartCoroutine. The coroutine pauses execution for a specified duration using new WaitForSeconds(5) before printing a message. ```csharp using UnityEngine; using System.Collections; public class ExampleClass : MonoBehaviour { IEnumerator WaitAndPrint() { // suspend execution for 5 seconds yield return new WaitForSeconds(5); print("WaitAndPrint " + Time.time); } IEnumerator Start() { print("Starting " + Time.time); // Start function WaitAndPrint as a coroutine yield return StartCoroutine("WaitAndPrint"); print("Done " + Time.time); } } ``` -------------------------------- ### Perforce URL Syntax Examples Source: https://docs.unity.cn/cn/current/Manual/UnityCloudBuildVcsPerforce Provides examples of valid URL formats for connecting to a Perforce server using either HTTPS or SSL protocols. ```text https://127.0.0.1:1667 ssl:127.0.0.1:167 ``` -------------------------------- ### 为 Unity Hub 设置代理环境变量 (Windows) Source: https://docs.unity.cn/cn/current/Manual/upm-config-network 创建一个 Windows 命令文件 (`.cmd`) 来设置 `HTTP_PROXY` 和 `HTTPS_PROXY` 环境变量,然后启动 Unity Hub。这会将代理设置应用于从 Hub 启动的所有 Unity Editor 进程。 ```batch @echo off set HTTP_PROXY=proxy-url set HTTPS_PROXY=proxy-url start "" "C:\Program Files\Unity Hub\Unity Hub.exe" ``` -------------------------------- ### Get Automatic Texture Format for Platform Source: https://docs.unity.cn/cn/current/ScriptReference/TextureImporter This example shows how to get the default texture format that Unity would automatically select for a given platform using `GetAutomaticFormat`. This can be useful for querying Unity's default import behavior. ```csharp using UnityEditor; public class GetAutoFormat { public static void LogAutomaticFormat(string texturePath) { TextureImporter importer = AssetImporter.GetAtPath(texturePath) as TextureImporter; if (importer != null) { // Get the automatic format for the current platform // Alternatively, you can specify a BuildTarget enum TextureImporterFormat format = importer.GetAutomaticFormat(EditorUserBuildSettings.activeBuildTarget); Debug.Log("Automatic format for current platform: " + format.ToString()); } } } ``` -------------------------------- ### Help.ShowHelpPage Source: https://docs.unity.cn/cn/current/ScriptReference/Help Displays a specified help page. The 'page' parameter should be a URL to the help page, typically starting with 'file://'. If the URL starts with 'file:///unity/', it points to a Unity help page. ```APIDOC ## Help.ShowHelpPage ### Description Displays the help page. `page` should be the URL of the help page, usually starting with `file://`. If `page` starts with `file:///unity/`, this page points to the Unity help page. See also: Help.ShowHelpForObject. ### Method `public static void ShowHelpPage (string page);` ### Parameters #### Path Parameters - **page** (string) - Required - The URL of the help page. ``` -------------------------------- ### Unity iOS Target GUID: Reflection for Compatibility Source: https://docs.unity.cn/cn/current/Manual/StructureOfXcodeProject A C# code snippet using reflection to get Unity iOS target GUIDs, ensuring compatibility with older and newer Unity versions by checking for the existence of new methods. ```csharp string mainTargetGuid; string unityFrameworkTargetGuid; var unityMainTargetGuidMethod = proj.GetType().GetMethod("GetUnityMainTargetGuid"); var unityFrameworkTargetGuidMethod = proj.GetType().GetMethod("GetUnityFrameworkTargetGuid"); if (unityMainTargetGuidMethod != null && unityFrameworkTargetGuidMethod != null) { mainTargetGuid = (string)unityMainTargetGuidMethod.Invoke(proj, null); unityFrameworkTargetGuid = (string)unityFrameworkTargetGuidMethod.Invoke(proj, null); } else { mainTargetGuid = proj.TargetGuidByName ("Unity-iPhone"); unityFrameworkTargetGuid = mainTargetGuid; } ``` -------------------------------- ### 注册 XRSDKPreInit 回调 (C++) Source: https://docs.unity.cn/cn/current/Manual/xrsdk-pre-init-interface 此函数在运行时初始化早期被调用,用于注册 UnityXRPreInitProvider,以便为引擎提供早期初始化所需的信息。 ```cpp XRSDKPreInit(IUnityInterfaces * interfaces) { IUnityXRPreInit* preInit = (IUnityXRPreInit*)interfaces->GetInterface(GetUnityInterfaceGUID()); UnityXRPreInitProvider provider = { 0 }; provider.userData = nullptr; provider.GetPreInitFlags = GetPreInitFlags; provider.GetGraphicsAdapterId = GetGraphicsAdapterId; provider.GetVulkanInstanceExtensions = GetVulkanInstanceExtensions; provider.GetVulkanDeviceExtensions = GetVulkanDeviceExtensions; preInit->RegisterPreInitProvider(&provider); } ``` -------------------------------- ### Instanced Vertex and Fragment Shader Example (Unity Shader) Source: https://docs.unity.cn/cn/current/Manual/gpu-instancing-shader Shows how to create an instanced Vertex and Fragment Shader, enabling per-instance color variations. This example requires manual setup of instance IDs using `UNITY_SETUP_INSTANCE_ID`. ```Unity Shader Shader "Custom/SimplestInstancedShader" { Properties { _Color ("Color", Color) = (1, 1, 1, 1) } SubShader { Tags { "RenderType"="Opaque" } LOD 100 Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #pragma multi_compile_instancing #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; UNITY_VERTEX_INPUT_INSTANCE_ID }; struct v2f { float4 vertex : SV_POSITION; UNITY_VERTEX_INPUT_INSTANCE_ID // use this to access instanced properties in the fragment shader. }; UNITY_INSTANCING_BUFFER_START(Props) UNITY_DEFINE_INSTANCED_PROP(float4, _Color) UNITY_INSTANCING_BUFFER_END(Props) v2f vert(appdata v) { v2f o; UNITY_SETUP_INSTANCE_ID(v); UNITY_TRANSFER_INSTANCE_ID(v, o); o.vertex = UnityObjectToClipPos(v.vertex); return o; } fixed4 frag(v2f i) : SV_Target { UNITY_SETUP_INSTANCE_ID(i); return UNITY_ACCESS_INSTANCED_PROP(Props, _Color); } ENDCG } } } ``` -------------------------------- ### Unity External Tools Preferences for Android Source: https://docs.unity.cn/cn/current/Manual/android-sdksetup Demonstrates how to configure Unity to use custom Android SDK, NDK, and JDK installations via the Preferences menu. This allows users to manage their build environment by specifying installation paths. ```Unity Editor Preferences 1. In Unity, select **Edit** > **Preferences** (macOS: **Unity** > **Preferences**). 2. In the left navigation column, select **External Tools**. 3. The Android section of the External Tools panel contains entries for **JDK** , **SDK** , **NDK** , and **Gradle**. 4. To customize the installation for any of these dependencies, disable the dependency’s respective **…installed with Unity (recommended)** checkbox then click **Browse** and select the installation folder for the custom dependency. ``` -------------------------------- ### Unity Package Manifest Example (JSON) Source: https://docs.unity.cn/cn/current/Manual/upm-manifestPkg A sample package.json file demonstrating the structure and common properties used to define a Unity package. This includes mandatory fields like 'name' and 'version', as well as recommended fields for user-friendliness and compatibility. ```JSON { "name": "com.example.package", "version": "1.0.0", "displayName": "My Example Package", "description": "A sample package demonstrating manifest properties.\nIt supports UTF-8 characters like \u25AA bullets.", "unity": "2021.3", "keywords": [ "example", "unity" ], "author": { "name": "Example Inc.", "email": "contact@example.com" }, "dependencies": { "com.unity.editorcorlytics": "1.0.0" } } ``` -------------------------------- ### 启动瓦片 - Unity C# Source: https://docs.unity.cn/cn/current/Manual/Tilemap-ScriptableTiles-TileBase 介绍了 StartUp 方法,该方法在瓦片地图首次更新时为每个瓦片调用。它允许为瓦片地图上的瓦片执行任何初始化逻辑,并接收瓦片位置、ITilemap 实例和游戏对象作为参数。 ```csharp public bool StartUp(Vector3Int location, ITilemap tilemap, GameObject go) ``` -------------------------------- ### Animator.recorderStopTime Source: https://docs.unity.cn/cn/current/ScriptReference/Animator-recorderStopTime Get the end time of a recorded clip relative to when recording started. Returns -1 if the buffer has not been initialized. ```APIDOC ## Animator.recorderStopTime ### Description Returns the end time of the recorded clip relative to the time recording was started. For example, if recording started at second 10 and ended at second 15, the value would be 5. If the buffer has not been initialized (StartRecording has not been called), the value of this property will be -1. See also: recorderStartTime. ### Method GET ### Endpoint /api/animator/recorderStopTime ### Parameters #### Query Parameters - **version** (string) - Optional - The Unity version to query. ### Request Example # No request body needed for a GET operation. ### Response #### Success Response (200) - **recorderStopTime** (float) - The end time of the recorded clip relative to the start time. #### Response Example ```json { "recorderStopTime": 5.0 } ``` ``` -------------------------------- ### Initiate Purchase in Unity C# Source: https://docs.unity.cn/cn/current/Manual/UnityIAPInitiatingPurchases This C# code snippet demonstrates how to call the `InitiatePurchase` method on the `IStoreController` to start the purchase process when a user clicks a buy button. It takes a product ID as input. ```csharp public void OnPurchaseClicked(string productId) { controller.InitiatePurchase(productId); } ``` -------------------------------- ### RenderSettings.fogStartDistance - Unity C# Source: https://docs.unity.cn/cn/current/ScriptReference/RenderSettings-fogStartDistance Gets or sets the starting distance for linear fog effects. This is a static property of the RenderSettings class. ```csharp public static float fogStartDistance; ``` -------------------------------- ### ParticleSystem.useAutoRandomSeed - C# Example Source: https://docs.unity.cn/cn/current/ScriptReference/ParticleSystem-useAutoRandomSeed This snippet demonstrates how to get and set the `useAutoRandomSeed` property of a ParticleSystem component in Unity using C#. ```csharp using UnityEngine; public class ParticleSeedControl : MonoBehaviour { public ParticleSystem particleSystem; void Start() { if (particleSystem == null) { particleSystem = GetComponent(); } // Example: Enable auto random seed particleSystem.useAutoRandomSeed = true; Debug.Log("Particle system auto random seed is: " + particleSystem.useAutoRandomSeed); // Example: Disable auto random seed and set a custom seed // particleSystem.useAutoRandomSeed = false; // particleSystem.randomSeed = 12345; // Debug.Log("Particle system auto random seed is: " + particleSystem.useAutoRandomSeed + ", custom seed is: " + particleSystem.randomSeed); } } ``` -------------------------------- ### Signing and Packaging for Mac App Store Source: https://docs.unity.cn/cn/current/Manual/UnityIAPAppleConfiguration Commands for signing and packaging a Unity application for the Mac App Store. This includes using `codesign` to sign the application bundle and `productbuild` to create an installer package. ```bash # Codesign the Unity purchasing bundle codesign -f --deep -s "3rd Party Mac Developer Application: " your.app/Contents/Plugins/unitypurchasing.bundle # Codesign the entire application codesign -f --deep -s "3rd Party Mac Developer Application: " your.app # Create an installer package productbuild --component your.app /Applications --sign "3rd Party Mac Developer Installer: " your.pkg ``` -------------------------------- ### Assembly Definition with GUID References and Exclude Platforms Source: https://docs.unity.cn/cn/current/Manual/AssemblyDefinitionFileFormat Defines an assembly named 'BeeAssembly' with references to other assemblies by GUID and specifies platforms to exclude (iOS, macOSStandalone, tvOS). It includes precompiled references and define constraints similar to the name-based example. ```json { "name": "BeeAssembly", "references": [ "GUID:17b36165d09634a48bf5a0e4bb27f4bd", "GUID:b470eee7144904e59a1064b70fa1b086", "GUID:2bafac87e7f4b9b418d9448d219b01ab", "GUID:27619889b8ba8c24980f49ee34dbb44a", "GUID:0acc523941302664db1f4e527237feb3" ], "includePlatforms": [], "excludePlatforms": [ "iOS", "macOSStandalone", "tvOS" ], "allowUnsafeCode": false, "overrideReferences": true, "precompiledReferences": [ "Newtonsoft.Json.dll", "nunit.framework.dll" ], "autoReferenced": false, "defineConstraints": [ "UNITY_2019", "UNITY_INCLUDE_TESTS" ], "versionDefines": [ { "name": "com.unity.ide.vscode", "expression": "[1.7,2.4.1]", "define": "MY_SYMBOL" }, { "name": "com.unity.test-framework", "expression": "[2.7.2-preview.8]", "define": "TESTS" } ], "noEngineReferences": false } ``` -------------------------------- ### 在 Unity Editor 启动时运行脚本 Source: https://docs.unity.cn/cn/current/Manual/RunningEditorCodeOnLaunch 使用 InitializeOnLoad 属性和静态构造函数,可以在 Unity Editor 启动时自动执行指定的脚本代码。此方法适用于需要项目启动时执行初始化操作的场景。 ```csharp using UnityEngine; using UnityEditor; [InitializeOnLoad] public class Startup { static Startup() { Debug.Log("Up and running"); } } ``` -------------------------------- ### ProfilerMarker.Begin Source: https://docs.unity.cn/cn/current/ScriptReference/Unity.Profiling.ProfilerMarker Starts profiling a segment of code marked with a custom name defined by this ProfilerMarker instance. Always end a profiled code segment started with Begin using End. Code marked with Begin and End appears in the Profiler hierarchy. Use Recorder to get per-frame timings in Player. ```APIDOC ## ProfilerMarker.Begin ### Description Starts profiling a segment of code marked with a custom name defined by this ProfilerMarker instance. Always end a profiled code segment started with Begin using End. Code marked with Begin and End appears in the Profiler hierarchy. Use Recorder to get per-frame timings in Player. **Note:** Begin and End are thread-safe and can be used in jobs code. ### Method **Overload 1:** `void Begin()` **Overload 2:** `void Begin(Object contextUnityObject)` ### Endpoint N/A (This is a code method, not a web endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp using Unity.Profiling; public class MySystemClass { static ProfilerMarker s_PreparePerfMarker = new ProfilerMarker("MySystem.Prepare"); public void UpdateLogic() { s_PreparePerfMarker.Begin(); // ... s_PreparePerfMarker.End(); } } ``` ### Response #### Success Response (N/A - This is a method call) None #### Response Example None ### Additional Notes Begin is conditionally compiled using the ConditionalAttribute. Therefore, it has zero overhead when deployed in a non-development build. See Also: ProfilerMarker.End, Recorder, ProfilerCPU. ``` -------------------------------- ### RenderSettings.fogStartDistance Source: https://docs.unity.cn/cn/current/ScriptReference/RenderSettings-fogStartDistance Sets or gets the starting distance for linear fog effects in Unity. This property is part of the RenderSettings class and is used in conjunction with fogEndDistance and fogMode. ```APIDOC ## RenderSettings.fogStartDistance ### Description Linear fog's start distance. ### Method `public static float fogStartDistance` ### Endpoint N/A (This is a static property within the Unity Engine) ### Parameters No parameters for direct access, but the property itself can be read or written to. ### Request Example ```csharp // Setting the fog start distance RenderSettings.fogStartDistance = 50.0f; // Getting the fog start distance float currentFogStartDistance = RenderSettings.fogStartDistance; ``` ### Response #### Success Response - **fogStartDistance** (float) - The current value of the fog start distance. #### Response Example ```json { "fogStartDistance": 50.0 } ``` ### Remarks Linear fog mode uses both the fog start and end distances. See Also: RenderSettings.fogEndDistance, RenderSettings.fogMode. ``` -------------------------------- ### Trello Integration Configuration Source: https://docs.unity.cn/cn/current/Manual/UnityIntegrations Instructions for setting up Trello integration for commenting on cards or creating new cards. ```APIDOC ## Trello Integration Configure Trello integration for interacting with Trello cards. ### Features: - **Collaborate:** Add comments to existing cards by including the card's URL in the publish message. - **Cloud Diagnostics:** Automatically creates and adds new cards to your board upon receiving a user report. ### Configuration Steps: 1. Create a Trello Integration in the Unity Services Dashboard (**Settings > Integrations**). 2. Select services and events, then click **Next**. 3. Sign into Trello and authorize Unity to make changes to your boards. 4. Configure the integration, specifying the board and list for posting, and save settings. ``` -------------------------------- ### Unmanaged Function Pointers Example in C# Source: https://docs.unity.cn/cn/current/Manual/CSharpCompiler This C# code snippet demonstrates how to use unmanaged function pointers in Unity, specifically targeting Windows platforms. It requires enabling 'unsafe' code in Player Settings. The example uses P/Invoke to load 'kernel32.dll' and get a pointer to the 'GetCurrentThreadId' function, then calls it using a C# unmanaged function pointer. ```csharp using System; using System.Runtime.InteropServices; using UnityEngine; public class UnmanagedFunctionPointers : MonoBehaviour { [DllImport("kernel32.dll")] static extern IntPtr LoadLibrary(string lpLibFileName); [DllImport("kernel32.dll")] static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName); // You must enable "Allow ‘unsafe’ code" in the Player Settings unsafe void Start() { #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN // This example is only valid on Windows // Get a pointer to an unmanaged function IntPtr kernel32 = LoadLibrary("kernel32.dll"); IntPtr getCurrentThreadId = GetProcAddress(kernel32, "GetCurrentThreadId"); // The unmanaged calling convention delegate* unmanaged[Stdcall] getCurrentThreadIdUnmanagedStdcall = (delegate* unmanaged[Stdcall])getCurrentThreadId; Debug.Log(getCurrentThreadIdUnmanagedStdcall()); #endif } } ``` -------------------------------- ### Configure Cache Server Path and Size (Command Line) Source: https://docs.unity.cn/cn/current/Manual/CacheServer Demonstrates how to configure the cache server's path and maximum size using command-line arguments. This allows customization of storage location and limits, ensuring efficient use of disk space. ```bash ./RunOSX.command --path ~/mycachePath --size 2000000000 ``` ```bash ./RunOSX.command --path ~/mycachePath --port 8199 --nolegacy ``` -------------------------------- ### BuildPipeline.WriteBootConfig Source: https://docs.unity.cn/cn/current/ScriptReference/BuildPipeline Writes out a "boot.config" file that contains configuration information for the very early stages of engine startup. ```APIDOC ## BuildPipeline.WriteBootConfig ### Description Writes out a "boot.config" file that contains configuration information for the very early stages of engine startup. ### Method `public static void WriteBootConfig(string outputFile, BuildTarget target, BuildOptions options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ### Parameters - **outputFile** (string) - The location to write the file to. - **target** (BuildTarget) - The platform to target for this build. - **options** (BuildOptions) - Options for this build. ``` -------------------------------- ### Control WebCamTexture Playback Source: https://docs.unity.cn/cn/current/ScriptReference/WebCamTexture This example shows how to control the playback of a WebCamTexture, including starting, pausing, and stopping the video feed. It relies on having a WebCamTexture instance already running. ```csharp using UnityEngine; public class WebcamControls : MonoBehaviour { public WebCamTexture webcamTexture; void Start() { // Assuming webcamTexture is already initialized and assigned if (webcamTexture == null) { Debug.LogError("WebcamTexture not assigned."); return; } webcamTexture.Play(); } void PauseCamera() { if (webcamTexture != null && webcamTexture.isPlaying) { webcamTexture.Pause(); } } void StopCamera() { if (webcamTexture != null && webcamTexture.isPlaying) { webcamTexture.Stop(); } } void ResumeCamera() { if (webcamTexture != null && !webcamTexture.isPlaying) { webcamTexture.Play(); } } } ``` -------------------------------- ### Complete Unity License Activation - Windows Source: https://docs.unity.cn/cn/current/Manual/ManualActivationGuide Completes the Unity license activation process using a previously obtained .ulf file via the command line on Windows. This step requires the path to the Unity editor and the .ulf file. ```batch "" -batchmode -manualLicenseFile -logfile ``` -------------------------------- ### Send Game Start Event Source: https://docs.unity.cn/cn/current/Manual/UnityAnalyticsStandardEvents This C# code demonstrates how to send a 'game_start' event using the `AnalyticsEvent.GameStart()` static function. This is a basic example of triggering a standard event. ```csharp AnalyticsEvent.GameStart(); ```