The camera in question is using the MainCamera tag, but when I try to use Camera.main, I get a null reference exception and I can’t figure out why. Could someone enlighten me?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class LootPickup : MonoBehaviour {
public GameObject ak47;
public GameObject m4a1;
public Transform gunPoint;
//public GameObject crosshairUIobj;
Camera myCamera;
//Text lootText;
GameObject Player;
// Weapons:
// 0 = Unarmed
// 1 = m4a1
// 2 = ak47
int newWeapon = 0;
// Use this for initialization
void Start () {
Player = GameObject.Find ("Player Controller(Clone)");
//lootText = crosshairUIobj.GetComponent<Text> ();
}
// Update is called once per frame
void Update () {
Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
Transform hitTransform;
Vector3 hitPoint;
hitTransform = FindClosestHitObject(ray, out hitPoint);
//Debug.Log (hitTransform.gameObject.tag);
if(hitTransform.transform.CompareTag ("ak47")){
newWeapon = 2;
//lootText.text = "Pick up AK-47";
}
if(hitTransform.transform.CompareTag ("m4a1")){
newWeapon = 1;
//lootText.text = "Pick up M4A1";
}
if(Input.GetKeyDown("f"))
{
exchangeWeapon (newWeapon);
}
}
void exchangeWeapon(int newWeapon){
if (newWeapon == 1) {
ak47.gameObject.SetActive(false);
m4a1.gameObject.SetActive(true);
}
if (newWeapon == 2) {
ak47.gameObject.SetActive(true);
m4a1.gameObject.SetActive(false);
}
if (newWeapon == 0) {
ak47.gameObject.SetActive(false);
m4a1.gameObject.SetActive(false);
}
}
Transform FindClosestHitObject(Ray ray, out Vector3 hitPoint) {
RaycastHit[] hits = Physics.RaycastAll(ray);
Transform closestHit = null;
float distance = 0;
hitPoint = Vector3.zero;
foreach(RaycastHit hit in hits) {
if(hit.transform != this.transform && ( closestHit==null || hit.distance < distance ) ) {
// We have hit something that is:
// a) not us
// b) the first thing we hit (that is not us)
// c) or, if not b, is at least closer than the previous closest thing
closestHit = hit.transform;
distance = hit.distance;
hitPoint = hit.point;
}
}
// closestHit is now either still null (i.e. we hit nothing) OR it contains the closest thing that is a valid thing to hit
return closestHit;
}
}
This is the console window output:
NullReferenceException: Object reference not set to an instance of an object
LootPickup.Update () (at Assets/LootPickup.cs:32)