Is this a good practice for mobile devices?

Hello,

I am targeting my game for both Android and iOS and I was wondering whether this would be a good practice. As my target is primarily mobile and to help Unity to collect garbage - was wondering to assign null to all the variables when you destroy a gameobject or that particular script.

Let’s say a GameObject A has a Script S. Then when you destroy the gameobject or Load another scene - reference all the variables to a null value.

	Vector3 PlayerPosition;
	float Fl;
	int In;
	Transform ThePlayer;
	
	
	void Start ()
	{
		ThePlayer = GameObject.FindWithTag("Player").GetComponent<Transform>();
		PlayerPosition = ThePlayer.position;
		Fl = 5.0f;
		In = 3;
	}
	
	
	void OnDestroy ()
	{
		ThePlayer = null;
		PlayerPosition = null;
		Fl = null;
		In = null;
	}

Thank you,

regards,

Karsnen.

In your question you make reference to two different kinds of variables:

  • Value Types - Like float, int, Vector3, etc.
  • Reference Types - Like MonoBehaviour, GameObject, Transform, etc.

There is no benefit to clearing the values of value types, in fact this shouldn’t even compile:

Vector3 PlayerPosition;
float Fl;
int In;

void OnDestroy ()
{
   PlayerPosition = null;
   Fl = null;
   In = null;
}

With regards to UnityEngine.Object instances you should note, managed objects are simply wrappers around unmanaged objects that are allocated. The unmanaged object counterparts are destroyed using the provided API Object.Destroy (runtime scripts) or Object.DestroyImmediate (editor scripts):

Destroy(ThePlayer.gameObject);

Though this does not clean up the managed object instance which should be explicitly cleared so that GC can cleanup the managed wrapper object:

ThePlayer = null;

Though in your example there seems very little point to doing the above in your OnDestroy message handler. You should only worry about nullifying your reference variables in scripts that will continue to exist. Likewise there is little point to nullifying variables within local scopes:

void SomeFunction(GameObject go) {
    Transform t = go.transform;

    // Do your stuff...

    // Absolutely no point:
    //   #1 - the transform object will still exist.
    //   #2 - the variable is going out of scope, so not GC issue
    t = null;
}

The way in which you do this will obviously vary with regards to what you are doing, but hopefully the above will help you to understand the general idea.

I’m not a guru on Unity garbage collection by any means, hopefully someone more knowledgeable can confirm:

I don’t think setting variables to null with help with garbage collection. It won’t entirely free up the memory space taken up by that variable, because it will still store it’s value as null.

If the value used to be a large array or a vector, setting it to null will lower the amount of memory taken up by the variable, but it won’t lower it to 0 bytes.

Check out these pages for more info: One, Two, Three.