Steeban Charles
Steeban Charles

Reputation: 27

What is Casting in Unity?

I am a beginner in game development and C#. I have some knowledge about casting in programming. I am following a tutorial. I am having problems with understanding this following sentence.

 GameObject obj = (GameObject)Instantiate(bullet);

Why we need to cast "Instantiate(bullet)" to GameObject ? Isn't that already a GameObject ? Explain me please or provide some links to learn about this? Thank you. (sorry for my poor English).

Upvotes: 1

Views: 12765

Answers (2)

Jaroslaw Weber
Jaroslaw Weber

Reputation: 105

If you dont cast, Instantiate will only instantiate the game object. Its like void function.

If you want to use that object in same script its better to use casting to get object reference immediately so you dont have to use gameobject.Find("xxx")

Upvotes: 0

ElDuderino
ElDuderino

Reputation: 3263

As you can read here

http://docs.unity3d.com/ScriptReference/Object.Instantiate.html

Instantiate returns an Object. An Object is not a GameObject, so you have to cast.

There is also another way to cast, which doesn't throw an exception if the cast fails. You can read about it here

C# "as" cast vs classic cast

Upvotes: 1

Related Questions