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 T27M · Nov 23, 2012 at 06:35 PM · c#raycastnullnullreference

How to catch a NullReferenceException ?

Hello

I can think of other ways to fix this issue, but I wanted some input. The object I'm intending to hit has a collider attached, but I want to be able to fire even when it isn't there.

Is there a way around this Null reference without having to use an off screen plane or something for the ray to hit?

         Ray ray = new Ray ( transform.position, transform.forward * 100f); 
         RaycastHit hit;
         
         Debug.DrawRay (transform.position, transform.forward * 100, Color.green);
                     
         if( Input.GetMouseButtonUp( 0 ) )
         {
             Physics.Raycast(ray, out hit);
             
             try
             {
                 Destroy(hit.collider.gameObject);
             }
             catch ( MissingReferenceException e )
             {
                 Debug.Log(e.Message);
             }
         }

I also tried :

             if ( hit.collider.gameObject != null )
                 Debug.Log("Test");

Both give me a null referece for the hit.collider.gameobject line.

Thanks

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
1
Best Answer

Answer by coastwise · Nov 23, 2012 at 06:45 PM

I see you checking for null, but you never check the base objects. This is what I mean (might be excessive, but give it a shot)

 if ( hit != null && hit.collider != null && hit.collider.gameObject != null )
     Debug.Log("test");
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 T27M · Nov 23, 2012 at 06:50 PM 0
Share

Apart from comparing, hit != null , that did the trick. Thanks

if (hit.collider != null && hit.collider.gameObject != null )

avatar image
3

Answer by David_29 · Jun 07, 2017 at 02:42 AM

@T27M

Read it all before you conclude it.

I see that there's an accepted answer. But, there is a better answer for handling NullReferenceExcep[tion. If you can relate programming in Java language like me, you can prevent from sending a null error by using the try-catch block. Try it for yourself! ;-)

If you're using in C#, check if you have using System; at the top of your script file. If not, add it. Now, you can use all sorts of Exception classes while try-catching a line of code.

Here's an example:

 using System; // --> This exact line of code. That's it.
 using UnityEngine;
 
 public class Test : MonoBehaviour {
 
     public GameObject player; // --> Example to check if there's a null content;
 
     public void Update() {
 
         // You may now catch null reference here.
         try {
 
             player.transform.Translate(0, 0, 2);
 
         } catch(NullReferenceException e) {
 
         }
 
     }
 
 }

Also remember, you can catch also other exceptions such as MissingReferenceException, MissingComponentException, IndexOutOfRangeException, or any other exception classes as long as you include using System in your script. That is all.

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
1

Answer by MrLucid72 · Mar 20, 2019 at 04:21 AM

Have C# 4.x?

 if (!hit?.collider?.gameObject)
     Debug.Log("null");

I believe should work. The question mark checks for null (which you can do as long as whatever you're doing accepts nullable). The "!" not checks for null as a bool.

A similar example with a callback:

Original:

 if (callback != null)
   callback(true);

C# 4.x:

 callback?.invoke(true);



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

14 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

Related Questions

NullReferenceException: Object reference not set to an instance of an object ProgressBar.Start () 2 Answers

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Raycast - arrow stopped by walls (layer) but not by units (layer) 1 Answer

2 raycasts on the fpwalker/camera 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