Weapon Switching

Hi,

I’m making a game wherein the main character has a selection of different weapons, and can swap between them on the fly. Currently, the file structure for this is:

Player->Arm->Weapon->FirePoint

This setup allows Arm to rotate (via an attached script), Weapon rotating with it. FirePoint is, well, the place (Transform) where the bullets/crossbow bolts are spawned. Weapon is a GameObject with an attached Sprite Renderer and behaviour Script (so, “Musket.cs” in the case of the Musket weapon). Of note is that Musket.cs includes a MusketBall prefab, where MusketBall is another object with its own behaviour script, (MusketBall.cs). The other three weapons in the game have similar structures (so you could read Crossbow/CrossbowBolt instead of Musket/Musketball).

The problem is this: I want it to be such that, when the user presses a certain button (Say, Mouse2), the equipped weapon cycles to another weapon in a predetermined order (say, if they’re holding Musket then equip Crossbow). My idea was to detect this button press in the script that parses user input, then send the name of the weapon to another script, which would unattach Musket and attach Crossbow. Two problems jump to mind:

  1. Crossbow would need to be attached as a Child of Arm, itself a Child of Player
  2. Ammo, which is a variable stored in the Musket.cs/Crossbow.cs script, would need to be persisted and passed to the new Musket object when the player switches back to their Musket, otherwise the player would be able to refill ammunition by switching weapons, removing the point of their being ammunition in the first place.

(FirePoint is included in the Prefab, and isn’t posing a problem when re-creating the Weapon).

I realise that this is a lengthy question, and appreciate any time spent in answering it.

Thanks

if you dont want inactive weapon to bo visible - attach all of them to Arm and make them inactive. Then just activate one of them and deactivate all others. Script variables will store their values even after deactivate/activate objects (so you will hav correct ammo amount for each weapon).

if you want inactive weapon to stay visible (e.g. to hang behind or be placet to holster) - just set transform.parent of active weapon to Arm, and transform.parent of all other weapons to Holster. And just store link to active weapon somewhere to avoid shooting is your own leg :)))