Unity script optimization and unity script Optimization
Selecting the correct script Optimization in Unity is more efficient than adjusting the code without any purpose. It is worth noting that the best optimization is not simply to reduce the complexity of the Code.
1. when using the FixedUpdate function, do not write too much code in the method body that does not require repeated calls, this is because the virtual machine processes each script and object with a execution efficiency of 50 to times per second. Of course, the execution efficiency can be changed. Choose Edit & gt; ProjectSettings & gt; Time from the left-side Navigation Pane to display the TimeManager orchestration panel in the Inspector view.
Difference between FixedUpdate and Update: Update will be executed every time a new frame is rendered. It will be affected by the current rendered object, and the rendering frame rate will change, therefore, the rendering interval also changes, that is, the Updata update frequency is related to the performance of the device. FixedUpdate is not affected by the frame rate, and is called at a fixed interval. Therefore, FixedUpdate is more used to process physical engines. Because Update is affected by rendered objects, Update is more used for script logic control.
2. Generally, a new Update function is generated when a new class is created. If the Code does not need this function, delete it. In addition, do not execute the Find, FindObjectOfType, and FindGameObjectsWithTag functions in the Update function. Instead, try to execute them in the Start or Awake functions.
3. The logic of referencing a game object can be defined at the very beginning. For example:
private Transform myTransform;private Rigidbody myRigidbody;void Start () { myTransform = transform; myRigidbody = rigidbody;}
4. Coroutines can be used when a program does not need to execute every frame. The InvokeRepeating function can be used for timed and repeated calls. For example, execute the DoSomeThing function once every one second after 1.5 seconds.
void Start() { InvokeRepeating("DoSomeTing", 1.5f, 1.0f);{
5. Minimize the use of temporary variables, especially in functions called in real time such as Update.
6. When the game is paused and the scenario is switched, garbage collection can be performed to remove unnecessary memory usage in the game in a timely manner.
Void Update() { if(Time.frameCount%50 == 0) { System.GC.Collect(); }}