- Home /
Question by
natestale · Apr 02, 2016 at 10:33 PM ·
nullreferenceexceptionsendmessage
Null Reference Exception error on GameObject.SendMessage
Hey guys, i have this script to pickup items, and works perfectly, but this Null Reference Exception error comes from line 60 and i don't know the reason. Any help please ?
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class TagsClass{
public string m_InteractTag = "Interact";
public string m_InteractItemsTag = "InteractItem";
public string m_DoorsTag = "Door";
}
public class DragRigidbodyUse : MonoBehaviour {
public GameObject playerCam;
public string UseButton = "Use";
public TagsClass Tags = new TagsClass();
private float PickupRange = 2f;
private Ray playerAim;
private GameObject objectHeld;
private bool tryPickupObject;
void Start () {
tryPickupObject = false;
objectHeld = null;
}
void FixedUpdate () {
if(Input.GetButton(UseButton)){
tryPickObject();
tryPickupObject = false;
Use();
}
}
private void tryPickObject(){
Ray playerAim = playerCam.GetComponent<Camera>().ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
RaycastHit hit;
if (Physics.Raycast (playerAim, out hit, PickupRange)){
objectHeld = hit.collider.gameObject;
if(hit.collider.tag == Tags.m_InteractTag && tryPickupObject){
objectHeld.GetComponent<Rigidbody>().useGravity = false;
/**/
}
if(hit.collider.tag == Tags.m_InteractItemsTag && tryPickupObject){
objectHeld.GetComponent<Rigidbody>().useGravity = true;
}
if(hit.collider.tag == Tags.m_DoorsTag && tryPickupObject){
objectHeld.GetComponent<Rigidbody>().useGravity = true;
objectHeld.GetComponent<Rigidbody>().freezeRotation = false;
}
}
}
private void Use() {
objectHeld.SendMessage ("UseObject",SendMessageOptions.DontRequireReceiver); //Every script attached to the PickupObject that has a UseObject function will be called.
objectHeld = null;
}
}
Comment
you're assu$$anonymous$$g that objectHeld
is being set - it's probably not. try doing a null
check before using it...
is being set only when the raycast hit's the object with tag "InteractItem"
Best Answer
Answer by miszelfox · Apr 03, 2016 at 07:42 PM
Null Reference means that objectHeld is null at this moment. Call your method ONLY when you are sure that it's not empty:
if(objectHeld!=null)
Use();
You call your method everytime button is pressed, but your objectHeld is not always set. You can also just put this method call in your tryPickObject method after first if statement