Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 Stealthygolem · Nov 06, 2014 at 10:41 AM · c#colliderlistnullreferenceexception

How to null-reference check a Collider2D that's been destroyed

Hello! I have been playing around with a twinstick control system for my game, and it's beginning to come up roses! But, there is now an issue with checking the collider when the collider (or gameObject) has been destroyed. To understand visually: My player has a CircleCollider2D that will attack any enemy colliding with the trigger when he is directing the right stick towards them.

My question is simply: How do I null reference check a Collider2D so the method can keep going as normal?

My current code:

    List<Collider2D> colliderList = new List<Collider2D>();

     void OnTriggerEnter2D(Collider2D col) {
         if(!colliderList.Contains (col) && col.gameObject.tag =="Enemy") {
             colliderList.Add (col);
         }
     }
 
     void OnTriggerExit2D(Collider2D col) {
         if(colliderList.Contains (col) && col.gameObject.tag =="Enemy") {
             colliderList.Remove(col);
         }
     }
 
     void OnTriggerStay2D(Collider2D col) {
 
         float addedDamageRange = Random.Range(2,6);
         float damageDealt = attackDamage + addedDamageRange;
 
         float rightHorizontal = Input.GetAxis("RightStickHorizontal");
         float rightVertical = Input.GetAxis("RightStickVertical");
 
         if ((rightHorizontal != 0 || rightVertical != 0) && meleeAttackCD == 0f) {
             foreach(Collider2D enemy in colliderList) {
                 EnemyHealth eh = (EnemyHealth)enemy.GetComponent("EnemyHealth");
                 if(enemy.collider2D) {
                     eh.curhp -= damageDealt;
                 }
                     
                 Debug.Log ("You hit enemy for "+damageDealt+" dmg");
                 meleeAttackCD = 1f;
             }
         }
     }    

When this code executed enough so that an enemy has been destroyed (his curhp == 0), it stops working and just gives me a null reference error looking for the previous BoxCollider2D on the enemy. I hope you can bare with me and understand. Any help is appreciated.

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 HarshadK · Nov 06, 2014 at 11:17 AM 0
Share

Where exactly you get a null reference error? Can you post the exact error message from console?

avatar image Stealthygolem · Nov 06, 2014 at 11:40 AM 0
Share

Sure thing, have this wall of mess!

 $$anonymous$$issingReferenceException: The object of type 'BoxCollider2D' has been destroyed but you are still trying to access it.
 Your script should either check if it is null or you should not destroy the object.
 UnityEngine.Component.get_gameObject () (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineComponent.cs:172)
 UnityEngine.Component.GetComponent (System.String type) (at C:/BuildAgent/work/d63dfc6385190b60/artifacts/EditorGenerated/UnityEngineComponent.cs:192)
 TwinStickRotation.OnTriggerStay2D (UnityEngine.Collider2D col) (at Assets/Scripts/TwinStick/TwinStickRotation.cs:82)

1 Reply

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by HarshadK · Nov 06, 2014 at 11:58 AM

In your OnTriggerEnter you add the collider to your colliderList which is traversed in your OnTriggerEnter. But I guess you are actually destroying your enemy in your EnemyHealth script when it reaches to zero but you are not removing his collider from the colliderList.

Just add a check in side your health decrease for if the health is zero and then remove that collider from the colliderList.

Try:

 if(enemy.collider2D)
 {
     eh.curhp -= damageDealt;
     
     if(eh.curhp <= 0)
     {
         // Remove this enemy's collider from the list since he is dead
         colliderList.Remove(col);
     }    
 }

Comment
Add comment · Show 3 · 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 Stealthygolem · Nov 06, 2014 at 12:20 PM 0
Share

It worked, sorta. It left me with this error, though:

 InvalidOperationException: Collection was modified; enumeration operation may not execute.
 System.Collections.Generic.List`1+Enumerator[UnityEngine.Collider2D].VerifyState () (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:778)
 System.Collections.Generic.List`1+Enumerator[UnityEngine.Collider2D].$$anonymous$$oveNext () (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:784)
 TwinStickRotation.OnTriggerStay2D (UnityEngine.Collider2D col) (at Assets/Scripts/TwinStick/TwinStickRotation.cs:81)


How do I fix this then, doctor? :) Thanks btw!

avatar image Stealthygolem · Nov 06, 2014 at 12:43 PM 0
Share

That did the trick. Thanks, $$anonymous$$ayank!

avatar image Mayank Ghanshala · Nov 06, 2014 at 12:45 PM 0
Share

you welcome @S$$anonymous$$lthygolem I accidentally deleted it although.

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

26 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

Related Questions

C# NullReferenceException 2 Answers

Detecting OnMouseDown from colliders in an array 1 Answer

Why do I keep getting NullReferenceException in Unity while iterating over a List (in OnDrawGizmos)? 2 Answers

C# NullReferenceException 1 Answer

Multiple Cars not working 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