Using "GameObject sparkles = Instantiate()" vs "Object.Instantiate()"

In the lesson, you used this statement “GameObject sparkles = Instantiate();” but it also worked when i tried “Object.Instantiate();” (which i saw in the Unity docs).

I’m wondering since the latter statement is shorter, isn’t it better to use that?
Is the former statement used because we want to give the instantiated object a name? (perhaps for better debugging?)

Thanks,
BK

Hi Bing,

In Unity, all of the classes inherit, from Object. When you create your member variable at the top of your class for your sparkles, from memory you declare it as a GameObject, this itself inherits from Object.

The code in the course declares a local variable, sparkles to hold a reference to the instantiated object. With that reference you can then access the GameObjects properties. If you just using Object.Instantiate the object will be created, but you will not have a reference back to it.

You could also just use Instantiate without the Object part in front of it, as MonoBehaviour inherits from, Behaviour, which inherits from Component which inherits from Object.

Hope this helps :slight_smile:

1 Like

I see, that makes sense. I realized at the end of that lesson, because we created that reference sparkles, we could then specify this object to destroy.

1 Like

Great, and yes, example, otherwise the instantiated object, whilst no longer emitting particles would remain within the scene.

If you don’t need to do anything with an instantiated object after its been created, then you don’t need to create the variable to hold its reference, but in quite a few scenarios you will. :slight_smile:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms