- Home /
NullReferenceException: Object reference not set to an instance of an object
I know this is a dumb question to ask and I know that others have asked it before, but none of the answers helped me. What I'm trying to do is check if my Player objects collides with a Collider that is supposed to kill the Enemy object or with a Collider that is supposed to kill the Player object. My problem is, when I try to call in the methods from other scripts to destroy the empty GameObjects that have BoxColliders and the Enemy object, i get this error: NullReferenceException: Object reference not set to an instance of an object.
PlayerMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float SPD_Move = 5F; //Movement speed
public float JMP_Height = 600F; //Jump height, high due to strong gravitational pull
public float SPD_Dash; //Dashing speed, needs to be high due to friction or something idc
private float Dash_Cooldown; //Dashing cooldown
public int Coins; //Coins collected
public int MaxCoins; //Total coins on level
public int Enemies; //Enemies killed
public int MaxEnemies; //Total enemies on level
private bool IsGrounded = true; //Is player on ground?
public int MaxJumps = 2; //Max jumps, for multiple jumps
private int CurrentJumps = 0; //Current jumps, resets when in contact with ground
public float GravitationalPull; //Gravitational force
private ConstantForce Gravity; //Constant force, applies gravitational pull
private EnemyMovement EnemyDie; //Supposedly to be called in to destroy enemy
private PlayerKillerBox PlayerKiller; //Called in to destroy the killbox that kills the player
private EnemyKillerBox EnemyKiller; //Called in to destroy the killbox that kills the enemy
private void Start()
{
//Decreasing the cooldown every second
InvokeRepeating("CooldownDecrement", 0F, 1F);
//Disabling built-in gravity
gameObject.GetComponent<Rigidbody>().useGravity = false;
//Custom gravity
Gravity = gameObject.AddComponent<ConstantForce>();
Gravity.force = new Vector3(0, GravitationalPull, 0);
}
private void Update()
{
//Checking if all coins have been collected
if (Coins == MaxCoins && Enemies == MaxEnemies)
CurrentLevelData.NextLevel();
//Reset button, if you mess up so badly that you need it xd
if (Input.GetKeyDown(KeyCode.R))
CurrentLevelData.ReloadLevel();
}
private void FixedUpdate()
{
//Movement
if (Input.GetAxis("Horizontal") > 0)
{
transform.position += transform.right * Time.deltaTime * SPD_Move;
//Dashing right and reseting the cooldown to 3 seconds
if ((Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift)) && Dash_Cooldown <= 0)
{
GetComponent<Rigidbody>().AddForce(Vector3.right * SPD_Dash);
Dash_Cooldown = 3;
}
}
else if (Input.GetAxis("Horizontal") < 0)
{
transform.position -= transform.right * Time.deltaTime * SPD_Move;
//Dashing left and reseting the cooldown to 3 seconds
if ((Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift)) && Dash_Cooldown <= 0)
{
GetComponent<Rigidbody>().AddForce(Vector3.left * SPD_Dash);
Dash_Cooldown = 3;
}
}
//Jumping
if (Input.GetKeyDown(KeyCode.Space) && (IsGrounded || CurrentJumps < MaxJumps))
{
//transform.position += transform.up * JMP_Height; BAD JUMPING, TELEPORTS THROUGH WALLS
GetComponent<Rigidbody>().AddForce(Vector3.up * JMP_Height);
IsGrounded = false;
CurrentJumps++;
}
}
private void OnCollisionEnter(Collision other)
{
//If player is on ground, allow to jump
if (other.gameObject.tag == "Ground")
{
IsGrounded = true;
CurrentJumps = 0;
}
//If player collects a coin, increase number of collected coins and destroy the collected coin
if (other.gameObject.tag == "CoinTag")
{
Coins++;
Destroy(other.gameObject);
}
//If player jumps on top of enemy, kill the enemy
if (other.gameObject.tag == "KillEnemy")
{
// Destroy(other.gameObject);
PlayerKiller.DestroyKillbox(); //Destroys the enemy object
EnemyKiller.DestroyKillbox(); //Destroys the killbox that kills the enemy
EnemyDie.DestroyEnemy(); //Destroys enemy object
Enemies++;
}
//If player falls out of the map or touches an enemy from the side, reset the level
if (other.gameObject.tag == "Killbox")
CurrentLevelData.ReloadLevel();
}
private void OnTriggerEnter(Collider other)
{
}
//Function to be called every second to decrease the cooldowns
private void CooldownDecrement()
{
if (Dash_Cooldown > 0)
Dash_Cooldown--;
}
}
EnemyMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyMovement : MonoBehaviour
{
public void DestroyEnemy()
{
Destroy(this.gameObject);
}
}
PlayerKillerBox.cs, which has the method for destroying the GameObject that holds the Collider which kills the player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerKillerBox : MonoBehaviour {
public void DestroyKillbox()
{
Destroy(gameObject);
}
}
EnemyKillerBox.cs which has the method for destroying the GameObject holding the Collider which destroys the enemy object
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyKillerBox : MonoBehaviour {
public void DestroyKillbox()
{
Destroy(gameObject);
}
}
Any help is greatly appreciated and once again sorry for posting what has been posted before. Thank you very much in advance!
It would probably help to post the line number of the error. It should be part of the error message in the console.
Answer by UDN_9a915d40-27e1-405b-b1cc-83be8be3e71d · Dec 28, 2017 at 03:51 PM
@unity_AM22EsnNpu6bTQ Try using Destroy(this);
instead if Destroy(gameObject);
Answer by ShadyProductions · Dec 28, 2017 at 03:28 PM
you probably destroy them and after that call the same destroy on the object but it's already destroyed meaning you're calling destroy on a null object.
You can solve this by adding an if check:
if (PlayerKiller.gameObject != null && EnemyKiller.gameObject != null && EnemyDie.gameObject != null) {
PlayerKiller.DestroyKillbox();
EnemyKiller.DestroyKillbox();
EnemyDie.DestroyEnemy();
}
But in general the way you set it up is bad practice.
Also it's not advised to use GetComponent continously, it's better to make a variable and get it only once at start, it's better for performance. likeso:
private Rigidbody rb;
private void Start() {
rb = GetComponent<Rigidbody>(); //get it only once and keep a reference in a variable
}
then use it in fixed update like
rb.AddForce etc
I tried using an if check, like you said, but now the error pops up for both the if check and the lines where I attempt to call in the method and also, the objects never even get destroyed.
private Enemy$$anonymous$$ovement EnemyDie;
private Player$$anonymous$$illerBox Player$$anonymous$$iller;
private Enemy$$anonymous$$illerBox Enemy$$anonymous$$iller;
they are private, where do you actually assign them? They are unassigned that's the problem., either make them public and assign them in the inspector on manually assign them using code.
Your answer
Follow this Question
Related Questions
How can I detect multiple triggers on same gameobject at once? 3 Answers
Variable Not Changing In Method 1 Answer
Dying Script error 2 Answers
Error: GetComponentFastPath is not allowed? 2 Answers
Issue with OnTriggerEnter. 1 Answer