Hi guys,
I’ve been running through a series of bugs with this Tutorial on Unity most particularly on the part where you need to a add score. the problem is when I play the game I’m getting an error:
“NullReferenceException: Object reference not set to an instance of an object
DestroyByContact.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/DestroyByContact.cs:42)”.
After that even I shoot the asteroids they only play the sound and the effect but not disappearing or even adding a score also with the spaceship.
Here’s the code for “Destroy By Contact”:
using UnityEngine;
using System.Collections;
public class DestroyByContact : MonoBehaviour {
public GameObject explotion;
private GameObject newProjectile;
public GameObject playerExplotion;
public int scoreValue;
private GameController gameController;
void start ()
{
/GameObject gameControllerObject = GameObject.FindWithTag(“GameController”);
if (gameController != null)
{
gameController = gameControllerObject.GetComponent();
}
if (gameController == null)
{
Debug.Log(“Cannot Find ‘GameController’ script”);
}/
gameController = GameObject.FindObjectOfType();
if(gameController == null){
Debug.Log(“Cannot Find ‘GameController’ script”);
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag == “Boundary”)
{
return;
}
newProjectile = Instantiate (explotion, transform.position, transform.rotation) as GameObject;
if (other.tag == “Player”)
{
newProjectile = Instantiate (playerExplotion, other.transform.position, other.transform.rotation) as GameObject;
}
gameController.AddScore (scoreValue);
Destroy (other.gameObject);
Destroy (gameObject);
}
}
Here’s the code for “Game Controller”:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GameController : MonoBehaviour {
public GameObject hazard;
public Vector3 SpawnValue;
public int hazardCount;
public float spawnWait;
public float startWait;
public float waveWait;
public GUIText scoreText;
private int score;
void Start ()
{
score = 0;
UpdateScore ();
StartCoroutine (SpawnWaves ());
}
IEnumerator SpawnWaves ()
{
yield return new WaitForSeconds (startWait);
while (true)
{
for (int i = 0; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3 (Random.Range (-SpawnValue.x, SpawnValue.x), 0.0f, SpawnValue.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (hazard, spawnPosition, spawnRotation);
yield return new WaitForSeconds (spawnWait);
}
yield return new WaitForSeconds(waveWait);
}
}
public void AddScore (int newScoreValue)
{
score += newScoreValue;
UpdateScore ();
}
void UpdateScore ()
{
scoreText.text = "Score: " + score;
}
}
Will do appreciate your help as I’m only a beginner in Unity.