The thing you want to instantiate is null
I'm having issues instantiating a prefab object. It was working fine, then I changed the sprite and name in the code and now the only way it will work is if the object that is supposed to instantiate is already in the scene. Here is the code I'm using:
// Use this for initialization
void Start () {
myRigidbody = GetComponent<Rigidbody2D> ();
myCollider = GetComponent<Collider2D> ();
InvokeRepeating ("Spawn", spawnTime, spawnTime);
theGround = GameObject.Find ("ground");
}
void Spawn () {
Vector3 topRight = Camera.main.ViewportToWorldPoint (new Vector3 (0, 1, transform.position.z));
bottomRight = theGround.transform.position.y;
Instantiate (GameObject.Find ("goal"), new Vector3 (5f, Random.Range (bottomRight + 0.5f, topRight.y - 0.5f), 0), Quaternion.identity);
}
Answer by Foulcloud · Aug 25, 2015 at 06:32 PM
Place the prefab in a folder called "Resources". Then use:
(GameObject)Instantiate(Resources.Load("goal"), new Vector3 (5f, Random.Range (bottomRight + 0.5f, topRight.y - 0.5f), 0), Quaternion.identity);
This will allow you to instantiate the prefab at any time. Currently, you are trying to clone a game object in the scene, so if none exist it will fail.
I am trying this but it isn't working. I made it so when my enemy dies it will drop an item but the item won't spawn. (GameObject)Instantiate(Objects.Load("item"), new Vector3 (5f, Random.Range (bottomRight + 0.5f, topRight.y - 0.5f), 0), Quaternion.identity); it just says "expected insert semicolon at the end" but it has a semicolon at the end.