- Home /
Trouble setting a variable to a game object using instantiate.
I'm trying to instantiate something and I need to set the instantiated object to a variable so that I can destroy it later. Here's the code:
public static Transform attackObj; (Had to make it static in order to edit in another script)
attackObj = Instantiate (attackRouteObj, attackingCity.transform.position, Quaternion.identity) as Transform; (Inside an if statement)
Debug.Log (attackObj);
The dbug log shows up null, even after the object has been instantiated.
You do not need to make it static. Public is enough. Static means there's only one instance; remove static unless you specifically need this. Use GetComponent ins$$anonymous$$d.
Answer by Xathereal · Nov 06, 2012 at 10:09 PM
The reason is the "Instantiate" function returns an 'Object' not a 'GameObject' and I think an 'Object' does not have a transform.
Try this (it worked for me):
Transform t = (Instantiate(attackRouteObj) as GameObject).transform;
Now we converted it to a GameObject and then got the transform from that.