I am currently working on my first unity game outside of a tutorial. I am trying to get a coin to spawn on the y axis at random positions. I have done this in c#, except the code only works some times (60% - 70% of the time). The other times the coin does not spawn and an error message saying **NullReferenceException: Object reference not set to an instance of an object** appears. Can you please help me.
Here is the scripts thats spawns the coin prefab:
using UnityEngine;
using System.Collections;
public class CoinSpawner : MonoBehaviour {
public GameObject Collectible;
private float Miny = -2.6f;
private float Maxy = 2.6f;
// Use this for initialization
void Start () {
Debug.Log ("Called");
spawnCoin ();
}
public void spawnCoin () {
Vector3 coin = new Vector3 (-2.1f, Random.Range (Miny, Maxy),0);
Instantiate (Collectible, coin, Quaternion.identity);
}
// Update is called once per frame
void Update () {
}
}
Here is the script that tells the coin what to do once spawned:
using UnityEngine;
using System.Collections;
public class CoinBehaviour : MonoBehaviour {
public CoinSpawner coinSpawner;
public int scoreValue = 1;
public ScoreKeeper scoreKeeper;
// Use this for initialization
void Start () {
// Get Score text thingy
scoreKeeper = GameObject.Find ("0000").GetComponent ();
// Get coin spawner thingy
coinSpawner = GameObject.Find ("Spawner").GetComponent();
}
void OnTriggerEnter2D (Collider2D col) {
if (col.gameObject.tag == "Player") {
Debug.Log ("Hit");
Destroy (gameObject);
coinSpawner.spawnCoin();
scoreKeeper.Score(scoreValue);
}
}
}
Picture of Game while working:
![alt text][1]
Picture of Game while not working:
![alt text][2]
[1]: /storage/temp/56804-screen-shot-2015-10-23-at-32704-pm.png
[2]: /storage/temp/56805-screen-shot-2015-10-23-at-32721-pm.png
↧