Does object destruction prevent using a function to randomly generate an object and then add to array?

I have been taught that local variables are destroyed when a function returns.

Suppose:

  • I have an array of objects of class Item as a member variable of a script component.
  • A function in the script creates a random object of class Item (for example a sword with random stats).
  • The function then adds a reference to that object to the array
  • Finally the function returns.

Wouldn’t the object of the reference be destroyed? If so, is there a work around? If not, why not?

Hey there,

short answer: No. Unless you call Destroy(yourobject) the object will still exist.

Longer answer:
When you create an object you have to differentiate between between creation of object by new and by Instantiate.
A Unityobject created by Instatiate will go on existing even if you don’t keep a reference of it in some of your scripts. It is a part of your scene ingame.
All other objects, for example some struct foo will exist as long as there is a reference kept to it. So by keeping a reference as a member in some other object the struct object will go on existing even if the function returns.
When you for example recreate the array that kept the reference, your referenced object will also cease existing unless there is another reference to it.

To be absolutely precise even this above is only half the truth. When an object looses all references it is stuck in this dereferenced state until cleaned up. In C# this will be done by the garbage collector. This is a natural process happening the background.
This process is quite user friendly but also brings up some issues since you as a user cannot influence the time of garbage collection. This may lead to stutters in your framerate when garbage collection happens to take place in frames that are already quite heavy on performce.

On a sidenote: Unity 2019.1 promises to include a new experimental garbage collection system that will be better for performance.

Hope this answers your question. Feel free to ask if there was something unclear.