The analyzer has detected that a Unity object is created in a frequently executed method.
Regular creation/destruction of game objects can load the CPU and lead to more frequent garbage collector calls. It negatively affects the program performance.
Look at the synthetic example:
CustomObject _instance;
void Update()
{
if (....)
{
CreateCustomObject();
....
}
else if (....)
{
....
Destroy(_instance.gameObject); // <=
}
}
void CreateCustomObject()
{
var go = new GameObject(); // <=
_instance = go.AddComponent<CustomObject>();
....
}
Here, some '_instance' game object is created and destroyed in the 'Update' method. Since 'Update' is executed every time the frames are updated, it is recommended to avoid such operations.
To optimize the code, initialize '_instance' once, for example in the 'Start' method. Then use the '_instance.gameObject.SetActive' method in the 'Update' method to activate/deactivate the object instead of creating/destroying it.
The implementation example:
CustomObject _instance;
void Start()
{
CreateCustomObject();
_instance.gameObject.SetActive(false);
....
}
void Update()
{
if (....)
{
....
_instance.gameObject.SetActive(true);
}
else if (....)
{
....
_instance.gameObject.SetActive(false);
}
}
void CreateCustomObject()
{
var go = new GameObject();
_instance = go.AddComponent<CustomObject>();
....
}
The same optimization applies to the 'MonoBehaviour' components. In this case, use the 'enabled' component property to activate/deactivate them.
Often, many temporary objects, like projectiles, need to be created/destroyed. These scenarios can also be optimized by replacing the above operations with 'activate/deactivate' operations within object pools. For such cases, Unity provides a built-in set of versatile object pools located within the 'UnityEngine.Pool' namespace, such as 'ObjectPool<T>'. For further information on how to use the class, refer to the Unity website here or here.