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 blazze11 · Jul 12, 2017 at 12:17 PM · scripting problemerror messagenullreferenceexception

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

I'm working on a shoot em up game. And sometimes when my enemies die the error appears in the console. I Instantiate random enemy prefabs. All with the right tag, every variable is set in the inspector. The error appears on like 5 - 10% of killed enemies. It was working the whole time.

 NullReferenceException: Object reference not set to an instance of an object
 EnemyController.TakeDamage (Single damage) (at Assets/Scripts/EnemyController.cs:98)
 UnityEngine.Component:SendMessage(String, Object)
 Shot:OnTriggerEnter2D(Collider2D) (at Assets/Scripts/Shot.cs:28)

Shot.cs:28+

     void OnTriggerEnter2D(Collider2D col)
     {
         if(col.tag == "player" && this.gameObject.tag == "enemyShot")
         {
             col.SendMessage("TakeDamage", damage);
             Destroy(this.gameObject);
         }
 
         if(col.tag == "enemy" && this.gameObject.tag == "playerShot")
         {
             col.SendMessage("TakeDamage", damage); //28
             Destroy(this.gameObject);
         }
     }

EnemyController.cs

     protected void Die()
     {
         Punktanzeige.SendMessage("AddPoints", ScorePoints);
         Instantiate(explosion, this.gameObject.transform.position, this.gameObject.transform.rotation);
 
         this.GetComponent<DropController>().SpawnPowerUp();
 
         speaker.PlayOneShot(destroySound);
         Destroy(this.gameObject);
     }
 
     protected void TakeDamage(float damage)
     {
 
         speaker.PlayOneShot(hitSound); //98
         sr.sprite = hitSprite;
         nextSprite = Time.time + hitEffectTime;
         hp -= damage;
 
         if (hp <= 0)
         {
             Die();
         }
     }


Comment
Add comment · Show 8
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 $$anonymous$$ · Jul 12, 2017 at 12:29 PM 1
Share

Tell us more about "speaker" as it seems that this object is empty at line 98. Where is it initialized and where is it destroyed?

avatar image blazze11 $$anonymous$$ · Jul 12, 2017 at 12:33 PM 0
Share

It's not the speaker if I remove it the error appears on the next line. speaker, sr, are all initialized in Start() of the EnemyController.cs.

avatar image crisis-sheep · Jul 12, 2017 at 12:55 PM 0
Share

What is PlayerOneShot exactly?

avatar image blazze11 crisis-sheep · Jul 12, 2017 at 12:58 PM 0
Share

https://docs.unity3d.com/ScriptReference/AudioSource.PlayOneShot.html

avatar image crisis-sheep blazze11 · Jul 12, 2017 at 01:02 PM 0
Share

Ah. I am officially an idiot.

avatar image crisis-sheep · Jul 12, 2017 at 01:05 PM 0
Share

Another question: how many colliders are attached to each enemy?

avatar image blazze11 crisis-sheep · Jul 12, 2017 at 01:10 PM 0
Share

each enemy has 1 polygon collider.

avatar image crisis-sheep blazze11 · Jul 12, 2017 at 01:15 PM 0
Share

Hmm. Okay, if I may suggest a test: remove everything from TakeDamage() except Die() – so that every hit will cause a kill. See if the incidence spikes?

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by crisis-sheep · Jul 12, 2017 at 01:30 PM

I'm gonna go with a race condition on this one. Collision callbacks have caused some sticky situations for me in the past.

I think on occasion there are multiple shots that would cause the enemy to destroy itself. One gets there first and the code drops out from under its feet (so to speak) in the middle of execution. That's why the null reference doesn't go away when you remove what appears to be the offending line – the whole object is now null.

Have you considered using an object pool? It's a better option usually than instantiation/destroying. Instead of destroying the enemy, disable it – with gameObject.SetActive(false); – and return it to the pool.

I'm pretty sure you won't run into any null references if you do this.

Comment
Add comment · Show 4 · 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 blazze11 · Jul 12, 2017 at 01:55 PM 0
Share

Never tried object pooling but I think this should help. Weird that it worked the whole time.

avatar image crisis-sheep blazze11 · Jul 12, 2017 at 02:08 PM 0
Share

I hear you! It's the main gotcha with concurrency. There are so many paths for the code to take (even in simple cases), and often most of them are valid, but there are certain outliers that will bite you.

avatar image crisis-sheep blazze11 · Jul 12, 2017 at 03:02 PM 0
Share

PS: Have you migrated to the new version of Unity? Possibly some underlying change that exposed the issue?

avatar image blazze11 crisis-sheep · Jul 13, 2017 at 09:42 PM 0
Share

Update: I created a objectPooler for Shots and Enemies. Replaced:

          if(col.tag == "enemy" && this.gameObject.tag == "playerShot")
          {
              col.Send$$anonymous$$essage("TakeDamage", damage);
              Destroy(this.gameObject);
 
 with:
 
         if(col.tag == "enemy" && gameObject.tag == "playerShot")
         {
             col.gameObject.GetComponent<EnemyController>().TakeDamage(damage);
             gameObject.SetActive(false);
         }

It does still happen but much less. I'm using Unity 5.5.4f1

avatar image
0

Answer by Cornelis-de-Jager · Jul 13, 2017 at 09:46 PM

I think the problem is that you aren't calling the behaviour. Since you are calling snedMessage on the collider it won't work. Since the collider doesn't have a function called TakeDamage. Try replacing send message with the following:

 void OnTriggerEnter2D(Collider2D col)
      {
          if(col.tag == "player" && this.gameObject.tag == "enemyShot")
          {
              col.GetComponent<EnemyController>().TakeDamage(damage);
              Destroy(this.gameObject);
          }
  
          if(col.tag == "enemy" && this.gameObject.tag == "playerShot")
         {
             col.GetComponent<EnemyController>().TakeDamage(damage);
              Destroy(this.gameObject);
          }
      }
 
Comment
Add comment · Show 1 · 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 blazze11 · Jul 13, 2017 at 09:51 PM 0
Share

I did this already and it does still happen sometimes.

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

110 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 avatar image avatar image avatar image avatar image

Related Questions

Error scripting message 1 Answer

How to unfreeze a Script in a unity5 Scene? 1 Answer

count <= std::numeric_limits::max() error when viewing custom trees on terrain 0 Answers

Error on script for detecting the terrain texture 2 Answers

First Person Controller Script not working 3 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