- Home /
NullReferenceException: Object reference not set to an instance of an object
PLS Help I get This Error : NullReferenceException: Object reference not set to an instance of an object Weapons.SwitchToWeapon (UnityEngine.GameObject weapon, UnityEngine.GameObject current) (at Assets/Scripts/Weapons.cs:64) Weapons.Update () (at Assets/Scripts/Weapons.cs:23)
using UnityEngine;
using System.Collections;
public class Weapons : MonoBehaviour {
public GameObject current;
public GameObject knife;
public GameObject pistol;
public GameObject customPistol;
public GameObject customGun;
public GameObject rifle;
public GameObject machine;
void Start(){
current = GameObject.Find("Knife");
}
void Update (){
if (Input.GetKey(KeyCode.Keypad1)) {
SwitchToWeapon(knife ,current);
}
if (Input.GetKey(KeyCode.Keypad2)) {
SwitchToWeapon(pistol ,current);
}
if (Input.GetKey(KeyCode.Keypad3)) {
SwitchToWeapon(customPistol ,current);
}
if (Input.GetKey(KeyCode.Keypad4)) {
SwitchToWeapon(customGun ,current);
}
if (Input.GetKey(KeyCode.Keypad5)) {
SwitchToWeapon(rifle ,current);
}
if (Input.GetKey(KeyCode.Keypad6)) {
SwitchToWeapon(machine ,current);
}
}
void SwitchToWeapon(GameObject weapon , GameObject current){
if (current = null){
current = GameObject.Find("Knife");
}
weapon.SetActive(true);
current.SetActive(false);
}
}
Comment
Best Answer
Answer by perchik · Mar 13, 2014 at 05:25 PM
So, your error message says what's going on.
On line 64, you call current.SetActive(false); and the error says you're trying to reference something that doesn't exist.
That means, current is null, which suggests that GameObject.Find("Knife"); didn't find anything.
Your answer