- Home /
Weapon Switch Script Help
Hey guys, Im working on a script to switch weapons. First off, I'm getting a Null Reference Exception error and I'm not sure why. Could you guys help me fix that and add what im trying to add into this script? I wanted to allow the player to switch weapons by scroll the mouse wheel up or down and I wasn't sure how to do that so I left it commented out.
var counter : float = 0;
function Start()
{
counter = 0;
GameObject.Find("FPS_Weapon").SetActiveRecursively(true);
GameObject.Find("Glowstick01").SetActiveRecursively(false);
GameObject.Find("flashlight").SetActiveRecursively(false);
}
function Update ()
{
if (Input.GetKeyDown("1"))
{
counter =0;
}
if (Input.GetKeyDown("2"))
{
counter =1;
}
if (Input.GetKeyDown("3"))
{
counter =2;
}
//allows the player to change weapons by scrolling the mouse as well
//mouse scroll up
//counter = counter +1;
//mouse scroll down
//counter = counter -1;
//prevent scrolling out of 'range'
if (counter == 3)
{
counter = 0;
}
if (counter == -1)
{
counter = 2;
}
//changes weapons based on what the variable 'counter' is equal to
if (counter == 0)
{
GameObject.Find("FPS_Weapon").SetActiveRecursively(true);
GameObject.Find("Glowstick01").SetActiveRecursively(false);
GameObject.Find("flashlight").SetActiveRecursively(false);
}
if (counter == 1)
{
GameObject.Find("Glowstick01").SetActiveRecursively(true);
GameObject.Find("FPS_Weapon").SetActiveRecursively(false);
GameObject.Find("flashlight").SetActiveRecursively(false);
}
if (counter == 2)
{
GameObject.Find("flashlight").SetActiveRecursively(true);
GameObject.Find("FPS_Weapon").SetActiveRecursively(false);
GameObject.Find("Glowstick01").SetActiveRecursively(false);
}
}
Answer by syclamoth · Dec 19, 2011 at 02:16 AM
You should avoid using GameObject.Find whenever you can. Instead, keep inspector-assigned references to all the objects in question, which is faster and more reliable. As it is, without knowing exactly what line the NRE is occuring on (sscce.org guys!), I can only assume that it is happening because at least one of those GameObject.Find calls has a misspelled or non-existant target, and so returns null because the requested object doesn't exist.
In any case, a much nicer way to manage weapons would be to create some kind of 'weapon' class, and then use an array or list of them which can be selected with an int or enum. Each 'weapon' can have different behaviour and renderers, but can be treated the same by the swapper script.
hey when you mean weapon class, do you mean like separate objects? like for example my player objects? then write a script to control them with numeric values? (sorry I am a newbie and was curious about a system like this for a 2D game)
Your answer
Follow this Question
Related Questions
Weapon Switching 2 Answers
WeaponScript not working 0 Answers
Weapon selection system 2 Answers
Magic mouse scroll-wheel 1 Answer
How Does Weapon Selection Work In-Game? 0 Answers