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 /
  • Help Room /
avatar image
0
Question by Ventuar · Jun 24, 2016 at 05:07 AM · c#errornullreferenceexceptionobject reference

Random Chance NullReferenceException: Object reference not set to an instance of an object

I am making a game where you have to shoot enemies, and the projectiles shot explode on impact. I've got everything implemented, but for some reason, this error has a random chance of appearing. For the life of me, I cannot see a pattern in how this appears. Here is the full error:

NullReferenceException: Object reference not set to an instance of an object Projectile.OnFireballExplode () (at Assets/Scripts/Projectile.cs:25) Projectile.OnCollisionEnter (UnityEngine.Collision collision) (at Assets/Scripts/Projectile.cs:13)

And here is the script on where the error occurs:

 using UnityEngine;
 using System.Collections;
 
 public class Projectile : MonoBehaviour {
 
     public GameObject explosionObject;
     public float blastRadius = 10f;
 
     private GameObject explosion;
 
     void OnCollisionEnter(Collision collision) {
         explosion = Instantiate(explosionObject, transform.position, transform.rotation) as GameObject;
         OnFireballExplode();
         explosion.transform.parent = GameObject.Find("Explosions").transform;
         Destroy(gameObject);
     }
 
     void OnFireballExplode()
     {
         
        GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");
 
        foreach (GameObject enemy in enemies) { 
             if (blastRadius >= Vector3.Distance(transform.position, enemy.transform.position)) {
                 enemy.GetComponent<Health>().DealDamage(50f); 
             }
         }
     }
 }    

The error occurs on the last line:

 enemy.GetComponent<Health>().DealDamage(50f); 

Even though every enemy has a health script, it still calls. Does anyone know why this is? Again, its odd. Sometimes it calls, sometimes it doesn't. Thank you!

Comment
Add comment · Show 2
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 NoseKills · Jun 24, 2016 at 07:00 AM 0
Share

First i think you should find out exactly what is null. Split that line into two so you see whether enemy is null or if it's the GetComponent. There shouldn't be a way for enemy to be null i think but still.

Does DealDamage call Destroy on something? Does it destroy the gameObject or perhaps just the script?

In any case add some Debug.Logs to see if some enemy gets destroyed multiple times or such

avatar image Mindmapfreak · Jun 24, 2016 at 09:35 AM 0
Share

Does it still crash if you change the line to

 if(enemy!=null && enemy.GetComponent<Health>()!=null) {
     enemy.GetComponent<Health>().DealDamage(50f);
 }

? (Note that this is not a solution to your problem, because if enemy or the Health-component are null there is probably something wrong at another place in your code. It is just for testing purposes.) If the error still occurs you should provide the code of DealDamage.

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Morgenstern_1 · Jun 24, 2016 at 10:31 AM

You could have accidentally applied the "enemy" tag to something in your scene that doesn't have a Health component. Are your enemies made up of multiple components? Perhaps it's a child object of an enemy that doesn't have a health component itself.

I feel obliged to say that your code is quite inefficient too... GameObject.Find should almost never be used unless there's absolutely no other option. And even if you must use it you should cache the result unless it's going to change.

Vector3.Distance is really expensive too... if you change the code to what I've put below you'll get the same end result much cheaper :)

 if (blastRadius * blastRadius >= Vector3.SqrMagnitude(transform.position - enemy.transform.position))

 
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 StormMuller · Jun 24, 2016 at 01:24 PM

So as @Morgenstern_1 pointed out, You might have a gameObject in your scene that is not an enemy but you have accidentally set it as the enemy. Also like he said your enemy prefab might have child gameObjects that are also tagged as "enemy", is this is the case then all your children And parent gameobjects are getting added to your enemies list and therefore it is looking for a Health component in every single one. To fix this just remove the enemy tag from the child gameobject(s) in your prefab. If you intended to tag the children as "enemy" then you can just replace this:

enemy.GetComponent<Health>().DealDamage(50f);

with this:

 Health hp = enemy.GetComponent<Health>();
 if(hp != null)
 {
    hp.DealDamage(50f);
 }

Also you should cache your gameobjects and not use any .FindX() methods unless you need to, this is also simple to do, Instantiate() returns a GameObject, so we can do this in your spawning script:

 static List<GameObject> enemies;
 
 void Start()
 {
    enemies = new List<GameObject>();
 }
 
 void Update()
 {
      if(/* Spawn condition here */)
      {
           enemies.Add(Instantiate(/* Your enemy prefab variable */));
       }
 }

and then to use this in your projectile script:

  public class Projectile : MonoBehaviour {
 
     /* Other methods you made */
 
      void OnFireballExplode()
      {
          // GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");

         // be sure to change this to the correct script name for your project
         foreach (GameObject enemy in SpawnScript.emeies) {
               if (blastRadius * blastRadius >= Vector3.SqrMagnitude(transform.position - enemy.transform.position)) {
                  enemy.GetComponent<Health>().DealDamage(50f); 
              }
         }
   }

And just remeber to call SpawnScript.enemies.Remove(/* the enemy game object that got destroyed */); when your enemy's health is at 0f;

So I hope this helped you fix your null reference error and optimized your code a little bit.

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

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

8 People are following this question.

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

Related Questions

Null Reference Exception For An Unknown Reason 0 Answers

Null Reference in UnityStandardAssets.Utility.WaypointProgressTracker.Update 0 Answers

NullReferenceException: Object reference not set to an instance of an object Groundcheck.OnTriggerEnter2D (UnityEngine.Collider2D col) (at Assets/object/code/Groundcheck.cs:17) 0 Answers

Not sure why i'm getting NullReferenceException 0 Answers

Error Object reference not set to an instance of an object!!! Help, I am new! 0 Answers


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