• 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 Frede1012 · Dec 28, 2012 at 12:10 PM · c#errorobjectdestroynullreferenceexception

NullReferenceException - When destroying Object

Hello there! I have a problem, i am getting an "NullReferenceException".. And i do not see why, it says its at line 45. Which makes no sense at all.. Everything worked before i added the "Destroy(targetobj);" :-)

Here is my code:

 using UnityEngine;
 using System.Collections;
 
 public class PickupItem : MonoBehaviour
 {
     public GameObject player;
     public string searchTag = "Item";
     public Transform target;
     public GameObject targetobj;
     public bool item_visible = false;
     public float distancemax = 2;
     
     // Use this for initialization
     void Start ()
     {
         player = GameObject.FindGameObjectWithTag ("Player");
     }
     
     // Update is called once per frame
     void Update ()
     {
         
         
     
         if (Input.GetButtonDown ("Use")) {
             
             ScanForTarget (false);
             
             item_visible = target.renderer.isVisible;
             
             float distance = Vector3.Distance (player.transform.position, target.transform.position);
         
             
             Debug.Log ("" + target + " Position: " + target.transform.position + " Player Position: " + player.transform.position + " Distance: " + distance);
                 
             if (distance < distancemax && item_visible == true) {
                 
                 Debug.Log ("'E' PRESSED @Item");
                 Debug.Log ("targetobj = " + targetobj.ToString ());
                 Destroy (targetobj);
                 MyPlayer.MyInventory.Add (new Item ("T-I", 0));
             
             }
         
         }
     }
     
     void ScanForTarget (bool debug)
     {
         
         target = GetNearestTaggedObject (debug);
         targetobj = target.gameObject;
 
     }
 
     Transform GetNearestTaggedObject (bool debugging)
     {
         
 
         float nearestDistanceSqr = Mathf.Infinity;
         GameObject[] taggedGameObjects = GameObject.FindGameObjectsWithTag (searchTag); 
         Transform nearestObj = null;
 
         
         foreach (GameObject obj in taggedGameObjects) {
 
             Vector3 objectPos = obj.transform.position;
             float distanceSqr = (objectPos - transform.position).sqrMagnitude;
 
             if (distanceSqr < nearestDistanceSqr) {
                 nearestObj = obj.transform;
                 nearestDistanceSqr = distanceSqr;
             }
         }
         
         if (debugging == true) {
         
             Debug.Log (nearestObj);
         }
         return nearestObj;
     }
     
 }
 

Full error message: NullReferenceException: Object reference not set to an instance of an object at ToolTipHandler.Update ()

Thanks!

  • Frederik

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

1 Reply

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

Answer by alexfeature · Dec 28, 2012 at 12:59 PM

Destroy sets reference to null. Hence targetObject is null when you are calling .ToString() on it.

Doing so causes the NullReferenceException.

If you want to log the state of the object do this : Debug.Log(string.Format("targetobj is {0}", targetobj == null ? "destroyed" : "alive"));

Comment
Add comment · Show 8 · 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 Frede1012 · Dec 28, 2012 at 01:13 PM 0
Share

Oh! How could i miss that, the Debug was only to check if it took the right GameObject.. Forgot to remove it :-P

  • Thanks anyway!

avatar image alexfeature · Dec 28, 2012 at 01:23 PM 0
Share

Glad i helped :D

avatar image Frede1012 · Dec 28, 2012 at 08:36 PM 0
Share

It didnt work.. I updated my code and it is still crashing..

avatar image alexfeature · Dec 29, 2012 at 06:57 AM 0
Share

Hm. Ok then.

Try adding some more debug lines and see at which point you get the last debug message. Then mark it in code.

It seems that everything is ok in your script. Ofc its hard to tell if any of the other objects are not null. For instance $$anonymous$$yPlayer or $$anonymous$$yInventory? $$anonymous$$aybe they are null?

avatar image Frede1012 · Dec 29, 2012 at 11:54 PM 0
Share

If i comment out the Destroy(targetobj); it doenst crash? Updated question with full error message.

Show more comments

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

10 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

Related Questions

Unknown reason for NullReferenceException error 1 Answer

Referencing a variable to a prefab from another script that is applied to multiple game objects 0 Answers

NullReferenceException and m_InstanceID == 0 on LoadLevel (C#) 1 Answer

Distribute terrain in zones 3 Answers

Why won't my script load? 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