Search code examples
c#unity-game-engineinstantiationgameobject

Right way to instantiate GameObject?


So I have a dilemma about right way to instantiate prefab gameObject in Unity c#.

Here is the 2 example codes

Example 1:

public Transform musicPrefab;
GameObject mManager = (GameObject)Instantiate(musicPrefab,transform.position, Quaternion.identity); 

Example 2:

public Transform musicPrefab;
Object mManager = Instantiate(musicPrefab,transform.position, Quaternion.identity);

But instantiating as Object works as well, so which way is right way?


Solution

  • Type object is way too general. It doesn't really make much sense, because you won't be able to do anything meaningful with object inside Unity3D. When you instantiate a prefab, you usually expect to create a GameObject (is there a situation when you actually don't get a GameObject?? I've personally never encountered such scenario...), so that should be the right way. GameObject has many properties and methods you can utilize. You would have to cast the result to GameObject in some later point either way...