Why did we use "as GameObject"?

In the Fire method we wrote this line of code:
GameObject laser = Instantiate(laserPrefab, transform.position, Quaternion.identity) as GameObject;
I tried running the game without as GameObject and got the same result. Therefore my question is- Why did we use as GameObject?

1 Like

Hi Almog,

The Instantiate method returns an object of type Object, not of type GameObject. In past versions of Unity, you had to explicitely cast the returned object. Otherwise, the compiler would have thrown an error. As it seems, this behaviour was changed in one of the newer versions of Unity, maybe in 5 or 2017. I assume the returned object gets casted implicitely now.

Game developers who have been using Unity for a couple of years, still cast the object explicitely. Maybe out of habit, maybe because they regard it as good practice.


See also:

Oh ok. And what is the difference between an Object and a GameObject?

Object is the base class in C#. GameObject is a class in the UnityEngine namespace. You also wrote classes, for example, TextAdventure, State, Player, and so on.

I’m not quite sure I understand. This is what I do understand (please correct me if I’m wrong): When we instantiate the Player Laser (which is a GameObject, right?), the method returns an Object. So then, we convert the Object into a GameObject so that the UnityEngine will be able to display the Laser in the game? Because an Object is just a class in C#, and it’s not capable of displaying itself in the engine?

That’s correct. :slight_smile:

GameObject is a C# class, too, but it is also a special Unity class. In the Unity Engine, the Unity classes/objests do things within the engine such as displaying something or becoming a part of the the physics simulation.

When you write a C# script and have it inherit from Unity’s MonoBehaviour or ScriptableObject class, you basically write a special Unity class as well. It will work within Unity, but not necessarily in non-Unity projects.

1 Like

Great, I understand it a lot better now :slightly_smiling_face:
Thank you so much!

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

Privacy & Terms