I’m simply trying to switch between two weapon game objects when you press a key. The script prints out “active” and “nonactive” so I know it works, it just doesn’t activate and deactivate the game objects properly, and I have no idea why. Can someone help me out on this?
Here’s the script:
function Update(){
if(Input.GetButtonDown("SwitchWeapons")){
gun = GameObject.FindWithTag("gun");
if(gun.active == true){
gun.SetActiveRecursively(false); //empty and child objects
print("active");
}
else if(gun.active == false){
gun.SetActiveRecursively(true); //empty and child objects
print("nonactive");
}
}
Try assigning the guns to variables at the start of your script. I’d bet the way that you’re finding the game objects is what is making your script work incorrectly. If you had a “for” function in there it might work, but an easier way would be to just define your gun game objects to separate variables at the start of your script
Something like
var gun1 : GameObject;
var gun2 : GameObject;
function Update(){
if(Input.GetButtonDown("SwitchWeapons"))
SwapWeapons();
}
function SwapWeapons(){
if (gun1.active == true) {
gun1.SetActiveRecursively(false);
gun2.SetActiveRecursively(true);
} else {
gun1.SetActiveRecursively(true);
gun2.SetActiveRecursively(false);
}
}
just make the variables swap out when you pick up the new weapons as well. I’m not sure exactly how you’re doing your pick up system, but if I was doing it I’d have the pick up item send a message to the player if they collide/interact with it that contains the gameobject information.
If you used something along these lines it’d should. Of course it’d be on collision or when it’s activated
var prefabToEnable : GameObject;
var player : GameObject;
function Start () {
if (player == null) {
gameObject.find("player");
}
}
function PlayerPicksUpThisWeapon () {
player.SendMessage("PickupWeapon", prefabToEnable, SendMessageOptions.DontRequireReceiver);
}
then on your player gun script you’d make a new function that would add the new weapon in.
function PickupWeapon (pickedupWeapon : GameObject) {
if (gun1.active == true) {
gun1 = pickedupWeapon;
}
if (gun2.active == true) {
gun2 = pickedupWeapon;
}
On the other hand you could go look at the dastardly banana FPS package and see how he did it. It is a pretty solid package and a great base to start from if you’re trying to do a FPS game