- Home /
Destroy () vs nulling an object created in script - c#
So if I created a new material from within a script:
private Material material;
void Start ()
{
material = new Material ("shader/shader");
}
Making sure that the only reference to this material is that material variable, if I were to null it:
void Update ()
{
material = null;
}
Does it also destroy the material? I ask this because I know that Unity wraps c++ objects in c#. So null would make the c# object get garbage collected, but does the c++ side get destroyed aswel? Or do you have to use Destroy () to ensure it does?
Answer by fafase · Jun 11, 2015 at 06:14 PM
I would use Destroy. I guess it runs and removes all possible references to the object, so it is sure to get collected.
Also, a null may not work the same in Unity, consider the following:
GameObject obj = new GameObject();
Rigidbody rig = obj.AddComponent<Rigidbody>();
rig.AddForce(force);
rig = null;
obj = null;
the script in which this happens has no access to the object anymore nor the rigidbody, you may think they will be collected. But the GO is still in the scene with a rigidbody attached to it.
So, for a null to work, you would have to gather all containers and references and make the separations from there.
Conclusion: Use Destroy.
I assume the GameObject
appears in the hierarchy when you create it like this? If so, there's still a reference to it so nulling your local variables are just eli$$anonymous$$ating your reference. Just have to remember that GameObjects
are kind of special in that the engine creates its own reference when you construct one. You have to remove the engine's reference if you want it to go away, and that is done with Destroy
.
This all seems right, except that, as I understand it, it's not just GameObjects which aren't garbage collected, Unity's Object class isn't either.
It's relevant because the $$anonymous$$aterial in the question is an Object but not a GameObject.
The main issue with the question is that we do not know exactly what happens when we create a new Object or a new GameObject. $$anonymous$$ost likely, we do not have access to every reference the engine is creating. So using Destroy is the solution.
@Dave Carlile, yes the GameObject is in the hierarchy and well alive as it can be fetched using Find or some Physics related method.
$$anonymous$$y point is mainly that if using a UnityEngine item, trying the conventional C# way is not reliable.
But I guess we already all agree with that.
Your answer
Follow this Question
Related Questions
how to destroy enemy 1 Answer
Why are objects just set to null? 2 Answers
Multiple Cars not working 1 Answer
Enemy Spawner help 1 Answer