NullReferenceException: Object reference not set to an instance of an object
Using the following script I get the following error ; "NullReferenceException: Object reference not set to an instance of an object" for both lines 32 and 18 .
using UnityEngine;
using System.Collections;
public class HealthPoints : MonoBehaviour {
public int health = 1;
public GameObject Enemy;
ScoreManager scoreManager;
// Update is called once per frame
void Start(){
scoreManager = GetComponent<ScoreManager>();
}
void Update () {
Die ();
}
void OnTriggerEnter2D(){
Debug.Log ("You hit something!");
health--;
}
void Die(){
if (health <= 0) {
Destroy (gameObject);
if (gameObject.layer == 8) {
scoreManager.score=10;
Debug.Log ("Enemy has died!");
}
}
}
}
Here is the "ScoreManager" Script :
using UnityEngine;
using System.Collections;
public class ScoreManager : MonoBehaviour {
public GUISkin theSkin;
public int score;
// Use this for initialization
void Start () {
score = 0;
}
void OnGUI(){
GUI.skin = theSkin;
GUI.Label (new Rect (Screen.width/2, 0, 100, 100), "" + score);
}
}
I'm not sure what to do as the error only appears after a trigger occurs. I believe it has something to do with the variable (int) score from the ScoreManager script, but I am unsure on how to resolve it. I have also looked at various other Unity Answers pages but despite my code being fairly similar, it still doesn't work. Thank you for reading and I appreciate any answers.
@RSharma98 Do you have the score manager component attached to the GameObject that this script is attached to? Because if you don't, that's your issue ;)
@binaryspace1010 I need the scripts on two different game objects, otherwise when my player dies the score will disappear. How do I reference a script from another game object?
@RSharma98 You could try making the int score static. As such, the variable will be shared all instances, and it will be the same. You just need to reference it using Score$$anonymous$$anager.score;
@rageingnonsense sorry but I tried making the int static but it did not work. @Positive7 your code worked perfectly, thanks a lot to everyone for helping :)
Yeah I know I tested it :D I'm glad I could help. $$anonymous$$eep up the good work!
Your answer
Follow this Question
Related Questions
C# Respawn and Score Problem 1 Answer
Score Points based on Animating Png Texture 2 Answers
Score counter not working properly. 1 Answer