terminalCode Example
PlayerInventory Weapon Switching
PlayerInventory Weapon Switching
Weapon switching with host authority and IPlayerEvents delegation.
CSHARP
public sealed class PlayerInventory : Component, Local.IPlayerEvents
{
[Sync(SyncFlags.FromHost, Change)] public BaseCarryable ActiveWeapon { get; private set; }
public void OnActiveWeaponChanged(BaseCarryable oldWeapon, BaseCarryable newWeapon)
{
if (oldWeapon.IsValid()) oldWeapon.GameObject.Enabled = false;
if (newWeapon.IsValid())
{
newWeapon.GameObject.Enabled = true;
newWeapon.SetDropped(false);
}
}
void Local.IPlayerEvents.OnCameraMove(ref Angles angles)
{
if (!ActiveWeapon.IsValid()) return;
ActiveWeapon.OnCameraMove(Player, ref angles);
}
void Local.IPlayerEvents.OnCameraPostSetup(Sandbox.CameraComponent camera)
{
if (!ActiveWeapon.IsValid()) return;
ActiveWeapon.OnCameraSetup(Player, camera);
}
public void NextWeapon()
{
if (!Networking.IsHost)
{
HostNextWeapon();
return;
}
var weapons = Weapons.ToList();
int currentIndex = ActiveWeapon.IsValid() ? weapons.IndexOf(ActiveWeapon) : -1;
int nextIndex = (currentIndex + 1) % weapons.Count;
SwitchWeapon(weapons[nextIndex]);
}
[Rpc.Host]
private void HostNextWeapon() => NextWeapon();
public void PrevWeapon()
{
if (!Networking.IsHost)
{
HostPrevWeapon();
return;
}
var weapons = Weapons.ToList();
int currentIndex = ActiveWeapon.IsValid() ? weapons.IndexOf(ActiveWeapon) : 0;
int prevIndex = (currentIndex - 1 + weapons.Count) % weapons.Count;
SwitchWeapon(weapons[prevIndex]);
}
[Rpc.Host]
private void HostPrevWeapon() => PrevWeapon();
}Key Features
- Sync'd ActiveWeapon with Change callback for network replication
- Host RPC pattern - Clients request, host executes
- Camera event delegation - Weapons can modify camera
- Circular weapon cycling - Wraps around inventory bounds
Was this helpful?