Question by
AustinMeiron · Sep 28, 2016 at 06:32 PM ·
c#scripting problemerror messagenullreferenceexception
Object reference not set to an instance of an object - Jumping Scripts (C#)
I'm trying to jump and execute in another script when the player collides with an object using this code in a script that checks for a collision named "CheckCollisions":
using UnityEngine;
using System.Collections;
public class CheckCollision : MonoBehaviour {
private GameObject Player;
private EndlessMode Jumpscripts;
// Use this for initialization
void Start () {
Player = GameObject.Find ("Player");
}
void OnCollisionEnter2D(Collision2D Player) {
Debug.Log ("Collision Detected");
Jumpscripts.StopGame ();
}
}
The script its jumping to ("EndlessMode") has this line of code that it should be executing:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class EndlessMode : MonoBehaviour {
public void StopGame () {
HasPlayerDied = true;
}
}
But when the Player does collide with an obsticle, executing the CheckCollision "OnCollisionEnter2D" function, i get the following error:
"NullReferenceException: Object reference not set to an instance of an object CheckCollision.OnCollisionEnter2D (UnityEngine.Collision2D Player) (at Assets/Scripts/CheckCollision.cs:20)"
Comment
Best Answer
Answer by conman79 · Sep 28, 2016 at 10:28 PM
You need to reference the EndlessMode script somewhere. You can do it in the Start function like this::
using UnityEngine;
using System.Collections;
public class CheckCollision : MonoBehaviour {
private GameObject Player;
private EndlessMode Jumpscripts;
// Use this for initialization
void Start () {
Jumpscripts = WHATEVERGAMEOBJECT.GetComponent<EndlessMode>();
Player = GameObject.Find ("Player");
}
void OnCollisionEnter2D(Collision2D Player) {
Debug.Log ("Collision Detected");
Jumpscripts.StopGame ();
}
}