Instantiating C#

I’ve been just going over this over and over and can’t figure out what is wrong. I’m instantiating an object, but even though that works fine, I cannot seem to reference that object in anyway.

public class BotSpawner : MonoBehaviour {
	public Transform bot;
	Vector3 position; 
	GameObject botObj;

	void Start () {
		position = Vector3.zero;
		botObj = Instantiate(bot, position, Quaternion.identity) as GameObject;
		print(botObj.transform.position.x);
	}
	
}

The print returns a null reference, as does every other attempt I’ve tried to use botObj as a GameObject. The object instantiates fine, however, and appears where its supposed to.

Try casting it to a GameObject. Instantiate, according to the docs, returns an Object, not a GameObject.

When you instantiate a Transform, you are returned a transform. If you instantiate a GameObject, you are returned a GameObject.

The issue is you are casting (using the as keyword) from the returned Transform into a GameObject which causes issues because that object is not a GameObject.

botObj = (Instantiate(bot, position, Quaternion.identity) as Transform).gameObject;

Try that, it should hopefully remedy the situation.

Ntero, that did remedy the situation, thank you.

I figured that casting it as GameObject was causing problems, but I didn’t know really how to fix that, and it was how many people were doing it in the examples that I could find.

The script works perfectly now.