Switching Weapons

SteveC

Member
Hey y'all!

I'm probably missing something simple, but what's the best way to switch weapons via script? I couldn't find the appropriate script to look @ for examples in the demo or the documentation. Can you point me in the right direction?
 
Much like walking around a Home Depot, I'm glad I asked for directions... it was dirt simple. Here's my working test:

For testing purposes, I used an InputEventManager script to capture KeyDown (it only switches to NextWeapon in this test) and send a UPC event (which are awesome, BTW... another thanks to Justin!) called appropriately "SwitchWeaponsKeyPressed":

InputEventManager:
Code:
using UnityEngine;
using Opsive.UltimateCharacterController.Events;

public class InputEventManager : MonoBehaviour {

    public bool m_CanListenForEvents = true;  
    public KeyCode m_SwitchWeaponsKey;

    void Update () {
        if(m_CanListenForEvents) {
            if(Input.GetKeyDown(m_SwitchWeaponsKey)) {
                Debug.Log ("Sending SwitchWeaponsKeyPressed Event from InputEventManager");
                EventHandler.ExecuteEvent ("SwitchWeaponsKeyPressed");
            }
        }
    }
}
 
(Sorry for doing this across 2 posts, was having issues posting this whole thing into one posting)

... And then TPCInventoryManager ('cause I'm still not used to calling it 'UPC') listens for the "SwitchWeaponsKeyPressed" event:

TPCInventoryManager:

Code:
using UnityEngine;
using Opsive.UltimateCharacterController.Character;
using Opsive.UltimateCharacterController.Character.Abilities.Items;

public class TPCInventoryManager : MonoBehaviour {

    [SerializeField] protected GameObject m_Player;
    [SerializeField] protected UltimateCharacterLocomotion m_CharacterLocomotion;

    void Awake() {
        if(m_Player != null) {
            // Get a reference to UltimateCharacterLocomotion component and register the SwitchWeaponsKeyPressed event
            m_CharacterLocomotion = m_Player.GetComponent<UltimateCharacterLocomotion> ();
            EventHandler.RegisterEvent ("SwitchWeaponsKeyPressed", SwitchToNextWeapon);
        } else {
            // Or die...
            Debug.Log ("m_Player in TPCInventoryManager on: " + gameObject.name + ", has not been set, disabling...");
            this.enabled = false;
        }
    }

    public void SwitchToNextWeapon()
    {
        Debug.Log ("Called SwitchToNextWeapon function in TPCInventoryManager");
        // Roll that beautiful CharacterLocomotion footage!
        if(m_CharacterLocomotion != null) {
            var equipNext = m_CharacterLocomotion.GetAbility <EquipNext>();

            if(equipNext != null) {
                m_CharacterLocomotion.TryStartAbility (equipNext);
            }
        }
    }
}

Thanks much for the pointers and the documentation, Justin!
 
Last edited:
Top