Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by unity_AM22EsnNpu6bTQ · Dec 28, 2017 at 03:18 PM · errorcollidergameobjectsmethodmethods

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!

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ScaniX · Dec 28, 2017 at 03:53 PM 0
Share

It would probably help to post the line number of the error. It should be part of the error message in the console.

2 Replies

· Add your reply
  • Sort: 
avatar image
-1

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);

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image unity_AM22EsnNpu6bTQ · Dec 28, 2017 at 03:40 PM 0
Share

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.

avatar image ShadyProductions unity_AM22EsnNpu6bTQ · Dec 29, 2017 at 01:07 AM 0
Share
 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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

106 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges