Switching weapons on a character/Blend trees in blend trees
Of course, you will want to switch the weapons of your character but not all characters have the same idle state depending on the weapon held. Let’s transition between these states and use the inputs 1–3 to swap weapons.
To begin, go to the input system and let’s add the keys 1–3. If you’re building for console, you might need to consider a button that swaps between ints to cycle through the weapons or build an internal UI system.
Next, in the starter assets input, let’s add the input for the weapon choices.
Next, we want to add the weapon functions so when it’s selected, we run a function in custom controls for the guns. Now truthfully, you should create a script just for weapons, but we are simplifying. What we are doing is when we get the bool for the weapon 1 input, we are sending a message to our custom controls to run weapon 1, and then setting it to false so it doesn’t constantly run on input.
In our custom controller, let’s add some headers and discover where our weapons are and where our right hand position is.
Create prefabs for your weapon and instantiate them when pressing the state. Set the weapons in the prefab to a tag called Player Weapon. Then whenever this function is called, it deletes the old weapon and adds the new weapon. As these weapons are instantiated, you should put these into an empty null and adjust the prefab rotation/position so they face the correct way when instantiated.
We now have it where our gun will instantiate, but it’s always in the same exact idle position. You should change the idle position dependent on which gun you use. To do this, let’s go to our animator and delete our old idle state and replace it with a new blend tree.
Now in this new blendtree called our idle blendtree, let’s add 3 different idles — a normal gun, a fighting idle, and a rifle idle. Use a 1D system so we can deal with float values. Create an idle float parameter and dependent on that value- it will determine the idle at which the player sits at.
Next, let’s swap between these states. Create a function called Change idle state. We take in the state value from our equip gun and will lerp between the idle value till we get to the requested state value dependent of what state we choose.
If we pull this off correctly, whenever we choose what gun we want, we can now change the state. In your game, you can set it to where certain cases need a bool check so when you pick up the gun, now certain states become available.