Weapon Cycle in Unity3d

Sharing is caring:

Cycle through Weapons with Arrays

In this Xenosmash tutorial we’ll go over how to cycle between two different weapons using an array. We’ll start off by positioning our weapons against our first person controller. Both weapons should ideally be in the same spot for congruency. Make sure that you have an empty game object that is a child of the camera of our first person controller.

This is where the script will be applied and also where the weapons will be “nested” under as child objects. Make sure both weapons are visible and apply the script to your empty game object. Adjust the array length to fit the size of your weapons available. So if you have two weapons, set the size to 2. You should now be able to cycle, or switch, between your weapons. When one is active, the others are not active and not visible.

 

3D Models Used From

http://turbosquid.com

 

Javascript Files

changeWeapon.js


var weapons : GameObject[]; // Array of Weapons

function Start () {

SelectWeapon(0);//select the weapon you want to start with. "0" is the first weapon in your array

}

function Update () {

if (Input.GetKeyDown("1")) SelectWeapon(0); //selects the first weapon when '1' is pressed

if (Input.GetKeyDown("2")) SelectWeapon(1); //selects the second weapon when '2' is pressed

}

function SelectWeapon(index : int){

for(var obj:GameObject in weapons)obj.SetActive(false); //these lines just cycle through the weapons in our array

weapons[index].SetActive(true); //selects one to be active, and the rest to be inactive

}

 

Jonathan Gonzalez

I love all things in game development and want to contribute by teaching others how to create games. I'm always looking to help others create awesome digital worlds. I've been a hardcore gamer since I was a kid and now it's my turn to create awesome digital experiences.

More Posts - Website

Follow Me:
TwitterYouTube

Speak Your Mind

*