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).
Answer by OncaLupe · Nov 14, 2015 at 09:37 PM
Instantiate creates an item of type 'Object', not 'GameObject'. To access the extra features of the item, it needs to be upcasted to GameObject. This can also be done like this:
GameObject obj = Instantiate(bullet) as GameObject;
Both versions end up doing the same thing. You can also upcast to specific components like Rigidbodies or scripts attached to the prefab.
http://docs.unity3d.com/ScriptReference/Object.Instantiate.html http://unity3d.com/learn/tutorials/modules/beginner/scripting/instantiate
Your answer
Follow this Question
Related Questions
Prefab destroyed upon instantiation 0 Answers
[HELP C#] Making Gameobject 1 equal Prefab 2 1 Answer
Instantiate prefab with its component c# 0 Answers