- Home /
NullReferenceException: Object reference not set to an instance of an object DestroyByContact.OnCollisionEnter2D (UnityEngine.Collision2D coll)
Hello everyone. I'm trying to develop a script that add points when the player touch an object. I'm following the official unity tutorial but it seems to have problems. When the player touch the object that have assigned the destroyByContacts script the game stop and give me this error:
NullReferenceException: Object reference not set to an instance of an object
DestroyByContact.OnCollisionEnter2D (UnityEngine.Collision2D coll) (at Assets/Scripts/DestroyByContact.cs:24)
Here is the scripts used:
DestroyByContacts (applied to object that need to be destroyed after collision and add point:
using UnityEngine;
using System.Collections;
public class DestroyByContact : MonoBehaviour {
public int scoreValue;
private GameController gameController;
void Start() {
GameObject gameControllerObject = GameObject.FindWithTag ("GameController");
if (gameControllerObject != null) {
gameController = gameControllerObject.GetComponent<GameController>();
}
if (gameController == null) {
Debug.Log("Cannot find 'GameController' script");
}
}
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "Player")
{
Destroy(this.gameObject);
gameController.AddScore(scoreValue);
}
}
}
GameController ( applied to the GameController Object of the scene) :
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public GUIText scoreText;
private int score;
void Start ()
{
score = 0;
UpdateScore ();
}
void UpdateScore()
{
scoreText.text = "Score: " + score;
}
public void AddScore( int newScoreValue )
{
score += newScoreValue;
UpdateScore ();
}
}
What can be the problem?
What is the value of score value when it gives you that error? gameController may not be null but something on line 24 is ...
Your answer
Follow this Question
Related Questions
I can do this in JS or not ??? 2 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Adding value to GameObject[] 1 Answer