Optimized code example

The following script is not optimized. Review the script to see what can be done to optimize it. Then, review the information provided after the script:

public class CucumberManager : MonoBehavior {
public static int currentCucumberCount;
Text Cucumber_Count;
public GameObject[] cucumbers;

void Update() {
Cucumber_Count = GetComponent<Text>();
currentCucumberCount = 1;
cucumbers = GameObject.FindGameObjectsWithTag("Cucumber");
Cucumber_Count.text = cucumbers.Length.ToString();
currentCucumberCount = cucumbers.Length;
}
}

Hopefully you were able to spot the inefficient, unoptimized component of the script. In the preceding example, all the statements other than the variable declarations occur in the Update() method. Consider the optimized version of the following script:

public class CucumberManager : MonoBehavior {
public static int currentCucumberCount;
Text Cucumber_Count;
public GameObject[] cucumbers;

void Awake() {
Cucumber_Count = GetComponent<Text>();
currentCucumberCount = 1;
}

void Update() {
cucumbers = GameObject.FindGameObjectsWithTag("Cucumber");
Cucumber_Count.text = cucumbers.Length.ToString();
currentCucumberCount = cucumbers.Length;
}
}

In the optimized version of this script, the GetComponent() method call and the currentCucumberCount variable initialization are moved over to the Awake() method. Those statements only need to run once. Putting them inside the Update() method would have caused undue strain on the CPU.

It is important for a game's overall performance to have optimized scripts. Checking for script optimization at the end of a project is a good idea. Ideally, you will ensure your scripts are optimized as your write, as opposed to reviewing them later. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset