- Home /
Question by
saver1991 · Jun 20, 2014 at 03:10 PM ·
c#errornullreferenceexception
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?
Comment
Your answer
Follow this Question
Related Questions
NullReferenceException problem 2 Answers
Targeting Issue Error 1 Answer
Can't explain an NRE 0 Answers
C# - instance is not set to an instance of an object 2 Answers
Editing in Animator removes Player tag 0 Answers