- Home /
NullReferenceException: Object reference not set to an instance of an object
I have this code and I want to trigger the function Sumar() in another script called Score, there is an empty GameObject in my scene which has attached the Score script, this empty GameObject only display text, while the ItemScript which has this function is attached to a Sprite.
void OnCollisionEnter2D(Collision2D collision)
{
// Colision con el jugador
PlayerScript player = collision.gameObject.GetComponent<PlayerScript>();
Score sumaPuntaje = this.GetComponent<Score>();
sumaPuntaje.Sumar();
if (player != null)
{
Destroy(gameObject);
}
}
}
But I keep getting this error:
NullReferenceException: Object reference not set to an instance of an object
I've tried with other instructions like this one:
Score sumaPuntaje = gameObject.GetComponent<Score>();
Score sumaPuntaje = GetComponent<Score>();
But I keep getting the error message, what can I do in orther to solve this?
Answer by sevensixtytwo · Sep 29, 2014 at 02:18 AM
Looks like you're trying to reference a component that's missing. If I understand you correctly, your objects look like this:
Sprite (has Item script and collision function)
Empty GO (has Score script and text)
In that case, GetComponent alone won't cut it, since it searches the gameObject it is attached to (your Sprite). You'll have to store a reference to your Empty GO in the Sprite in order to GetComponent the Score script.
GameObject ScoreObject;
And then:
Score sumaPuntaje = ScoreObject.GetComponent<Score>();
sumaPuntaje.Sumar();
NOTE: There are better ways to store references, I'm just trying to stay close as possible to the original script. An alternative is to store the actual Score script as a reference or to tag its gameObject and use GameObject.FindWithTag.
I added this line to make sure i was picking the score object:
void Start()
{
ScoreObject = GameObject.FindGameObjectWithTag("Score");
}
Your answer
Follow this Question
Related Questions
NullReferenceException: Object reference not set to an instance of an object CannonFire.Update 0 Answers
NullReferenceException help 1 Answer
Pause menu error NullReferenceException:Object reference not set to an instance of an Object .js 1 Answer
Another NullReferenceException: question...(Java) 1 Answer
NullReferenceException 3 Answers