I have a little problem with the GetComponent<>() function. I’m using it to access a variable from another script. But when I try to access it this error pops out:
“NullReferenceException: Object reference not set to an instance of an object
EnemyController.OnCollisionEnter2D (UnityEngine.Collision2D coll) (atAssets/Scripts/EnemyController.cs:24)”.
Both scripts:
public class EnemyController : MonoBehaviour {
GameObject GameController;
ScoreCount scoreCount;
void Start ()
{
GameController = GameObject.Find ("GameController");
scoreCount = GameController.GetComponent<ScoreCount>();
}
void OnCollisionEnter2D(Collision2D coll)
{
scoreCount.score += 5;
Destroy (coll.gameObject);
Destroy (gameObject);
}
}
and
public class ScoreCount : MonoBehaviour {
public int score = 0;
}
The error is about the “scoreCount.score += 5;” line.
Second script has been attached to “GameController” object. It doesn’t do anything yet, but I’d like to have the score variable in it, as the first object gets deleted. It was working earlier, but it seems that I’ve changed something and I can’t figure out what.
Whats the error? is it that GameController is not set? try Debug.Log(GameController) to check it has been set correctly.
– kensctI've added Debug.Log(GameController) and nothing happens. I've tried setting this up using Inspector before but there was no difference.
– LiquidLemon