Question by
StetsonT22 · Jan 09, 2016 at 05:01 AM ·
c#null reference exceptionavoidance
Why wont my code run?
After trying to fix a null reference error my code no longer runs. I threw in some debug.logs to see what was going on, and it wont make it passed the second debug.log.
I'm confused, by the third frame/timestep would all conditions not be met?
/*Item Pickup Ray*/
/*To be attached to the player CAMERA...*/
/*Stetson*/ //25/12/2015
using UnityEngine;
using System.Collections;
public class ItemPickupRay : MonoBehaviour {
public float pickupDistance = 2f; //Max distance that an object can be picked up from...
public LayerMask layerMask; //Go in the inspecter and set this to the same layer all pickupable object...
private GameObject cachedOBJ;
public ItemDisplayInfoManager cachedMNGR;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
//Create ray...
Ray pickupRay = new Ray (transform.position, transform.forward);
//Create a veriable to store the hit object...
RaycastHit hit;
//if our ray hits something we'll store the hit info...
if (Physics.Raycast (pickupRay, out hit, pickupDistance, layerMask)) {
Debug.Log ("hit Something on layer");
//Store the object we are hitting...
cachedOBJ = hit.collider.gameObject.transform.parent.gameObject;
//if there is a game objects stored already...
if (cachedOBJ){
Debug.Log ("Have object cached");
//Store the object we are hittings manager...
cachedMNGR = hit.collider.GetComponentInChildren<ItemDisplayInfoManager>();
//If we have a manager...
if(cachedMNGR){
Debug.Log ("Have manager cached");
//If hit object is a weapon...
if (cachedOBJ. GetComponent<Firearm>()){
Firearm fireArmScript = cachedOBJ.GetComponent<Firearm>();
//If the weapon is NOT in the players hand...
if(!fireArmScript.isInHand){
//Display weapon info...
cachedMNGR.ShowInfo();
//if user presses the "USE" button...
if (Input.GetButtonDown ("Use/Select")){
//Call PickupWeapon() Method...
fireArmScript.PickupWeapon ();
}
}
}
}
}
}
}
}
Comment
//Store the object we are hitting...
cachedOBJ = hit.collider.gameObject.transform.parent.gameObject;
Debug.Log(cachedOBJ); // add this line
//if there is a game objects stored already...
try this, it will at least tell you if cachedOBJ is being used properly