I have a huge number of weapon in my game and I want the most efficient way to switch between them. I know you can disable and enable weapon but I don’t think its the most efficient way.
Thanks
Sorry for my english (I’m french)
I have a huge number of weapon in my game and I want the most efficient way to switch between them. I know you can disable and enable weapon but I don’t think its the most efficient way.
Thanks
Sorry for my english (I’m french)
The easiest and most efficient way I can think of, is to create a weapon switching script on the player, with 2 public variables:
You can then code it however youd like to switch weapons with the [scroll wheel][1] or [input keys][2], and change the current weapon, to the next element of your array (depending on the direction it should be searching in the array - if they want to switch to a previous weapon for example, it would search 1 UP(–) the array, and next weapon would search 1 DOWN(++) the array)
Generally, that could look something like (C#, all untested code):
//global variables
public GameObject currentWeapon;
public Transform playersHands; //you dont technically NEED this, if you dont have a lot going on in your game, to do a GameObject.Find(), otherwise, it would be best to know exactly where to place the weapon
public GameObject[] WeaponInventory;
private int index = 0; //this will keep track of where you are in your array, when switching weapons
//in Start
currentWeapon = WeaponInventory[0]; //the first index of the array is the weapon they will start with - change "0" to a different number if you want them to start with a different weapon
//in Update
if(Input.GetKeyDown(KeyCode.Q){
//switch to the NEXT weapon
if(index + 1 > WeaponInventory.Lenth){ index = 0; } else { index++;} //keep index, within the bounds of the array -- if they are on the last weapon of the array, loop back to the first weapon
currentWeapon = WeaponInventory*; //switch the weapon*
if(hands.childCount > 0){ //if the player HAS a weapon currently out
Destroy(hands.GetChild(0)); //destroy their current weapon
}
GameObject weapon = (GameObject) Instantiate(currentWeapon,hands.position, hands.rotation); //create their selected weapon at their hands
weapon.transform.parent = hands; //parent the weapon to their hands
//at this point here, is where you can play the weapons “withdraw” or “switching” animation if you have one.
}
You could even go so far to say you dont even need “currentWeapon”, and use the array at the index in the Instantiate.
[1]: Implementing the ScrollWheel: - Questions & Answers - Unity Discussions
[2]: Unity - Scripting API: Input.GetKeyDown