- Home /
Instantiate an object and place it on a list.
I cann't seem to figure out what I'm doing wrong. So the idea is: Object enters trigger, I instantiate a prefab and add it on a list. But what happens is that a null obejct gets added.
void OnTriggerEnter(Collider col)
{
GameObject gox = Instantiate (radarPlayer, position, col.transform.rotation) as GameObject;
radarObjects.Add (gox);
}
}
I even tried changing the instantiation to
GameObject gox = (GameObject) Instantiate(radarPlayer);
I guess I'm doing something wrong when casting, since I dont really understand much of that.
Answer by farhanblu · May 24, 2016 at 08:59 AM
What is the type of radarPlayer object? If it is a gameObject, it should work fine. Generally, you cast your objects as GameObject gox = Instantiate(radarPlayer) as GameObject;
. However, if your radarPlayer is not a GameObject reference but something like a reference to a MonoBehavior script like this RadarPlayer radarPlayer;
, then you would have to instantiate it as GameObject gox = Instantiate(radarPlayer.gameObject) as GameObject;
Since I do not see a Resources.Load
statement, I am assuming that you want to instantiate a prefab that has been linked in inspector. Make sure your radarPlayer's reference is set in inspector.
Usually you don't cast in one way or another, you either cast:
Type obj = (Type)otherObj;
if you want the system to crash, for example while developing, you want to make sure you don't miss that the cast did not work.
Type obj = otherObj as Type;
if you want to continue even though it did not work.
First is slower but contains extra info, second is faster but requires null check to prevent crash later on.