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
4
Question by Twizzsted · Sep 12, 2016 at 04:39 AM · c#gameobjectnullreferenceexceptioncomponentconfused

How to Check if a component Exists on a Gameobject.

Hey, I have the following code in a script i wrote:

 RaycastHit2D raydata = Physics2D.Linecast (transform.position, dir );
     
         Vector3 limit ;
         if (raydata.distance > 0) {
             limit = raydata.point;
         
             if (raydata.rigidbody.gameObject.GetComponent<Attack> () != null) { //errors here
                 raydata.rigidbody.gameObject.GetComponent<Attack> ().Health -= dmg;
             }
         } else {
             limit = dir;
         }


but on running, it throws a NullReferenceException at the indicated line, and i can't figure out why. (Attack is the name of a script i'm looking for in the gameobject)

Comment
Add comment
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

3 Replies

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

Answer by flaviusxvii · Sep 12, 2016 at 04:45 AM

I suspect whatever it hit didn't have a rigidbody. You should get the gameObject through the collider instead.

 if (raydata.collider.gameObject.GetComponent<Attack> () != null) { //errors here
                  raydata.collider.gameObject.GetComponent<Attack> ().Health -= dmg;
              }
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 Twizzsted · Sep 14, 2016 at 05:27 PM 0
Share

This seems to have fixed it. Thanks!

avatar image Bunny83 Twizzsted · Sep 14, 2016 at 05:51 PM 0
Share

You also should check if raydata.collider is not null. That's the actual indicator if you hit something or not.

avatar image
5

Answer by aditya · Sep 12, 2016 at 05:20 AM

Create a class to check component

 using UnityEngine;
 public static class hasComponent {
     public static bool HasComponent<T>(this GameObject flag)where T : Component{
         return flag.GetComponent<T> () != null;
     }
 }


And use it as follows ... For eg. you wanna check for Rigidbody

 public Gameobject gameObjectToCheck;
 
 void yourMethod(){
     gameObjectToCheck.HasComponent<Rigidbody>();
 }


It will return true if it has that component otherwise false ... Good Luck

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 Bunny83 · Sep 14, 2016 at 05:52 PM 0
Share

Why would you use "GetComponents" which actually allocates an array on the heap with all components of that type? Just using GetComponent and doing a null check will do the same without any garbage creation.

avatar image aditya Bunny83 · Sep 15, 2016 at 06:57 AM 0
Share

Correct ... but it looks cool to just check for a true false value rather than a comparison with a value in an actual code ... but you know what, i didn't even noticed that GetComponents thing when posting here as this code was for my project and was according to my needs ... BTW a big thanks (AGAIN) as i m editing my answer ^^

avatar image
2

Answer by Masterio · Sep 12, 2016 at 01:02 PM

 RaycastHit2D raydata = Physics2D.Linecast (transform.position, dir );
 Vector3 limit ;   
    
 if(raydata.transform != null && raydata.distance > 0)
 {
     limit = raydata.point;
  
     Attack attack = raydata.transform.gameObject.GetComponent<Attack>();
  
     if (attack != null) 
     { 
         attack.Health -= dmg;
     }
 }     
 else
 {
     limit = dir;
 }

If you relly need to check the rigidbody exists just change the:

raydata.transform.

for the:

raydata.rigidbody.

If you have lot of colliders on map use layers. ;)

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

6 People are following this question.

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

Related Questions

How to add a component on a GameObject in Custom Inspector 1 Answer

How to get a component from an object and add it to another? (Copy components at runtime) 12 Answers

How do I nullreference this correctly? 1 Answer

NullReferenceException error in an array of objects 0 Answers

AddComponent() causes a "trying to create a MonoBehaviour using the 'new' keyword" warning 2 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