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);” :slight_smile:

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

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”));