NullReferenceException: Object reference not set to an instance of an object
MarsFPSKit.Weapons.Kit_ModernWeaponScriptRuntimeData.FiredWeapon (MarsFPSKit.Kit_PlayerBehaviour target, System.Int32 damageIndex, UnityEngine.Vector3 originPoint, UnityEngine.Vector3 hitPoint) (at Assets/314 Arts/MarsFPSKit/Scripts/Player/Weapons/Kit_ModernWeaponScriptRuntimeData.cs:383)
MarsFPSKit.Weapons.Kit_ModernWeaponScript.FireRaycast (MarsFPSKit.Kit_PlayerBehaviour pb, MarsFPSKit.Weapons.Kit_ModernWeaponScriptRuntimeData data, System.Single delta, System.Single revertBy) (at Assets/314 Arts/MarsFPSKit/Scripts/Player/Weapons/Kit_ModernWeaponScript.cs:3930)
MarsFPSKit.Weapons.Kit_ModernWeaponScript.FireOneShot (MarsFPSKit.Kit_PlayerBehaviour pb, MarsFPSKit.Weapons.Kit_ModernWeaponScriptRuntimeData data, System.Single delta, System.Single revertBy, System.Boolean rpc) (at Assets/314 Arts/MarsFPSKit/Scripts/Player/Weapons/Kit_ModernWeaponScript.cs:3827)
MarsFPSKit.Weapons.Kit_ModernWeaponScript.AuthorativeInput (MarsFPSKit.Kit_PlayerBehaviour pb, MarsFPSKit.Weapons.Kit_WeaponRuntimeDataBase runtimeData, MarsFPSKit.Kit_PlayerInput input, System.Single delta, System.Double revertTime) (at Assets/314 Arts/MarsFPSKit/Scripts/Player/Weapons/Kit_ModernWeaponScript.cs:876)
MarsFPSKit.Weapons.Kit_ModernWeaponManager.AuthorativeInput (MarsFPSKit.Kit_PlayerBehaviour pb, MarsFPSKit.Kit_PlayerInput input, System.Single delta, System.Double revertTime) (at Assets/314 Arts/MarsFPSKit/Scripts/Player/Weapons/Kit_ModernWeaponManager.cs:608)
MarsFPSKit.Weapons.Kit_ModernWeaponManager.PredictionInput (MarsFPSKit.Kit_PlayerBehaviour pb, MarsFPSKit.Kit_PlayerInput input, System.Single delta) (at Assets/314 Arts/MarsFPSKit/Scripts/Player/Weapons/Kit_ModernWeaponManager.cs:614)
MarsFPSKit.Kit_PlayerBehaviour.PredictionInput (MarsFPSKit.Kit_PlayerInput input) (at Assets/314 Arts/MarsFPSKit/Scripts/Player/Kit_PlayerBehaviour.cs:724)
MarsFPSKit.Kit_PlayerBehaviour+<LocalPlayerRoutine>d__64.MoveNext () (at Assets/314 Arts/MarsFPSKit/Scripts/Player/Kit_PlayerBehaviour.cs:496)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <5eddeaad60a14d8ab4eb3a7453824232>:0)


using System.Linq;
using System.Reflection;
using System.Collections;
using UnityEngine;
using Mirror;
using MarsFPSKit;
using MarsFPSKit.Weapons;

[RequireComponent(typeof(Collider))]
public class SimpleWeaponAutoPickupTrigger : NetworkBehaviour
{
    [Header("Weapon Settings")]
    public int weaponID = 0;

    [Header("Ammo Settings")]
    public int bulletsLeft = 30;
    public int bulletsLeftToReload = 60;
    public int[] attachments = new int[0];

    [Header("Respawn Settings")]
    [Tooltip("Seconds to wait before respawning the rotating weapon")]
    public float respawnTime = 10f;

    private Collider col;

    private static FieldInfo weaponsInUseDataObjectsField;
    private static FieldInfo currentWeaponField;

    private void Awake()
    {
        col = GetComponent<Collider>();
        if (!col.isTrigger)
        {
            col.isTrigger = true;
            Debug.LogWarning("Collider was not trigger; forced isTrigger = true.");
        }

        if (!TryGetComponent<Rigidbody>(out Rigidbody rb))
        {
            rb = gameObject.AddComponent<Rigidbody>();
            rb.isKinematic = true;
            Debug.Log("Added kinematic Rigidbody for trigger detection.");
        }

        if (attachments == null || attachments.Length == 0)
        {
            var weaponInfo = Kit_IngameMain.instance.gameInformation.allWeapons[weaponID];
            if (weaponInfo is Kit_ModernWeaponScript modernWeapon)
            {
                attachments = new int[modernWeapon.attachmentSlots.Length];
                for (int i = 0; i < attachments.Length; i++)
                    attachments[i] = 0;
            }
            else attachments = new int[0];
        }
    }

    [ServerCallback]
    private void OnTriggerEnter(Collider other)
    {
        var player = other.GetComponentInParent<Kit_PlayerBehaviour>();
        if (player == null) return;

        TryPickup(player);
    }

    [Server]
    private void TryPickup(Kit_PlayerBehaviour player)
    {
        if (player == null) return;

        var wm = player.weaponManager as Kit_ModernWeaponManager;
        var runtimeData = player.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

        if (wm == null || runtimeData == null)
        {
            Debug.LogWarning("[Server] Player weaponManager or NetworkData is invalid.");
            return;
        }

        if (weaponID < 0 || weaponID >= Kit_IngameMain.instance.gameInformation.allWeapons.Length)
        {
            Debug.LogWarning($"Invalid weaponID {weaponID}");
            return;
        }

        if (runtimeData.weaponsInUseDataObjects.Any(w => w != null && w.id == weaponID))
        {
            Debug.Log($"[Server] Player already has weapon ID {weaponID}.");
            return;
        }

        var weaponInfo = Kit_IngameMain.instance.gameInformation.allWeapons[weaponID];
        int slotToUse = weaponInfo.canFitIntoSlots.Contains(runtimeData.currentWeapon)
            ? runtimeData.currentWeapon
            : (weaponInfo.canFitIntoSlots.Length > 0 ? weaponInfo.canFitIntoSlots[0] : 0);

        if (Kit_IngameMain.instance.gameInformation.enableDropWeaponOnSceneSpawnedWeapons)
        {
            wm.DropWeapon(player, slotToUse);
        }

        int[] finalAttachments = attachments;
        if (weaponInfo is Kit_ModernWeaponScript modernWS)
        {
            if (attachments == null || attachments.Length != modernWS.attachmentSlots.Length)
            {
                finalAttachments = new int[modernWS.attachmentSlots.Length];
                for (int i = 0; i < finalAttachments.Length; i++) finalAttachments[i] = 0;
            }
        }
        else finalAttachments = new int[0];

        int bulletsLeftClamped = bulletsLeft;
        int bulletsLeftToReloadClamped = bulletsLeftToReload;

        if (weaponInfo is Kit_ModernWeaponScript modernWeapon)
        {
            var magMax = modernWeapon.bulletsPerMag;
            if (modernWeapon.reloadMode == ReloadMode.Chambered || modernWeapon.reloadMode == ReloadMode.ProceduralChambered)
                bulletsLeftClamped = Mathf.Clamp(bulletsLeft, 0, magMax + 1);
            else
                bulletsLeftClamped = Mathf.Clamp(bulletsLeft, 0, magMax);

            bulletsLeftToReloadClamped = Mathf.Max(0, bulletsLeftToReload);
        }

        player.ReplaceWeapon(slotToUse, weaponID, bulletsLeftClamped, bulletsLeftToReloadClamped, finalAttachments);

        var equippedRuntime = GetRuntimeDataForSlot(wm, slotToUse);
        if (equippedRuntime != null && equippedRuntime is Kit_ModernWeaponScriptRuntimeData modernRuntime)
        {
            player.StartCoroutine(AssignPlayerReferenceNextFrame(modernRuntime, player));
        }
        else
        {
            Debug.LogWarning($"[Server] Could not get runtime data for slot {slotToUse}.");
        }

        // Weapon visibility & selection (try methods, fallback to reflection)
        var selectMethod = wm.GetType().GetMethod("AuthoritativeSelectWeapon", BindingFlags.Public | BindingFlags.Instance);
        var equipMethod = wm.GetType().GetMethod("EquipWeapon", BindingFlags.Public | BindingFlags.Instance);
        var drawMethod = wm.GetType().GetMethod("DrawWeapon", BindingFlags.Public | BindingFlags.Instance);

        if (selectMethod != null)
        {
            selectMethod.Invoke(wm, new object[] { slotToUse });
            if (equipMethod != null)
                equipMethod.Invoke(wm, new object[] { slotToUse, equippedRuntime });
            else if (drawMethod != null)
                drawMethod.Invoke(wm, new object[] { slotToUse, equippedRuntime });
        }
        else
        {
            if (currentWeaponField == null)
                currentWeaponField = wm.GetType().GetField("currentWeapon", BindingFlags.NonPublic | BindingFlags.Instance);

            if (currentWeaponField != null)
                currentWeaponField.SetValue(wm, slotToUse);
            else
                Debug.LogWarning("Reflection could not find 'currentWeapon' field!");

            if (drawMethod != null)
                drawMethod.Invoke(wm, new object[] { slotToUse, equippedRuntime });
            else
                Debug.LogWarning("Could not find DrawWeapon method via reflection!");
        }

        Debug.Log($"[Server] Player {player.netId} picked up weapon ID {weaponID} in slot {slotToUse}.");

        RpcDisablePickup();

        if (WeaponPickupRespawner.Instance != null)
            WeaponPickupRespawner.Instance.ScheduleRespawn(gameObject, respawnTime);
        else
            Debug.LogWarning("WeaponPickupRespawner instance not found, cannot schedule respawn.");
    }

    private IEnumerator AssignPlayerReferenceNextFrame(Kit_ModernWeaponScriptRuntimeData runtimeData, Kit_PlayerBehaviour player)
    {
        yield return null; // wait a frame for full internal initialization
        yield return null;

        if (runtimeData != null)
        {
            runtimeData.pb = player;
            Debug.Log("[Server] Assigned player reference to weapon runtime data.");
        }
    }

    [ClientRpc]
    private void RpcDisablePickup()
    {
        gameObject.SetActive(false);
    }

    [Server]
    public void RespawnPickup()
    {
        // Reset pickup state as needed before enabling:
        if (col != null) col.enabled = true;

        if (!gameObject.activeSelf)
            gameObject.SetActive(true);

        Debug.Log($"[Server] Pickup '{gameObject.name}' respawned and ready.");
    }

    private Kit_WeaponRuntimeDataBase GetRuntimeDataForSlot(Kit_ModernWeaponManager wm, int slot)
    {
        if (wm == null) return null;

        if (weaponsInUseDataObjectsField == null)
        {
            weaponsInUseDataObjectsField = typeof(Kit_ModernWeaponManager).GetField(
                "weaponsInUseDataObjects", BindingFlags.NonPublic | BindingFlags.Instance);

            if (weaponsInUseDataObjectsField == null)
            {
                Debug.LogWarning("Reflection failed to get 'weaponsInUseDataObjects' field.");
                return null;
            }
        }

        var arr = weaponsInUseDataObjectsField.GetValue(wm) as Kit_WeaponRuntimeDataBase[];
        if (arr == null || slot < 0 || slot >= arr.Length) return null;

        return arr[slot];
    }
}

using Mirror;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using UnityEngine;

namespace MarsFPSKit
{
    namespace Weapons
    {
        /// <summary>
        /// Input that is allowed for the given weapon slot
        /// </summary>
        [System.Serializable]
        public class WeaponManagerSlot
        {
            /// <summary>
            /// Can weapons in this slot be equipped?
            /// </summary>
            public bool enableEquipping = true;
            /// <summary>
            /// ID of <see cref="Kit_PlayerInput.weaponSlotUses"/>
            /// </summary>
            public int equippingInputID;
            /// <summary>
            /// Can weapons in this slot be quick used (e.g. quick grenades, quick knife)
            /// </summary>
            public bool enableQuickUse;
            /// <summary>
            /// ID of <see cref="Kit_PlayerInput.weaponSlotUses"/>
            /// </summary>
            public int quickUseInputID;
        }

        public enum DeadDrop { None, Selected, All }

        /// <summary>
        /// This is a modern, generic weapon manager. Weapons are put away and then taken out, like in COD or Battlefield. Supports an "infinite" amount of weapons
        /// </summary>
        [CreateAssetMenu(menuName = ("MarsFPSKit/Weapons/Modern Weapon Manager"))]
        public class Kit_ModernWeaponManager : Kit_WeaponManagerBase
        {
            public WeaponManagerSlot[] slotConfiguration;
            /// <summary>
            /// Main drop prefab!
            /// </summary>
            public GameObject dropPrefab;
            /// <summary>
            /// Layers that will be hit by the pickup raycast
            /// </summary>
            public LayerMask pickupLayers;
            /// <summary>
            /// Distance for the pickup raycast
            /// </summary>
            public float pickupDistance = 3f;
            /// <summary>
            /// Which weapons should be dropped upon death?
            /// </summary>
            public DeadDrop uponDeathDrop;
            /// <summary>
            /// How fast does the weapon position change?
            /// </summary>
            public float weaponPositionChangeSpeed = 5f;
            /// <summary>
            /// Can we switch while we are running?
            /// </summary>
            public bool allowSwitchingWhileRunning;
            /// <summary>
            /// Can we do quick use while running?
            /// </summary>
            public bool allowQuickUseWhileRunning;

            public override void OnWeaponsInUseSyncCallback(Kit_PlayerBehaviour pb, SyncList<uint>.Operation op, int itemIndex, uint item)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

                switch (op)
                {
                    case SyncList<uint>.Operation.OP_SET:
                        //Cleanup old data first
                        for (int i = 0; i < runtimeData.weaponsInUseDataObjects[itemIndex].instantiatedObjects.Count; i++)
                        {
                            if (runtimeData.weaponsInUseDataObjects[itemIndex].instantiatedObjects[i])
                            {
                                NetworkIdentity nid = runtimeData.weaponsInUseDataObjects[itemIndex].instantiatedObjects[i].GetComponentInChildren<NetworkIdentity>();

                                if (nid)
                                {
                                    if (NetworkServer.active)
                                    {
                                        NetworkServer.Destroy(nid.gameObject);
                                    }
                                }
                                else
                                {
                                    Destroy(runtimeData.weaponsInUseDataObjects[itemIndex].instantiatedObjects[i]);
                                }
                            }
                        }

                        runtimeData.weaponsInUseDataObjects[itemIndex].instantiatedObjects.Clear();

                        //We may need to wait a bit for the network
                        Kit_ScriptableObjectCoroutineHelper.instance.StartCoroutine(Kit_ScriptableObjectCoroutineHelper.instance.NetworkReplaceWeapon(pb, runtimeData, itemIndex, runtimeData.weaponsInUseSync[itemIndex]));
                        break;
                }
            }

            public override void SetupSpawnData(Kit_PlayerBehaviour pb, Loadout loadout, NetworkConnectionToClient sender)
            {
                GameObject data = Instantiate(networkData, Vector3.zero, Quaternion.identity);
                Kit_ModernWeaponManagerNetworkData runtimeData = data.GetComponent<Kit_ModernWeaponManagerNetworkData>();
                pb.weaponManagerNetworkData = runtimeData;

                for (int i = 0; i < loadout.loadoutWeapons.Length; i++)
                {
                    GameObject spawnObject = Kit_IngameMain.instance.gameInformation.allWeapons[loadout.loadoutWeapons[i].weaponID].SetupSpawnData(pb, i, loadout.loadoutWeapons[i]);
                    NetworkServer.Spawn(spawnObject, sender);
                    NetworkIdentity id = spawnObject.GetComponent<NetworkIdentity>();

                    //Add to our weapon list
                    runtimeData.weaponsInUseSync.Add(id.netId);
                }
            }

            public override void SetupSpawnData(Kit_PlayerBehaviour pb, Loadout loadout)
            {
                GameObject data = Instantiate(networkData, Vector3.zero, Quaternion.identity);
                Kit_ModernWeaponManagerNetworkData runtimeData = data.GetComponent<Kit_ModernWeaponManagerNetworkData>();
                pb.weaponManagerNetworkData = runtimeData;

                for (int i = 0; i < loadout.loadoutWeapons.Length; i++)
                {
                    GameObject spawnObject = Kit_IngameMain.instance.gameInformation.allWeapons[loadout.loadoutWeapons[i].weaponID].SetupSpawnData(pb, i, loadout.loadoutWeapons[i]);
                    NetworkServer.Spawn(spawnObject);
                    NetworkIdentity id = spawnObject.GetComponent<NetworkIdentity>();

                    //Add to our weapon list
                    runtimeData.weaponsInUseSync.Add(id.netId);
                }
            }

            public override void InitializeServer(Kit_PlayerBehaviour pb)
            {
                //Is created in SetupSpawnData
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                runtimeData.ownerPlayerNetworkId = pb.netId;
                //Spawn it here
                if (pb.isBot)
                    NetworkServer.Spawn(runtimeData.gameObject);
                else
                    NetworkServer.Spawn(runtimeData.gameObject, pb.gameObject);

                //Setup input IDs
                runtimeData.lastInputIDs = new bool[pb.input.weaponSlotUses.Length];

                //Initially build list
                runtimeData.weaponsInUseDataObjects = new Kit_WeaponRuntimeDataBase[runtimeData.weaponsInUseSync.Count];

                for (int i = 0; i < runtimeData.weaponsInUseSync.Count; i++)
                {
                    NetworkIdentity id = null;

                    if (NetworkServer.active)
                    {
                        id = NetworkServer.spawned[runtimeData.weaponsInUseSync[i]];
                    }
                    else
                    {
                        id = NetworkClient.spawned[runtimeData.weaponsInUseSync[i]];
                    }

                    if (id)
                    {
                        runtimeData.weaponsInUseDataObjects[i] = id.GetComponent<Kit_WeaponRuntimeDataBase>();
                    }
                    else
                    {
                        //Didn't find it. This shouldn't happen!
                        runtimeData.weaponsInUseDataObjects[i] = null;
                    }
                }

                for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                {
                    int slot = i;
                    int id = runtimeData.weaponsInUseDataObjects[slot].id;
                    //Get their behaviour modules
                    Kit_WeaponBase weaponBehaviour = pb.gameInformation.allWeapons[id];
                    //Assign Behaviour
                    runtimeData.weaponsInUseDataObjects[slot].behaviour = weaponBehaviour;
                    runtimeData.weaponsInUseDataObjects[slot].pb = pb;
                    //Setup FP
                    weaponBehaviour.SetupFirstPerson(pb, runtimeData.weaponsInUseDataObjects[slot]);
                    //Setup TP
                    weaponBehaviour.SetupThirdPerson(pb, runtimeData.weaponsInUseDataObjects[slot]);
                }

                SelectDefaultWeapon(pb, runtimeData);

                //Set time
                runtimeData.switchNextEnd = Time.time + runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.drawTime;
                //Set phase
                runtimeData.switchPhase = 1;
                //Set switching
                runtimeData.switchInProgress = true;
            }

            public override void InitializeClient(Kit_PlayerBehaviour pb)
            {
                if (!pb.weaponManagerNetworkData)
                {
                    //Find ours
                    pb.weaponManagerNetworkData = FindObjectsOfType<Kit_ModernWeaponManagerNetworkData>().Where(x => x.ownerPlayerNetworkId == pb.netId).FirstOrDefault();
                }

                if (pb.isClientOnly)
                {
                    Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

                    //Setup input IDs
                    runtimeData.lastInputIDs = new bool[pb.input.weaponSlotUses.Length];

                    //Initially build list
                    runtimeData.weaponsInUseDataObjects = new Kit_WeaponRuntimeDataBase[runtimeData.weaponsInUseSync.Count];

                    for (int i = 0; i < runtimeData.weaponsInUseSync.Count; i++)
                    {
                        NetworkIdentity id = null;

                        if (NetworkServer.active)
                        {
                            id = NetworkServer.spawned[runtimeData.weaponsInUseSync[i]];
                        }
                        else
                        {
                            id = NetworkClient.spawned[runtimeData.weaponsInUseSync[i]];
                        }

                        if (id)
                        {
                            runtimeData.weaponsInUseDataObjects[i] = id.GetComponent<Kit_WeaponRuntimeDataBase>();
                        }
                        else
                        {
                            //Didn't find it. This shouldn't happen!
                            runtimeData.weaponsInUseDataObjects[i] = null;
                        }
                    }

                    for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                    {
                        int slot = i;
                        int id = runtimeData.weaponsInUseDataObjects[slot].id;
                        //Get their behaviour modules
                        Kit_WeaponBase weaponBehaviour = pb.gameInformation.allWeapons[id];
                        //Assign Behaviour
                        runtimeData.weaponsInUseDataObjects[slot].behaviour = weaponBehaviour;
                        runtimeData.weaponsInUseDataObjects[slot].pb = pb;
                        //Setup FP
                        weaponBehaviour.SetupFirstPerson(pb, runtimeData.weaponsInUseDataObjects[slot]);
                        //Setup TP
                        weaponBehaviour.SetupThirdPerson(pb, runtimeData.weaponsInUseDataObjects[slot]);
                    }

                    SelectDefaultWeapon(pb, runtimeData);

                    //Set time
                    runtimeData.switchNextEnd = Time.time + runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.drawTime;
                    //Set phase
                    runtimeData.switchPhase = 1;
                    //Set switching
                    runtimeData.switchInProgress = true;
                }
            }

            /// <summary>
            /// Selects the first weapon
            /// </summary>
            /// <param name="pb"></param>
            /// <param name="runtimeData"></param>
            void SelectDefaultWeapon(Kit_PlayerBehaviour pb, Kit_ModernWeaponManagerNetworkData runtimeData)
            {
                //Select default weapon
                for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                {
                    if (i < slotConfiguration.Length && slotConfiguration[i].enableEquipping)
                    {
                        if (runtimeData.weaponsInUseDataObjects[i].behaviour.CanBeSelected(pb, runtimeData.weaponsInUseDataObjects[i]))
                        {
                            int id = i;
                            //Select current weapon
                            runtimeData.weaponsInUseDataObjects[i].behaviour.DrawWeapon(pb, runtimeData.weaponsInUseDataObjects[i]);
                            //Play Third person animation
                            pb.thirdPersonPlayerModel.PlayWeaponChangeAnimation(runtimeData.weaponsInUseDataObjects[i].behaviour.thirdPersonAnimType, true, runtimeData.weaponsInUseDataObjects[i].behaviour.drawTime);
                            //Set current weapon
                            runtimeData.desiredWeapon = runtimeData.currentWeapon = id;
                            return;
                        }

                    }
                }
            }

            public override void TakeControl(Kit_PlayerBehaviour pb)
            {
                //Hide crosshair
                Kit_IngameMain.instance.hud.DisplayCrosshair(0f, false);

            }

            public override void ForceUnselectCurrentWeapon(Kit_PlayerBehaviour pb)
            {
                Debug.Log("[Weapon Manager] Forcing unselect of current weapon!");
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                bool foundWeapon = false;
                //Try to find next weapon
                int next = -1;
                for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                {
                    if (foundWeapon) break;


                    if (!runtimeData.weaponsInUseDataObjects[i].isInjectedFromPlugin)
                    {
                        //Check if this one works!
                        if (runtimeData.weaponsInUseDataObjects[i].behaviour.CanBeSelected(pb, runtimeData.weaponsInUseDataObjects[i]))
                        {
                            int id = i;
                            next = id;
                            //We found one
                            foundWeapon = true;
                            break;
                        }
                    }

                }

                //This should ALWAYS be true!
                if (next >= 0)
                {
                    runtimeData.desiredWeapon = next;
                    //Begin switch and skip putaway
                    runtimeData.switchInProgress = true;
                    //Set time (Because here we cannot use a coroutine)
                    runtimeData.switchNextEnd = 0f;
                    //Set phase
                    runtimeData.switchPhase = 0;
                    if (pb.isFirstPersonActive)
                    {
                        //Hide crosshair
                        Kit_IngameMain.instance.hud.DisplayCrosshair(0f, false);
                    }
                    //Set current one too!
                    runtimeData.currentWeapon = next;
                }
                else
                {
                    Debug.LogError("Could not find next weapon! This is not allowed!");
                }
            }

            public override void AuthorativeInput(Kit_PlayerBehaviour pb, Kit_PlayerInput input, float delta, double revertTime)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

                if (Physics.Raycast(pb.playerCameraTransform.position, pb.playerCameraTransform.forward, out runtimeData.hit, pickupDistance, pickupLayers.value))
                {
                    if (runtimeData.hit.transform.root.GetComponent<Kit_DropBehaviour>())
                    {
                        Kit_DropBehaviour drop = runtimeData.hit.transform.root.GetComponent<Kit_DropBehaviour>();
                        if (pb.isFirstPersonActive)
                        {
                            Kit_IngameMain.instance.hud.DisplayWeaponPickup(true, drop.weaponID);
                            Kit_IngameMain.instance.hud.DisplayInteraction(false);
                        }

                        if (runtimeData.lastInteract != input.interact && pb.isServer)
                        {
                            runtimeData.lastInteract = input.interact;
                            if (input.interact && (allowSwitchingWhileRunning || !pb.movement.IsRunning(pb)))
                            {
                                int slot = 0;

                                if (Kit_IngameMain.instance.gameInformation.allWeapons[drop.weaponID].canFitIntoSlots.Contains(runtimeData.currentWeapon))
                                {
                                    slot = runtimeData.currentWeapon;
                                }
                                else
                                {
                                    slot = Kit_IngameMain.instance.gameInformation.allWeapons[drop.weaponID].canFitIntoSlots[0];
                                }

                                //Check if we can drop
                                if (!drop.isSceneOwned || drop.isSceneOwned && Kit_IngameMain.instance.gameInformation.enableDropWeaponOnSceneSpawnedWeapons)
                                {
                                    //First drop our weapon
                                    DropWeapon(pb, slot, drop.transform);
                                }

                                pb.ReplaceWeapon(slot, drop.weaponID, drop.bulletsLeft, drop.bulletsLeftToReload, drop.attachments.ToArray());

                                drop.PickedUp();
                            }
                        }
                    }
                    else if (runtimeData.hit.transform.GetComponentInParent<Kit_InteractableObject>())
                    {
                        Kit_InteractableObject io = runtimeData.hit.transform.GetComponentInParent<Kit_InteractableObject>();

                        if (io.CanInteract(pb))
                        {
                            if (pb.isFirstPersonActive)
                            {
                                Kit_IngameMain.instance.hud.DisplayWeaponPickup(false);
                                Kit_IngameMain.instance.hud.DisplayInteraction(true, io.interactionText);
                            }

                            if (io.IsHold())
                            {
                                if (input.interact)
                                {
                                    //Store object
                                    runtimeData.holdingInteractableObject = io;

                                    //Tell object we want to interact
                                    io.Interact(pb);
                                }
                                else
                                {
                                    if (runtimeData.holdingInteractableObject)
                                    {
                                        runtimeData.holdingInteractableObject.InteractHoldEnd(pb);
                                        runtimeData.holdingInteractableObject = null;
                                    }
                                }
                            }
                            else
                            {
                                if (runtimeData.lastInteract != input.interact)
                                {
                                    runtimeData.lastInteract = input.interact;
                                    if (input.interact && NetworkServer.active)
                                    {
                                        //Tell object we want to interact
                                        io.Interact(pb);
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (pb.isFirstPersonActive)
                            {
                                Kit_IngameMain.instance.hud.DisplayWeaponPickup(false);
                                Kit_IngameMain.instance.hud.DisplayInteraction(false);
                            }

                            if (runtimeData.holdingInteractableObject)
                            {
                                runtimeData.holdingInteractableObject.InteractHoldEnd(pb);
                                runtimeData.holdingInteractableObject = null;
                            }
                        }
                    }
                    else
                    {
                        if (pb.isFirstPersonActive)
                        {
                            Kit_IngameMain.instance.hud.DisplayWeaponPickup(false);
                            Kit_IngameMain.instance.hud.DisplayInteraction(false);
                        }

                        if (runtimeData.holdingInteractableObject)
                        {
                            runtimeData.holdingInteractableObject.InteractHoldEnd(pb);
                            runtimeData.holdingInteractableObject = null;
                        }
                    }
                }
                else
                {
                    if (pb.isFirstPersonActive)
                    {
                        Kit_IngameMain.instance.hud.DisplayWeaponPickup(false);
                        Kit_IngameMain.instance.hud.DisplayInteraction(false);
                    }

                    if (runtimeData.holdingInteractableObject)
                    {
                        runtimeData.holdingInteractableObject.InteractHoldEnd(pb);
                        runtimeData.holdingInteractableObject = null;
                    }
                }

                if (!runtimeData.isDesiredWeaponLocked)
                {
                    for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                    {
                        if (!runtimeData.weaponsInUseDataObjects[i].isInjectedFromPlugin)
                        {
                            if (slotConfiguration.Length > i)
                            {
                                if (slotConfiguration[i].enableEquipping && slotConfiguration[i].equippingInputID >= 0 && !runtimeData.quickUseInProgress)
                                {
                                    if (runtimeData.lastInputIDs[slotConfiguration[i].equippingInputID] != input.weaponSlotUses[slotConfiguration[i].equippingInputID])
                                    {
                                        runtimeData.lastInputIDs[slotConfiguration[i].equippingInputID] = input.weaponSlotUses[slotConfiguration[i].equippingInputID];
                                        //Check for input
                                        if (input.weaponSlotUses[slotConfiguration[i].equippingInputID] && (allowSwitchingWhileRunning || !pb.movement.IsRunning(pb)))
                                        {
                                            int id = i;
                                            if (runtimeData.desiredWeapon != id)
                                            {
                                                if (runtimeData.weaponsInUseDataObjects[i].behaviour.CanBeSelected(pb, runtimeData.weaponsInUseDataObjects[i]))
                                                {
                                                    runtimeData.desiredWeapon = id;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (input.nextWeapon)
                    {
                        int nextWeapon = runtimeData.desiredWeapon + 1;
                        if (nextWeapon >= runtimeData.weaponsInUseSync.Count) nextWeapon = 0;
                        while (runtimeData.weaponsInUseDataObjects[nextWeapon].isInjectedFromPlugin || !runtimeData.weaponsInUseDataObjects[nextWeapon].behaviour.CanBeSelected(pb, runtimeData.weaponsInUseDataObjects[nextWeapon]))
                        {
                            nextWeapon++;
                            if (nextWeapon >= runtimeData.weaponsInUseSync.Count) nextWeapon = 0;
                        }

                        runtimeData.desiredWeapon = nextWeapon;
                    }
                    else if (input.previousWeapon)
                    {
                        int previousWeapon = runtimeData.desiredWeapon - 1;
                        if (previousWeapon < 0) previousWeapon = runtimeData.weaponsInUseDataObjects.Length - 1;
                        while (runtimeData.weaponsInUseDataObjects[previousWeapon].isInjectedFromPlugin || !runtimeData.weaponsInUseDataObjects[previousWeapon].behaviour.CanBeSelected(pb, runtimeData.weaponsInUseDataObjects[previousWeapon]))
                        {
                            previousWeapon--;
                            if (previousWeapon < 0) previousWeapon = runtimeData.weaponsInUseDataObjects.Length - 1;
                        }

                        runtimeData.desiredWeapon = previousWeapon;
                    }

                    //Check if we can do a quick use!
                    if (runtimeData.currentWeapon == runtimeData.desiredWeapon && !runtimeData.switchInProgress)
                    {
                        if (!runtimeData.quickUseInProgress)
                        {
                            for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                            {
                                if (!runtimeData.weaponsInUseDataObjects[i].isInjectedFromPlugin)
                                {
                                    int slot = i;
                                    if (slotConfiguration.Length > slot)
                                    {
                                        if (slotConfiguration[slot].enableQuickUse)
                                        {
                                            if (slotConfiguration[slot].quickUseInputID >= 0)
                                            {
                                                if (runtimeData.lastInputIDs[slotConfiguration[slot].quickUseInputID] != input.weaponSlotUses[slotConfiguration[slot].quickUseInputID])
                                                {
                                                    runtimeData.lastInputIDs[slotConfiguration[slot].quickUseInputID] = input.weaponSlotUses[slotConfiguration[slot].quickUseInputID];
                                                    //Check for input
                                                    if (input.weaponSlotUses[slotConfiguration[slot].quickUseInputID] && (allowQuickUseWhileRunning || !pb.movement.IsRunning(pb)))
                                                    {
                                                        if (runtimeData.weaponsInUseDataObjects[slot].behaviour.SupportsQuickUse(pb, runtimeData.weaponsInUseDataObjects[slot]))
                                                        {
                                                            runtimeData.desiredQuickUse = slot;
                                                            runtimeData.quickUseInProgress = true;
                                                            //Also reset these!
                                                            runtimeData.quickUseState = 0;
                                                            runtimeData.quickUseOverAt = Time.time;
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (runtimeData.quickUseState == 2)
                            {
                                //Check if quick use button needs to be released
                                if (runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse].behaviour.WaitForQuickUseButtonRelease(pb, runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse]) && (!pb.input.weaponSlotUses[slotConfiguration[runtimeData.desiredQuickUse].quickUseInputID]))
                                {
                                    runtimeData.quickUseSyncButtonWaitOver = true;
                                }
                            }
                        }
                    }
                }

                if (!runtimeData.switchInProgress && !runtimeData.quickUseInProgress)
                {
                    runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.AuthorativeInput(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon], input, delta, revertTime);
                }
            }

            public override void PredictionInput(Kit_PlayerBehaviour pb, Kit_PlayerInput input, float delta)
            {
                AuthorativeInput(pb, input, delta, 0f);
            }

            public override void CustomUpdate(Kit_PlayerBehaviour pb, double revertBy)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                // ======= Updated Auto-Switch on Weapon Out of Ammo - START =======
                if (runtimeData != null && !runtimeData.switchInProgress && runtimeData.currentWeapon >= 0 && runtimeData.currentWeapon < runtimeData.weaponsInUseDataObjects.Length)
                {
                    var currentWeaponData = runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon] as Kit_ModernWeaponScriptRuntimeData;

                    if (currentWeaponData != null)
                    {
                        bool outOfAmmo = (currentWeaponData.bulletsLeft == 0 && currentWeaponData.bulletsLeftToReload == 0);

                        if (outOfAmmo)
                        {
                            int nextWeaponSlot = -1;
                            int weaponCount = runtimeData.weaponsInUseDataObjects.Length;
                            int startIndex = (runtimeData.currentWeapon + 1) % weaponCount;

                            for (int iOffset = 0; iOffset < weaponCount; iOffset++)
                            {
                                int i = (startIndex + iOffset) % weaponCount;

                                if (i == runtimeData.currentWeapon) continue;

                                var wpnData = runtimeData.weaponsInUseDataObjects[i] as Kit_ModernWeaponScriptRuntimeData;
                                if (wpnData == null) continue;

                                // Check if this weapon can be selected (i.e. is valid)
                                bool canSelect = wpnData.behaviour.CanBeSelected(pb, wpnData);

                                // Assume melee has no ammo by definition, so we treat any selectable weapon as valid here
                                if (canSelect)
                                {
                                    // Decide if weapon has ammo or is melee/no-ammo
                                    bool hasAmmo = (wpnData.bulletsLeft > 0 || wpnData.bulletsLeftToReload > 0);

                                    // Include weapon even if no ammo, to handle melee (bat) which has 0 ammo
                                    if (hasAmmo || !HasAmmo(wpnData))
                                    {
                                        nextWeaponSlot = i;
                                        break;
                                    }
                                }
                            }

                            if (nextWeaponSlot >= 0)
                            {
                                runtimeData.desiredWeapon = nextWeaponSlot;
                                runtimeData.switchInProgress = true;
                                runtimeData.switchNextEnd = Time.time + currentWeaponData.behaviour.putawayTime;
                                runtimeData.switchPhase = 0;

                                if (pb.isFirstPersonActive)
                                {
                                    Kit_IngameMain.instance.hud.DisplayCrosshair(0f, false);
                                }
                            }
                        }
                    }
                }

                // Helper method to detect if weapon expects ammo
                bool HasAmmo(Kit_ModernWeaponScriptRuntimeData data)
                {
                    // We determine no ammo type by fire mode = melee (that you can adjust)
                    // For your setup, you may need to detect more precisely via the weapon's class/type.
                    if (data == null) return false;

                    // For example: check weaponID or fireMode or other custom logic here
                    // Let's say melee weapons have fireMode = None (OR you can check data.bulletsPerMag <= 0)
                    // Adjust this check based on your weapon data

                    // Assuming if bulletsPerMag <= 0 it's no-ammo melee
                    return data.bulletsPerMag > 0;
                }
                // ======= Updated Auto-Switch on Weapon Out of Ammo - END =======


                //Quick use has priority!
                if ((runtimeData.quickUseInProgress || runtimeData.quickUseState > 0) && runtimeData.desiredQuickUse >= 0)
                {
                    //Update weapon animation
                    runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse].behaviour.AnimateWeapon(pb, runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse], pb.movement.GetCurrentWeaponMoveAnimation(pb), pb.movement.GetCurrentWalkAnimationSpeed(pb));

                    if (Time.time >= runtimeData.quickUseOverAt)
                    {
                        //First, put away current weapon!
                        if (runtimeData.quickUseState == 0)
                        {
                            if (!runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse].behaviour.QuickUseSkipsPutaway(pb, runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse]))
                            {
                                //Set time (Because here we cannot use a coroutine)
                                runtimeData.quickUseOverAt = Time.time + runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.putawayTime;
                                //Set phase
                                runtimeData.quickUseState = 1;
                                //Start putaway
                                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.PutawayWeapon(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
                                //Play Third person animation
                                pb.thirdPersonPlayerModel.PlayWeaponChangeAnimation(runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.thirdPersonAnimType, false, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.putawayTime);
                                if (pb.isFirstPersonActive)
                                {
                                    //Hide crosshair
                                    Kit_IngameMain.instance.hud.DisplayCrosshair(0f, false);
                                }
                            }
                            else
                            {
                                //Set phase
                                runtimeData.quickUseState = 1;
                                if (pb.isFirstPersonActive)
                                {
                                    //Hide crosshair
                                    Kit_IngameMain.instance.hud.DisplayCrosshair(0f, false);
                                }
                            }
                        }
                        else if (runtimeData.quickUseState == 1)
                        {
                            //Weapon has been put away, hide weapon
                            runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.PutawayWeaponHide(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
                            runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.QuickUseOnOtherWeaponBegin(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);

                            //Set state
                            runtimeData.quickUseState = 2;

                            //Begin quick use....
                            runtimeData.quickUseOverAt = Time.time + runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse].behaviour.BeginQuickUse(pb, runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse], (float)revertBy);
                        }
                        else if (runtimeData.quickUseState == 2)
                        {
                            //Check if weapon wants to abort quick use
                            if (!runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse].behaviour.SupportsQuickUse(pb, runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse]) ||
                                //Check if we don't need to wait for the button
                                (!runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse].behaviour.WaitForQuickUseButtonRelease(pb, runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse])) ||
                                //Or button was released via sync
                                (runtimeData.quickUseSyncButtonWaitOver))
                            {
                                runtimeData.quickUseSyncButtonWaitOver = true;
                                //Set State
                                runtimeData.quickUseState = 3;
                                //End quick use...
                                runtimeData.quickUseOverAt = Time.time + runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse].behaviour.EndQuickUse(pb, runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse], (float)revertBy);
                            }
                        }
                        else if (runtimeData.quickUseState == 3)
                        {
                            //Hide Quick Use!
                            runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse].behaviour.EndQuickUseAfter(pb, runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse], (float)revertBy);
                            //Check if currently selected  weapon is valid.
                            if (runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.CanBeSelected(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]))
                            {
                                //Set weapon
                                runtimeData.currentWeapon = runtimeData.desiredWeapon;
                            }
                            else
                            {
                                //Its not, find a new one
                                int next = 0;
                                for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                                {
                                    //Check if this one works!
                                    if (runtimeData.weaponsInUseDataObjects[i].behaviour.CanBeSelected(pb, runtimeData.weaponsInUseDataObjects[i]))
                                    {
                                        int id = i;
                                        next = id;
                                        //We found one
                                        break;
                                    }
                                }

                                //This should ALWAYS be true!
                                if (next >= 0)
                                {
                                    runtimeData.desiredWeapon = next;
                                    //Set current one too!
                                    runtimeData.currentWeapon = next;
                                }
                                else
                                {
                                    Debug.LogError("Could not find next weapon! This is not allowed!");
                                }
                            }

                            //Draw that weapon
                            runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.DrawWeapon(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
                            //Play Third person animation
                            pb.thirdPersonPlayerModel.PlayWeaponChangeAnimation(runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.thirdPersonAnimType, true, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.drawTime);
                            //Set phase
                            runtimeData.quickUseState = 4;
                            //Set time
                            runtimeData.quickUseOverAt = Time.time + runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.drawTime;
                            //Done, now wait
                        }
                        else if (runtimeData.quickUseState == 4)
                        {
                            //End quick use
                            runtimeData.quickUseInProgress = false;
                            runtimeData.desiredQuickUse = -1;
                            runtimeData.quickUseSyncButtonWaitOver = false;
                            runtimeData.quickUseState = 0;
                            runtimeData.quickUseOverAt = Time.time;

                            //Also reset switching just to be sure!
                            runtimeData.switchPhase = 0;
                            runtimeData.switchNextEnd = 0f;
                            runtimeData.switchInProgress = false;
                        }
                    }
                }
                else
                {
                    //Update weapon animation
                    runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.AnimateWeapon(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon], pb.movement.GetCurrentWeaponMoveAnimation(pb), pb.movement.GetCurrentWalkAnimationSpeed(pb));

                    if (!runtimeData.switchInProgress)
                    {
                        //If we aren't switching weapons, update weapon behaviour
                        runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.CalculateWeaponUpdate(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);

                        //Check if we want to select a different weapon
                        if (runtimeData.desiredWeapon != runtimeData.currentWeapon)
                        {
                            //If not, start to switch
                            runtimeData.switchInProgress = true;
                            //Set time (Because here we cannot use a coroutine)
                            runtimeData.switchNextEnd = Time.time + runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.putawayTime;
                            //Set phase
                            runtimeData.switchPhase = 0;
                            //Start putaway
                            runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.PutawayWeapon(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
                            //Play Third person animation
                            pb.thirdPersonPlayerModel.PlayWeaponChangeAnimation(runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.thirdPersonAnimType, false, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.putawayTime);
                            if (pb.isFirstPersonActive)
                            {
                                //Hide crosshair
                                Kit_IngameMain.instance.hud.DisplayCrosshair(0f, false);
                            }
                        }
                    }
                    else
                    {
                        //Switching, courtine less
                        #region Switching
                        //Check for time
                        if (Time.time >= runtimeData.switchNextEnd)
                        {
                            //Time is over, check which phase is next
                            if (runtimeData.switchPhase == 0)
                            {
                                //Weapon has been put away, hide weapon
                                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.PutawayWeaponHide(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);

                                runtimeData.currentWeapon = runtimeData.desiredWeapon;

                                //Draw that weapon
                                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.DrawWeapon(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
                                //Set phase
                                runtimeData.switchPhase = 1;
                                //Set time
                                runtimeData.switchNextEnd = Time.time + runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.drawTime;
                                //Play Third person animation
                                pb.thirdPersonPlayerModel.PlayWeaponChangeAnimation(runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.thirdPersonAnimType, true, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.drawTime);
                                //Done, now wait
                            }
                            else if (runtimeData.switchPhase == 1)
                            {
                                //Switching is over
                                runtimeData.switchPhase = 0;
                                runtimeData.switchNextEnd = 0f;
                                runtimeData.switchInProgress = false;
                            }
                        }
                        #endregion
                    }
                }

                //Move weapons transform
                pb.weaponsGo.localPosition = Vector3.Lerp(pb.weaponsGo.localPosition, Vector3.zero + pb.looking.GetWeaponOffset(pb), Time.deltaTime * weaponPositionChangeSpeed);

                //Move weapons transform
                pb.weaponsGo.localRotation = Quaternion.Slerp(pb.weaponsGo.localRotation, pb.looking.GetWeaponRotationOffset(pb), Time.deltaTime * weaponPositionChangeSpeed);

                if (pb.isFirstPersonActive)
                {
                    Kit_IngameMain.instance.hud.DisplayWeaponsAndQuickUses(pb, runtimeData);
                }
            }

            public override void PlayerDead(Kit_PlayerBehaviour pb)
            {
                if (NetworkServer.active && (Kit_IngameMain.instance.currentPvPGameModeBehaviour && Kit_IngameMain.instance.currentPvPGameModeBehaviour.CanDropWeapons()) || (Kit_IngameMain.instance.currentPvEGameModeBehaviour && Kit_IngameMain.instance.currentPvEGameModeBehaviour.CanDropWeapons()))
                {
                    Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                    if (uponDeathDrop == DeadDrop.Selected)
                    {
                        DropWeaponDead(pb, runtimeData.currentWeapon);
                    }
                    else if (uponDeathDrop == DeadDrop.All)
                    {
                        for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                        {
                            if (!runtimeData.weaponsInUseDataObjects[i].isInjectedFromPlugin)
                            {
                                DropWeaponDead(pb, i);
                            }
                        }
                    }

                }
            }

            public override void OnAnimatorIKCallback(Kit_PlayerBehaviour pb, Animator anim)
            {
                //Get runtime data
                if (pb.isLocalPlayer)
                {
                    Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                    if (anim)
                    {
                        //Get Weapon IK
                        WeaponIKValues ikv = null;

                        if (runtimeData.quickUseInProgress && runtimeData.quickUseState > 0 && runtimeData.quickUseState < 4)
                        {
                            ikv = runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse].behaviour.GetIK(pb, anim, runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse]);
                        }
                        else
                        {
                            ikv = runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.GetIK(pb, anim, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
                        }

                        if (ikv != null)
                        {
                            if (ikv.leftHandIK)
                            {
                                anim.SetIKPosition(AvatarIKGoal.LeftHand, ikv.leftHandIK.position);
                                anim.SetIKRotation(AvatarIKGoal.LeftHand, ikv.leftHandIK.rotation);
                            }
                            if (!runtimeData.switchInProgress && ikv.canUseIK && ikv.leftHandIK)
                            {
                                runtimeData.leftHandIKWeight = Mathf.Lerp(runtimeData.leftHandIKWeight, 1f, Time.deltaTime * 3);
                            }
                            else
                            {
                                runtimeData.leftHandIKWeight = Mathf.Lerp(runtimeData.leftHandIKWeight, 0f, Time.deltaTime * 20);
                            }
                            anim.SetIKPositionWeight(AvatarIKGoal.LeftHand, runtimeData.leftHandIKWeight);
                            anim.SetIKRotationWeight(AvatarIKGoal.LeftHand, runtimeData.leftHandIKWeight);
                        }
                        else
                        {
                            runtimeData.leftHandIKWeight = Mathf.Lerp(runtimeData.leftHandIKWeight, 0f, Time.deltaTime * 20);
                            anim.SetIKPositionWeight(AvatarIKGoal.LeftHand, runtimeData.leftHandIKWeight);
                            anim.SetIKRotationWeight(AvatarIKGoal.LeftHand, runtimeData.leftHandIKWeight);
                        }
                    }

                }
                else
                {
                    Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                    if (anim)
                    {
                        //Get Weapon IK
                        WeaponIKValues ikv = null;

                        if (runtimeData.quickUseInProgress && runtimeData.quickUseState > 0 && runtimeData.quickUseState < 4)
                        {
                            ikv = runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse].behaviour.GetIK(pb, anim, runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse]);
                        }
                        else
                        {
                            ikv = runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.GetIK(pb, anim, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
                        }

                        if (ikv != null)
                        {
                            if (ikv.leftHandIK)
                            {
                                anim.SetIKPosition(AvatarIKGoal.LeftHand, ikv.leftHandIK.position);
                                anim.SetIKRotation(AvatarIKGoal.LeftHand, ikv.leftHandIK.rotation);
                            }
                            if (!runtimeData.switchInProgress && ikv.canUseIK && ikv.leftHandIK)
                            {
                                runtimeData.leftHandIKWeight = Mathf.Lerp(runtimeData.leftHandIKWeight, 1f, Time.deltaTime * 3);
                            }
                            else
                            {
                                runtimeData.leftHandIKWeight = Mathf.Lerp(runtimeData.leftHandIKWeight, 0f, Time.deltaTime * 20);
                            }
                            anim.SetIKPositionWeight(AvatarIKGoal.LeftHand, runtimeData.leftHandIKWeight);
                            anim.SetIKRotationWeight(AvatarIKGoal.LeftHand, runtimeData.leftHandIKWeight);
                        }
                        else
                        {
                            runtimeData.leftHandIKWeight = Mathf.Lerp(runtimeData.leftHandIKWeight, 0f, Time.deltaTime * 20);
                            anim.SetIKPositionWeight(AvatarIKGoal.LeftHand, runtimeData.leftHandIKWeight);
                            anim.SetIKRotationWeight(AvatarIKGoal.LeftHand, runtimeData.leftHandIKWeight);
                        }
                    }

                }
            }

            public override void FallDownEffect(Kit_PlayerBehaviour pb, bool wasFallDamageApplied)
            {
                if (pb.isBot) return;
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.FallDownEffect(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon], wasFallDamageApplied);

            }

            public override void OnControllerColliderHitRelay(Kit_PlayerBehaviour pb, ControllerColliderHit hit)
            {
                if (!pb.weaponManagerNetworkData) return;
                //Get runtime data
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.OnControllerColliderHitCallback(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon], hit);
            }

            public override void NetworkSemiRPCReceived(Kit_PlayerBehaviour pb)
            {
                if (!pb.weaponManagerNetworkData) return;
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                //Relay to weapon script
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.NetworkSemiRPCReceived(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
            }

            public override void NetworkBoltActionRPCReceived(Kit_PlayerBehaviour pb, int state)
            {
                if (!pb.weaponManagerNetworkData) return;
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                //Relay to weapon script
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.NetworkBoltActionRPCReceived(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon], state);
            }

            public override void NetworkBurstRPCReceived(Kit_PlayerBehaviour pb, int burstLength)
            {
                if (!pb.weaponManagerNetworkData) return;
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                //Relay to weapon script
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.NetworkBurstRPCReceived(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon], burstLength);
            }

            public override void NetworkReloadRPCReceived(Kit_PlayerBehaviour pb, bool isEmpty)
            {
                if (!pb.weaponManagerNetworkData) return;
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                //Relay to weapon script
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.NetworkReloadRPCReceived(pb, isEmpty, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);

            }

            public override void NetworkProceduralReloadRPCReceived(Kit_PlayerBehaviour pb, int stage)
            {
                if (!pb.weaponManagerNetworkData) return;
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                //Relay to weapon script
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.NetworkProceduralReloadRPCReceived(pb, stage, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);

            }

            public override void NetworkMeleeChargeRPCReceived(Kit_PlayerBehaviour pb, int state, int slot)
            {
                if (!pb.weaponManagerNetworkData) return;
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                //Relay to weapon script
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.NetworkMeleeChargeRPCReceived(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon], state, slot);

            }

            public override void NetworkMeleeHealRPCReceived(Kit_PlayerBehaviour pb, int slot)
            {
                if (!pb.weaponManagerNetworkData) return;
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                //Relay to weapon script
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.NetworkMeleeHealRPCReceived(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon], slot);
            }

            public override void NetworkMeleeStabRPCReceived(Kit_PlayerBehaviour pb, int state, int slot)
            {
                if (!pb.weaponManagerNetworkData) return;
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                //Relay to weapon script
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.NetworkMeleeStabRPCReceived(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon], state, slot);
            }

            public override void NetworkGrenadePullPinRPCReceived(Kit_PlayerBehaviour pb)
            {
                if (!pb.weaponManagerNetworkData) return;
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                //Relay to weapon script
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.NetworkGrenadePullPinRPCReceived(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
            }

            public override void NetworkGrenadeThrowRPCReceived(Kit_PlayerBehaviour pb)
            {
                if (!pb.weaponManagerNetworkData) return;
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects.Length <= runtimeData.currentWeapon) return;
                //Relay to weapon script
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.NetworkGrenadeThrowRPCReceived(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
            }

            public override float GetAimingPercentage(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.GetAimingPercentage(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]); //Relay to weapon script
            }

            public override bool IsAiming(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.IsWeaponAiming(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]); //Relay to weapon script
            }

            public override float AimInTime(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.AimInTime(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]); //Relay to weapon script
            }

            public override bool ForceIntoFirstPerson(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.ForceIntoFirstPerson(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]); //Relay to weapon script
            }

            public override bool CanRun(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (allowSwitchingWhileRunning) return true;
                else return !runtimeData.switchInProgress;
            }

            public override float CurrentMovementMultiplier(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.SpeedMultiplier(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]); //Relay to weapon script
            }

            public override float CurrentSensitivity(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.Sensitivity(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]); //Relay to weapon script
            }

            public override int GetCurrentWeapon(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                //Just return ID
                return runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].id;
            }

            public override int HasWeapon(Kit_PlayerBehaviour pb, int id)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

                for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                {
                    if (runtimeData.weaponsInUseDataObjects[i].id == id)
                    {
                        return i;
                    }
                }

                return -1;
            }

            public override Kit_WeaponRuntimeDataBase GetRuntimeDataOfWeapon(Kit_PlayerBehaviour pb, int slot)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                //Just return ID
                return runtimeData.weaponsInUseDataObjects[slot];
            }

            public override bool CanBuyWeapon(Kit_PlayerBehaviour pb, int id)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

                for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                {
                    if (runtimeData.weaponsInUseDataObjects[i].id == id)
                    {
                        //Special case for grenades - let us buy more grenades if we are below that #
                        if (runtimeData.weaponsInUseDataObjects[i] != null && runtimeData.weaponsInUseDataObjects[i].GetType() == typeof(Kit_ModernGrenadeScriptRuntimeData))
                        {
                            Kit_ModernGrenadeScriptRuntimeData gcrd = runtimeData.weaponsInUseDataObjects[i] as Kit_ModernGrenadeScriptRuntimeData;
                            Kit_ModernGrenadeScript grenadeData = runtimeData.weaponsInUseDataObjects[i].behaviour as Kit_ModernGrenadeScript;

                            if (gcrd.amountOfGrenadesLeft < grenadeData.amountOfGrenadesAtStart)
                            {
                                return true;
                            }

                        }

                        return false;
                    }

                }

                //Can buy
                return true;
            }

            public override void NetworkReplaceWeapon(Kit_PlayerBehaviour pb, int slot, int weapon, int bulletsLeft, int bulletsLeftToReload, int[] attachments)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

                GameObject spawnObject = Kit_IngameMain.instance.gameInformation.allWeapons[weapon].SetupSpawnData(pb, slot, new LoadoutWeapon { weaponID = weapon, attachments = attachments });

                Kit_WeaponRuntimeDataBase wrdb = spawnObject.GetComponent<Kit_WeaponRuntimeDataBase>();

                if (wrdb is Kit_ModernWeaponScriptRuntimeData)
                {
                    Kit_ModernWeaponScriptRuntimeData mwsrd = wrdb as Kit_ModernWeaponScriptRuntimeData;
                    mwsrd.bulletsLeft = bulletsLeft;
                    mwsrd.bulletsLeftToReload = bulletsLeftToReload;
                }

                NetworkServer.Spawn(spawnObject, pb.gameObject);
                NetworkIdentity id = spawnObject.GetComponent<NetworkIdentity>();

                NetworkIdentity oldIdentity = NetworkServer.spawned[runtimeData.weaponsInUseSync[slot]];

                if (oldIdentity)
                {
                    NetworkServer.Destroy(oldIdentity.gameObject);
                }

                runtimeData.weaponsInUseSync[slot] = id.netId;
            }

            public override void NetworkPhysicalBulletFired(Kit_PlayerBehaviour pb, Vector3 pos, Vector3 dir)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                //Relay to weapon script
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.NetworkPhysicalBulletFired(pb, pos, dir, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
            }

            public void DropWeapon(Kit_PlayerBehaviour pb, int slot)
            {
                if ((Kit_IngameMain.instance.currentPvPGameModeBehaviour && Kit_IngameMain.instance.currentPvPGameModeBehaviour.CanDropWeapons()) || (Kit_IngameMain.instance.currentPvEGameModeBehaviour && Kit_IngameMain.instance.currentPvEGameModeBehaviour.CanDropWeapons()))
                {
                    if (pb.weaponManagerNetworkData != null && pb.weaponManagerNetworkData.GetType() == typeof(Kit_ModernWeaponManagerNetworkData))
                    {
                        //Get the manager's runtime data
                        Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                        if (runtimeData.weaponsInUseDataObjects[slot] != null && runtimeData.weaponsInUseDataObjects[slot].GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                        {
                            //Get the weapon's runtime data
                            Kit_ModernWeaponScriptRuntimeData wepData = runtimeData.weaponsInUseDataObjects[slot] as Kit_ModernWeaponScriptRuntimeData;
                            //Get the Scriptable object
                            Kit_ModernWeaponScript wepScript = runtimeData.weaponsInUseDataObjects[slot].behaviour as Kit_ModernWeaponScript;
                            //Instantiate
                            GameObject go = Instantiate(dropPrefab, pb.playerCameraTransform.position, pb.playerCameraTransform.rotation);
                            Kit_DropBehaviour dp = go.GetComponent<Kit_DropBehaviour>();
                            dp.isSceneOwned = true;
                            dp.weaponID = wepScript.gameGunID;
                            dp.bulletsLeft = wepData.bulletsLeft;
                            dp.bulletsLeftToReload = wepData.bulletsLeftToReload;

                            for (int i = 0; i < wepData.attachments.Count; i++)
                            {
                                dp.attachments.Add(wepData.attachments[i]);
                            }

                            NetworkServer.Spawn(go);
                        }
                        else if (runtimeData.weaponsInUseDataObjects[slot] != null && runtimeData.weaponsInUseDataObjects[slot].GetType() == typeof(Kit_ModernMeleeScriptRuntimeData))
                        {
                            //Get the weapon's runtime data
                            Kit_ModernMeleeScriptRuntimeData wepData = runtimeData.weaponsInUseDataObjects[slot] as Kit_ModernMeleeScriptRuntimeData;
                            //Get the Scriptable object
                            Kit_ModernMeleeScript wepScript = runtimeData.weaponsInUseDataObjects[slot].behaviour as Kit_ModernMeleeScript;
                            //Instantiate
                            GameObject go = Instantiate(dropPrefab, pb.playerCameraTransform.position, pb.playerCameraTransform.rotation);
                            Kit_DropBehaviour dp = go.GetComponent<Kit_DropBehaviour>();
                            dp.isSceneOwned = true;
                            dp.weaponID = wepScript.gameGunID;
                            dp.bulletsLeft = 0;
                            dp.bulletsLeftToReload = 0;

                            for (int i = 0; i < wepData.attachments.Count; i++)
                            {
                                dp.attachments.Add(wepData.attachments[i]);
                            }

                            NetworkServer.Spawn(go);
                        }
                        else if (runtimeData.weaponsInUseDataObjects[slot] != null && runtimeData.weaponsInUseDataObjects[slot].GetType() == typeof(Kit_ModernGrenadeScriptRuntimeData))
                        {
                            //Get the weapon's runtime data
                            Kit_ModernGrenadeScriptRuntimeData wepData = runtimeData.weaponsInUseDataObjects[slot] as Kit_ModernGrenadeScriptRuntimeData;
                            if (wepData.amountOfGrenadesLeft <= 0) return;
                            //Get the Scriptable object
                            Kit_ModernGrenadeScript wepScript = runtimeData.weaponsInUseDataObjects[slot].behaviour as Kit_ModernGrenadeScript;
                            //Instantiate
                            GameObject go = Instantiate(dropPrefab, pb.playerCameraTransform.position, pb.playerCameraTransform.rotation);
                            Kit_DropBehaviour dp = go.GetComponent<Kit_DropBehaviour>();
                            dp.isSceneOwned = true;
                            dp.weaponID = wepScript.gameGunID;
                            dp.bulletsLeft = 0;
                            dp.bulletsLeftToReload = 0;

                            for (int i = 0; i < wepData.attachments.Count; i++)
                            {
                                dp.attachments.Add(wepData.attachments[i]);
                            }

                            NetworkServer.Spawn(go);
                        }
                    }
                }
            }

            /// <summary>
            /// Drops a weapon and applies the ragdoll force!
            /// </summary>
            /// <param name="pb"></param>
            /// <param name="slot"></param>
            public void DropWeaponDead(Kit_PlayerBehaviour pb, int slot)
            {
                if ((Kit_IngameMain.instance.currentPvPGameModeBehaviour && Kit_IngameMain.instance.currentPvPGameModeBehaviour.CanDropWeapons()) || (Kit_IngameMain.instance.currentPvEGameModeBehaviour && Kit_IngameMain.instance.currentPvEGameModeBehaviour.CanDropWeapons()))
                {
                    if (pb.weaponManagerNetworkData != null && pb.weaponManagerNetworkData.GetType() == typeof(Kit_ModernWeaponManagerNetworkData))
                    {
                        //Get the manager's runtime data
                        Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                        if (runtimeData.weaponsInUseDataObjects[slot] != null && runtimeData.weaponsInUseDataObjects[slot].GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                        {
                            //Get the weapon's runtime data
                            Kit_ModernWeaponScriptRuntimeData wepData = runtimeData.weaponsInUseDataObjects[slot] as Kit_ModernWeaponScriptRuntimeData;
                            //Get the Scriptable object
                            Kit_ModernWeaponScript wepScript = runtimeData.weaponsInUseDataObjects[slot].behaviour as Kit_ModernWeaponScript;
                            //Instantiate
                            GameObject go = Instantiate(dropPrefab, pb.playerCameraTransform.position, pb.playerCameraTransform.rotation);
                            Kit_DropBehaviour dp = go.GetComponent<Kit_DropBehaviour>();
                            dp.isSceneOwned = true;
                            dp.weaponID = wepScript.gameGunID;
                            dp.bulletsLeft = wepData.bulletsLeft;
                            dp.bulletsLeftToReload = wepData.bulletsLeftToReload;

                            for (int i = 0; i < wepData.attachments.Count; i++)
                            {
                                dp.attachments.Add(wepData.attachments[i]);
                            }

                            NetworkServer.Spawn(go);
                            Rigidbody body = go.GetComponent<Rigidbody>();
                            if (body)
                            {
                                body.velocity = pb.movement.GetVelocity(pb);
                                body.AddForceNextFrame(pb.ragdollForward * pb.ragdollForce / 10);
                            }
                        }
                        else if (runtimeData.weaponsInUseDataObjects[slot] != null && runtimeData.weaponsInUseDataObjects[slot].GetType() == typeof(Kit_ModernMeleeScriptRuntimeData))
                        {
                            //Get the weapon's runtime data
                            Kit_ModernMeleeScriptRuntimeData wepData = runtimeData.weaponsInUseDataObjects[slot] as Kit_ModernMeleeScriptRuntimeData;
                            //Get the Scriptable object
                            Kit_ModernMeleeScript wepScript = runtimeData.weaponsInUseDataObjects[slot].behaviour as Kit_ModernMeleeScript;
                            //Instantiate
                            GameObject go = Instantiate(dropPrefab, pb.playerCameraTransform.position, pb.playerCameraTransform.rotation);
                            Kit_DropBehaviour dp = go.GetComponent<Kit_DropBehaviour>();
                            dp.isSceneOwned = true;
                            dp.weaponID = wepScript.gameGunID;
                            dp.bulletsLeft = 0;
                            dp.bulletsLeftToReload = 0;

                            for (int i = 0; i < wepData.attachments.Count; i++)
                            {
                                dp.attachments.Add(wepData.attachments[i]);
                            }

                            NetworkServer.Spawn(go);
                            Rigidbody body = go.GetComponent<Rigidbody>();
                            if (body)
                            {
                                body.velocity = pb.movement.GetVelocity(pb);
                                body.AddForceNextFrame(pb.ragdollForward * pb.ragdollForce / 10);
                            }
                        }
                        else if (runtimeData.weaponsInUseDataObjects[slot] != null && runtimeData.weaponsInUseDataObjects[slot].GetType() == typeof(Kit_ModernGrenadeScriptRuntimeData))
                        {
                            //Get the weapon's runtime data
                            Kit_ModernGrenadeScriptRuntimeData wepData = runtimeData.weaponsInUseDataObjects[slot] as Kit_ModernGrenadeScriptRuntimeData;
                            if (wepData.amountOfGrenadesLeft <= 0) return;
                            //Get the Scriptable object
                            Kit_ModernGrenadeScript wepScript = runtimeData.weaponsInUseDataObjects[slot].behaviour as Kit_ModernGrenadeScript;
                            //Instantiate
                            GameObject go = Instantiate(dropPrefab, pb.playerCameraTransform.position, pb.playerCameraTransform.rotation);
                            Kit_DropBehaviour dp = go.GetComponent<Kit_DropBehaviour>();
                            dp.isSceneOwned = true;
                            dp.weaponID = wepScript.gameGunID;
                            dp.bulletsLeft = 0;
                            dp.bulletsLeftToReload = 0;

                            for (int i = 0; i < wepData.attachments.Count; i++)
                            {
                                dp.attachments.Add(wepData.attachments[i]);
                            }

                            NetworkServer.Spawn(go);
                            Rigidbody body = go.GetComponent<Rigidbody>();
                            if (body)
                            {
                                body.velocity = pb.movement.GetVelocity(pb);
                                body.AddForceNextFrame(pb.ragdollForward * pb.ragdollForce / 10);
                            }
                        }
                    }
                }
            }

            public void DropWeapon(Kit_PlayerBehaviour pb, int slot, Transform replace)
            {
                if (pb.weaponManagerNetworkData != null && pb.weaponManagerNetworkData.GetType() == typeof(Kit_ModernWeaponManagerNetworkData))
                {
                    //Get the manager's runtime data
                    Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                    if (runtimeData.weaponsInUseDataObjects[slot] != null && runtimeData.weaponsInUseDataObjects[slot].GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                    {
                        //Get the weapon's runtime data
                        Kit_ModernWeaponScriptRuntimeData wepData = runtimeData.weaponsInUseDataObjects[slot] as Kit_ModernWeaponScriptRuntimeData;
                        //Get the Scriptable object
                        Kit_ModernWeaponScript wepScript = runtimeData.weaponsInUseDataObjects[slot].behaviour as Kit_ModernWeaponScript;
                        //Instantiate
                        GameObject go = Instantiate(dropPrefab, replace.position, replace.rotation);
                        Kit_DropBehaviour dp = go.GetComponent<Kit_DropBehaviour>();
                        dp.isSceneOwned = true;
                        dp.weaponID = wepScript.gameGunID;
                        dp.bulletsLeft = wepData.bulletsLeft;
                        dp.bulletsLeftToReload = wepData.bulletsLeftToReload;

                        for (int i = 0; i < wepData.attachments.Count; i++)
                        {
                            dp.attachments.Add(wepData.attachments[i]);
                        }

                        NetworkServer.Spawn(go);
                    }
                    else if (runtimeData.weaponsInUseDataObjects[slot] != null && runtimeData.weaponsInUseDataObjects[slot].GetType() == typeof(Kit_ModernMeleeScriptRuntimeData))
                    {
                        //Get the weapon's runtime data
                        Kit_ModernMeleeScriptRuntimeData wepData = runtimeData.weaponsInUseDataObjects[slot] as Kit_ModernMeleeScriptRuntimeData;
                        //Get the Scriptable object
                        Kit_ModernMeleeScript wepScript = runtimeData.weaponsInUseDataObjects[slot].behaviour as Kit_ModernMeleeScript;
                        //Instantiate
                        GameObject go = Instantiate(dropPrefab, replace.position, replace.rotation);
                        Kit_DropBehaviour dp = go.GetComponent<Kit_DropBehaviour>();
                        dp.isSceneOwned = true;
                        dp.weaponID = wepScript.gameGunID;
                        dp.bulletsLeft = 0;
                        dp.bulletsLeftToReload = 0;

                        for (int i = 0; i < wepData.attachments.Count; i++)
                        {
                            dp.attachments.Add(wepData.attachments[i]);
                        }

                        NetworkServer.Spawn(go);
                    }
                    else if (runtimeData.weaponsInUseDataObjects[slot] != null && runtimeData.weaponsInUseDataObjects[slot].GetType() == typeof(Kit_ModernGrenadeScriptRuntimeData))
                    {
                        //Get the weapon's runtime data
                        Kit_ModernGrenadeScriptRuntimeData wepData = runtimeData.weaponsInUseDataObjects[slot] as Kit_ModernGrenadeScriptRuntimeData;
                        if (wepData.amountOfGrenadesLeft <= 0) return;
                        //Get the Scriptable object
                        Kit_ModernGrenadeScript wepScript = runtimeData.weaponsInUseDataObjects[slot].behaviour as Kit_ModernGrenadeScript;
                        //Instantiate
                        GameObject go = Instantiate(dropPrefab, replace.position, replace.rotation);
                        Kit_DropBehaviour dp = go.GetComponent<Kit_DropBehaviour>();
                        dp.isSceneOwned = true;
                        dp.weaponID = wepScript.gameGunID;
                        dp.bulletsLeft = 0;
                        dp.bulletsLeftToReload = 0;

                        for (int i = 0; i < wepData.attachments.Count; i++)
                        {
                            dp.attachments.Add(wepData.attachments[i]);
                        }

                        NetworkServer.Spawn(go);
                    }
                }
            }

            public override int WeaponState(Kit_PlayerBehaviour pb)
            {
                //Get the manager's runtime data
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.WeaponState(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
            }

            public override int WeaponType(Kit_PlayerBehaviour pb)
            {
                //Get the manager's runtime data
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.GetWeaponType(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
            }

            public override void FirstThirdPersonChanged(Kit_PlayerBehaviour pb, Kit_GameInformation.Perspective perspective)
            {
                if (pb.syncSetup)
                {
                    //Forward to currently selected weapon
                    Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                    if (runtimeData.quickUseInProgress && runtimeData.quickUseState > 0 && runtimeData.quickUseState < 4)
                    {
                        runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse].behaviour.FirstThirdPersonChanged(pb, perspective, runtimeData.weaponsInUseDataObjects[runtimeData.desiredQuickUse]);
                    }
                    else
                    {
                        runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.FirstThirdPersonChanged(pb, perspective, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
                    }
                }
            }

            public override void OnAmmoPickup(Kit_PlayerBehaviour pb, Kit_AmmoPickup pickup)
            {
                //Forward to currently selected weapon
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.OnAmmoPickup(pb, pickup, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
            }

            public override void RestockAmmo(Kit_PlayerBehaviour pb, bool allWeapons)
            {
                if (pb.isServer)
                {
                    if (pb.weaponManagerNetworkData != null && pb.weaponManagerNetworkData.GetType() == typeof(Kit_ModernWeaponManagerNetworkData))
                    {
                        if (allWeapons)
                        {
                            Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                            for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                            {
                                runtimeData.weaponsInUseDataObjects[i].behaviour.RestockAmmo(pb, runtimeData.weaponsInUseDataObjects[i]);
                            }
                        }
                        else
                        {
                            //Forward to currently selected weapon
                            Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                            runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.RestockAmmo(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
                        }
                    }
                }
            }

            public override bool IsCurrentWeaponFull(Kit_PlayerBehaviour pb)
            {
                //Forward to currently selected weapon
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon].behaviour.IsWeaponFull(pb, runtimeData.weaponsInUseDataObjects[runtimeData.currentWeapon]);
            }

            public override void PluginSelectWeapon(Kit_PlayerBehaviour pb, int slot, bool locked = true)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                //Just set, thats all!
                runtimeData.desiredWeapon = slot;
                runtimeData.isDesiredWeaponLocked = locked;
            }

            public override int GetCurrentlyDesiredWeapon(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.desiredWeapon;
            }

            public override int GetCurrentlyDesiredQuickUse(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.desiredQuickUse;
            }

            public override int GetCurrentlySelectedWeapon(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                return runtimeData.currentWeapon;
            }

            public override void SetDesiredWeapon(Kit_PlayerBehaviour pb, int desiredWeapon)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;
                if (runtimeData.weaponsInUseDataObjects[desiredWeapon].behaviour.CanBeSelected(pb, runtimeData.weaponsInUseDataObjects[desiredWeapon]))
                {
                    runtimeData.desiredWeapon = desiredWeapon;

                }
            }

            public override int[] GetSlotsWithEmptyWeapon(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

                List<int> emptySlots = new List<int>();

                for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                {
                    //Check if that slot contains a placehodler weapon
                    if (runtimeData.weaponsInUseDataObjects[i].behaviour.GetType() == typeof(Kit_WeaponUnselectable))
                    {
                        int id = i;
                        //Add it to list of empty slots
                        emptySlots.Add(id);
                    }
                }

                return emptySlots.ToArray();
            }

            public override void BeginSpectating(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

                for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                {
                    //Relay
                    runtimeData.weaponsInUseDataObjects[i].behaviour.BeginSpectating(pb, runtimeData.weaponsInUseDataObjects[i], runtimeData.weaponsInUseDataObjects[i].attachments.ToArray());
                }
            }

            public override void EndSpectating(Kit_PlayerBehaviour pb)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

                for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                {
                    //Relay
                    runtimeData.weaponsInUseDataObjects[i].behaviour.EndSpectating(pb, runtimeData.weaponsInUseDataObjects[i]);
                }
            }

            public override void OnTriggerEnterRelay(Kit_PlayerBehaviour pb, Collider col)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

                for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                {
                    //Relay
                    runtimeData.weaponsInUseDataObjects[i].behaviour.OnTriggerEnterRelay(pb, runtimeData.weaponsInUseDataObjects[i], col);
                }
            }

            public override void OnTriggerExitRelay(Kit_PlayerBehaviour pb, Collider col)
            {
                Kit_ModernWeaponManagerNetworkData runtimeData = pb.weaponManagerNetworkData as Kit_ModernWeaponManagerNetworkData;

                for (int i = 0; i < runtimeData.weaponsInUseDataObjects.Length; i++)
                {
                    //Relay
                    runtimeData.weaponsInUseDataObjects[i].behaviour.OnTriggerExitRelay(pb, runtimeData.weaponsInUseDataObjects[i], col);
                }
            }
        }
    }
}
using Mirror;
using System;
using System.Collections.Generic;
using UnityEngine;

namespace MarsFPSKit
{
    namespace Weapons
    {
        public class Kit_ModernWeaponManagerNetworkData : Kit_WeaponManagerNetworkBase
        {
            /// <summary>
            /// Our currently selected weapon; [0] = slot; [1] = weapon In Slot
            /// </summary>
            public int currentWeapon;
            [SyncVar]
            /// <summary>
            /// The weapon we want to select
            /// </summary>
            public int desiredWeapon;
            [System.NonSerialized]
            /// <summary>
            /// Desired weapon is locked (by plugin?)
            /// </summary>
            public bool isDesiredWeaponLocked;
            [SyncVar]
            /// <summary>
            /// Is a quick use in progress?
            /// </summary>
            public bool quickUseInProgress;
            [SyncVar]
            /// <summary>
            /// Quick use that we want to do!
            /// </summary>
            public int desiredQuickUse;
            [System.NonSerialized]
            /// <summary>
            /// Current state of quick use.
            /// </summary>
            public int quickUseState;
            [System.NonSerialized]
            /// <summary>
            /// When is the next quick use state over?
            /// </summary>
            public float quickUseOverAt;
            [SyncVar]
            /// <summary>
            /// Sync!
            /// </summary>
            public bool quickUseSyncButtonWaitOver;
            /// <summary>
            /// These are the network ids of our weapon's prefabs that co-exist with out player
            /// </summary>
            public readonly SyncList<uint> weaponsInUseSync = new SyncList<uint>();
            /// <summary>
            /// Stores the objects of our list
            /// </summary>
            public Kit_WeaponRuntimeDataBase[] weaponsInUseDataObjects = new Kit_WeaponRuntimeDataBase[0];
            [System.NonSerialized]
            /// <summary>
            /// Last states for the slot buttons!
            /// </summary>
            public bool[] lastInputIDs;
            [System.NonSerialized]
            /// <summary>
            /// Last state for the drop weapon
            /// </summary>
            public bool lastInteract;
            [System.NonSerialized]
            /// <summary>
            /// Are we currently switching weapons?
            /// </summary>
            public bool switchInProgress;
            [System.NonSerialized]
            /// <summary>
            /// When is the next switching phase over?
            /// </summary>
            public float switchNextEnd; //This is only so we don't have to use a coroutine
            [System.NonSerialized]
            /// <summary>
            /// The current phase of switching
            /// </summary>
            public int switchPhase;
            [System.NonSerialized]
            /// <summary>
            /// Raycast hit for the pickup process
            /// </summary>
            public RaycastHit hit;
            [System.NonSerialized]
            /// <summary>
            /// To fire the interaction end trigger
            /// We store the object we are currently interacting with
            /// </summary>
            public Kit_InteractableObject holdingInteractableObject;

            private void Start()
            {
                weaponsInUseSync.OnChange += OnWeaponsInUseSyncCallback;
            }

            private void OnWeaponsInUseSyncCallback(SyncList<uint>.Operation operation, int index, uint item)
            {
                //Make sure its assigned
                //Shouldn't happen..
                //But just in case, it should fix itself.
                if (!ownerPlayer)
                {
                    if (NetworkServer.active)
                    {
                        if (NetworkServer.spawned.ContainsKey(ownerPlayerNetworkId))
                        {
                            Kit_PlayerBehaviour pb = NetworkServer.spawned[ownerPlayerNetworkId].GetComponent<Kit_PlayerBehaviour>();
                            pb.weaponManagerNetworkData = this;
                            ownerPlayer = pb;
                        }
                    }
                    else
                    {
                        if (NetworkClient.spawned.ContainsKey(ownerPlayerNetworkId))
                        {
                            Kit_PlayerBehaviour pb = NetworkClient.spawned[ownerPlayerNetworkId].GetComponent<Kit_PlayerBehaviour>();
                            pb.weaponManagerNetworkData = this;
                            ownerPlayer = pb;
                        }
                    }
                }

                if (ownerPlayer)
                {
                    ownerPlayer.weaponManager.OnWeaponsInUseSyncCallback(ownerPlayer, operation, index, item);
                }
            }

            public Kit_WeaponRuntimeDataBase GetWeapon(int index)
            {
                if (weaponsInUseDataObjects.Length == 0)
                {
                    //Rebuild list
                    for (int i = 0; i < weaponsInUseSync.Count; i++)
                    {
                        NetworkIdentity id = NetworkClient.spawned[weaponsInUseSync[i]];

                        if (id)
                        {
                            weaponsInUseDataObjects[i] = id.GetComponent<Kit_WeaponRuntimeDataBase>();
                        }
                        else
                        {
                            //Didn't find it. This shouldn't happen!
                            weaponsInUseDataObjects[i] = null;
                        }
                    }
                }

                return weaponsInUseDataObjects[index];
            }

            private void OnDestroy()
            {
                if (NetworkServer.active)
                {
                    for (int i = 0; i < weaponsInUseDataObjects.Length; i++)
                    {
                        if (weaponsInUseDataObjects[i])
                        {
                            NetworkServer.Destroy(weaponsInUseDataObjects[i].gameObject);
                        }
                    }
                }
            }

            #region IK
            [System.NonSerialized]
            /// <summary>
            /// Weight of the left hand IK
            /// </summary>
            public float leftHandIKWeight;
            #endregion
        }
    }
}

using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Serialization;

namespace MarsFPSKit
{
    namespace Weapons
    {
        #region enums
        public enum FireMode { Semi, Auto, Burst, BoltAction };
        public enum FireTypeMode { Simple, Pellets }
        public enum BulletMode { Raycast, Physical }
        public enum ReloadMode { Simple, FullEmpty, Chambered, Procedural, ProceduralChambered }
        public enum SpreadMode { Simple, SprayPattern }
        #endregion

        [CreateAssetMenu(menuName = ("MarsFPSKit/Weapons/Modern Weapon Script"))]
        public class Kit_ModernWeaponScript : Kit_WeaponBase
        {
            [Header("Switching")]
            [Tooltip("Time in seconds to draw (equip) the weapon")]
            public float drawTime = 0.5f;

            [Tooltip("Time in seconds to put away (holster) the weapon")]
            public float putawayTime = 0.5f;

            [Header("Spring")]
            /// <summary>
            /// Config for positional spring
            /// </summary>
            public Kit_Spring.SpringConfig springPosConfig;
            /// <summary>
            /// Config for rotational spring
            /// </summary>
            public Kit_Spring.SpringConfig springRotConfig;

            #region Settings
            [Header("Settings")]
            public FireMode fireMode = FireMode.Semi;
            /// <summary>
            /// How many rounds per minute does this weapon shoot?
            /// </summary>
            public int RPM = 600;
            private float fireRate = 0.1f;
            /// <summary>
            /// How many bullets do we have per mag
            /// </summary>
            public int bulletsPerMag = 30;
            /// <summary>
            /// With how many <see cref="WeaponControllerRuntimeData.bulletsLeftToReload"/> do we start?
            /// </summary>
            public int bulletsToReloadAtStart = 60;
            /// <summary>
            /// How much damage does this weapon deal?
            /// </summary>
            public float baseDamage = 30f;
            /// <summary>
            /// The max. range of this weapon
            /// </summary>
            public float range = 500f;
            /// <summary>
            /// This is the damage drop off relative to <see cref="range"/>. It should be a value between 0 and 1 that multiplies with <see cref="baseDamage"/>
            /// </summary>
            public AnimationCurve damageDropoff = AnimationCurve.Linear(0, 1, 500f, 0.8f);
            /// <summary>
            /// Should we shoot one bullet at a time or pellets?
            /// </summary>
            public FireTypeMode fireTypeMode = FireTypeMode.Simple;
            /// <summary>
            /// If we are firing using burst, how many bullets should be fired in one burst?
            /// </summary>
            public int burstBulletsPerShot = 3;
            /// <summary>
            /// How many seconds need to pass between individual shots in burst fire mode?
            /// </summary>
            public float burstTimeBetweenShots = 0.1f;
            /// <summary>
            /// If we should shoot pellets, how many should we shoot?
            /// </summary>
            public int amountOfPellets = 12;
            /// <summary>
            /// How much should the weapon slow us down (base)?  Other values are multiplier by this.
            /// </summary>
            public float speedMultiplierBase = 1f;
            /// <summary>
            /// How much force is applied to the ragdoll?
            /// </summary>
            public float ragdollForce = 500f;
            #endregion

            #region Attachments
            [FormerlySerializedAs("attachmentSlots")]
            /// <summary>
            /// Attachment slots available on this weapon
            /// </summary>
            public AttachmentSlot[] attachmentSlotsSpecific;

            /// <summary>
            /// If assigned, this list is used instead
            /// </summary>
            public Kit_AttachmentsUniversal attachmentSlotOverride;

            public AttachmentSlot[] attachmentSlots
            {
                get
                {
                    if (attachmentSlotOverride) return attachmentSlotOverride.attachmentSlots;
                    else return attachmentSlotsSpecific;
                }
            }
            #endregion

            #region Animation Settings
            /// <summary>
            /// Should the "empty" bool be set to the animator?
            /// </summary>
            public bool setEmptyBool;
            /// <summary>
            /// Should the "aiming" bool be set to the animator?
            /// </summary>
            public bool setAimingBool;
            /// <summary>
            /// Should the "aiming" bool be set to the animator?
            /// </summary>
            public bool setRunningBool;
            /// <summary>
            /// Should the "aiming" bool be set to the animator?
            /// </summary>
            public bool sendRunningEvents;
            /// <summary>
            /// Set "aiming" float to the animator?
            /// </summary>
            public bool setAimingProgress;
            /// <summary>
            /// Set actual movement direction to the animator? ("hor" / "ver")
            /// </summary>
            public bool setMovementDirection;
            #endregion

            #region Crosshair
            [Header("Crosshair")]
            /// <summary>
            /// Is the crosshair enabled for this weapon?
            /// </summary>
            public bool crosshairEnabled = true;
            /// <summary>
            /// By which factor should we multiply the crosshair's size?
            /// </summary>
            public float crosshairSizeMultiplier = 1f;
            #endregion

            #region Bullets
            [Header("Bullets")]
            /// <summary>
            /// Determines whether we should use raycast or physical bullets
            /// </summary>
            public BulletMode bulletsMode = BulletMode.Raycast;
            /// <summary>
            /// Is bullet penetration enabled?
            /// </summary>
            public bool bulletsPenetrationEnabled = true;
            /// <summary>
            /// This is a value that determines how many objects can be penetrated with this bullet. Think of it as the money you have available to pay the penetration cost here <see cref="Kit_PenetrateableObject.cost"/>
            /// </summary>
            public int bulletsPenetrationForce = 3;
            /// <summary>
            /// If <see cref="bulletsMode"/> is set to <see cref="BulletMode.Physical"/>, this prefab will be instantiated instead of raycast
            /// </summary>
            public GameObject bulletPrefab;
            /// <summary>
            /// Speed of physical bullet in m/s
            /// </summary>
            public float bulletSpeed = 200;
            /// <summary>
            /// How many frames after shooting should the bullet be hidden?
            /// </summary>
            public int bulletHideForFrames = 3;
            /// <summary>
            /// Multiplier of gravity applied to bullet (1 = realistic). Multiplies with <see cref="Physics.gravity"/>
            /// </summary>
            public float bulletGravityMultiplier = 1f;
            /// <summary>
            /// How long will this weapon's bullets exist?
            /// </summary>
            public float bulletLifeTime = 10f;
            /// <summary>
            /// Should the bullet parent itself to its hit thing and stay alive? Useful for things like nails and arrows.
            /// </summary>
            public bool bulletStaysAliveAfterDeath = false;
            /// <summary>
            /// If bullet stays alive after death, this is how long
            /// </summary>
            public float bulletStaysAliveAfterDeathTime = 10f;
            #endregion

            #region Bullet Spread
            [Header("Bullet Spread")]
            /// <summary>
            /// Which spray m ode does this weapon use?
            /// </summary>
            public SpreadMode bulletSpreadMode = SpreadMode.Simple;
            /// <summary>
            /// Base value for hip bullet spread
            /// </summary>
            public float bulletSpreadHipBase = 0.1f;
            /// <summary>
            /// How much spread should be added for our current velocity in reference to <see cref="bulletSpreadHipVelocityReference"/>
            /// </summary>
            public float bulletSpreadHipVelocityAdd = 0.1f;
            /// <summary>
            /// Reference velocity for hip spread
            /// </summary>
            public float bulletSpreadHipVelocityReference = 6f;

            /// <summary>
            /// Base value for aiming bullet spread
            /// </summary>
            public float bulletSpreadAimBase = 0.01f;
            /// <summary>
            /// How much spread should be added for our current velocity in reference to <see cref="bulletSpreadAimVelocityReference"/>
            /// </summary>
            public float bulletSpreadAimVelocityAdd = 0.02f;
            /// <summary>
            /// Reference velocity for aim spread
            /// </summary>
            public float bulletSpreadAimVelocityReference = 6f;

            //SPRAY PATTERN
            /// <summary>
            /// Offset values for the spray pattern mode
            /// </summary>
            public Vector3[] bulletSpreadSprayPattern = new Vector3[30];
            /// <summary>
            /// How fast does the spray pattern recover?
            /// </summary>
            public float bulletSpreadSprayPatternRecoverySpeed = 1f;
            //END
            #endregion

            #region Recoil
            [Header("Recoil")]
            /// <summary>
            /// Minimum amount of recoil per shot
            /// </summary>
            public Vector2 recoilPerShotMin = new Vector2 { x = -0.1f, y = 0.5f };
            /// <summary>
            /// Max amount of recoil per shot
            /// </summary>
            public Vector2 recoilPerShotMax = new Vector2 { x = 0.1f, y = 1f };
            /// <summary>
            /// How fast is our recoil going to be applied
            /// </summary>
            public float recoilApplyTime = 0.1f;
            /// <summary>
            /// How fast are we going to return to our normal position?
            /// </summary>
            public float recoilReturnSpeed = 6f;
            #endregion

            #region Reload
            [Header("Reload")]
            public ReloadMode reloadMode = ReloadMode.Chambered;
            public bool reloadProceduralAddBulletDuringStartEmpty;
            /// <summary>
            /// Reload time for normal reload (simple / full)
            /// </summary>
            public float reloadTimeOne, reloadTimeTwo; //Reload is split up in two parts, first is till bullets are updated, second is till you can shoot again
            /// <summary>
            /// Reload time for empty reload, if <see cref="reloadMode"/> is set to <see cref="ReloadMode.FullEmpty"/> or <see cref="ReloadMode.Chambered"/>
            /// </summary>
            public float reloadEmptyTimeOne, reloadEmptyTimeTwo;
            /// <summary>
            /// How much time does it take to start the procedural reload when the gun is still loaded?
            /// </summary>
            public float reloadProceduralStartTime;
            /// <summary>
            /// How much time does it take to start the reload when the gun is empty (and no bullet is added as set in <see cref="reloadProceduralAddBulletDuringStartEmpty"/>
            /// </summary>
            public float reloadProceduralEmptyStartTime;
            /// <summary>
            /// How much time until the bullet gets added (empty reload start + adding bullet during animation)
            /// </summary>
            public float reloadProceduralEmptyInsertStartTimeOne;
            /// <summary>
            /// How much time left until the loop can start?
            /// </summary>
            public float reloadProceduralEmptyInsertStartTimeTwo;
            /// <summary>
            /// How much time before the bullet gets added?
            /// </summary>
            public float reloadProceduralInsertTimeOne;
            /// <summary>
            /// How much time needs to pass after the bullet was added
            /// </summary>
            public float reloadProceduralInsertTimeTwo;
            /// <summary>
            /// How long does it take to end the procedural reload?
            /// </summary>
            public float reloadProceduralEndTime;

            /// <summary>
            /// Reloading full sound
            /// </summary>
            public AudioClip reloadSound;
            /// <summary>
            /// Reloading empty sound
            /// </summary>
            public AudioClip reloadSoundEmpty;
            /// <summary>
            /// Max sound distance for third person reload
            /// </summary>
            public float reloadSoundThirdPersonMaxRange = 20;
            /// <summary>
            /// Sound rolloff for third person reload
            /// </summary>
            public AnimationCurve reloadSoundThirdPersonRolloff = AnimationCurve.EaseInOut(0f, 1f, 20f, 0f);
            /// <summary>
            /// Sound that plays when the procedural reload starts while there is still ammo left in the gun
            /// </summary>
            public AudioClip reloadProceduralStartSound;
            /// <summary>
            /// Sound that plays when the procedural reload starts while the gun is completely empty
            /// </summary>
            public AudioClip reloadProceduralStartEmptySound;
            /// <summary>
            /// Sound that plays when a bullet is inserted during the procedural reload
            /// </summary>
            public AudioClip reloadProceduralInsertSound;
            /// <summary>
            /// Sound that plays when the procedural reload ends
            /// </summary>
            public AudioClip reloadProceduralEndSound;
            #endregion

            #region Aiming
            /// <summary>
            /// Can we aim?
            /// </summary>
            [Header("Aiming")]
            public bool aimEnabled = true;
            /// <summary>
            /// How fast (in seconds) should we go from idle position to aiming?
            /// </summary>
            public float aimInTime = 0.5f;
            /// <summary>
            /// How fast (in seconds) should we return from aiming back to idle position?
            /// </summary>
            public float aimOutTime = 0.5f;
            /// <summary>
            /// How much should aiming slow us down?
            /// </summary>
            public float aimSpeedMultiplier = 0.8f;
            #endregion

            #region Weapon Delay
            [Header("Weapon Delay")]
            /// <summary>
            /// Base amount for weapon delay
            /// </summary>
            public float weaponDelayBaseAmount = 1f;
            /// <summary>
            /// Max amount for weapon delay
            /// </summary>
            public float weaponDelayMaxAmount = 0.02f;
            /// <summary>
            /// Multiplier that is applied when we are aiming
            /// </summary>
            public float weaponDelayAimingMultiplier = 0.3f;
            /// <summary>
            /// How fast does the weapon delay update?
            /// </summary>
            public float weaponDelaySmooth = 3f;
            #endregion

            #region Weapon Tilt
            /// <summary>
            /// Should the weapon tilt sideways when we are walking sideways?
            /// </summary>
            public bool weaponTiltEnabled = true;
            /// <summary>
            /// Should the weapon also tilt when we are aiming?
            /// </summary>
            public bool weaponTiltEnabledWhileAiming;
            /// <summary>
            /// By how many degrees should the weapon tilt?
            /// </summary>
            public float weaponTiltIntensity = 5f;
            /// <summary>
            /// How fast should it return to 0,0,0 when weapon tilt is disabled?
            /// </summary>
            public float weaponTiltReturnSpeed = 3f;
            #endregion

            #region Weapon Fall
            [Header("Fall Down effect")]
            public float fallDownAmount = 10.0f;
            public float fallDownMinOffset = -6.0f;
            public float fallDownMaxoffset = 6.0f;
            public float fallDownTime = 0.1f;
            public float fallDownReturnSpeed = 1f;
            #endregion

            #region Shell Ejection
            [Header("Shell Ejection")]
            /// <summary>
            /// Our shell ejection prefab
            /// </summary>
            public GameObject shellEjectionPrefab;
            /// <summary>
            /// Should there be a delay between the shot and the shell ejection? Must be lower than <see cref="fireRate"/>.
            /// </summary>
            public float shellEjectionTime = 0f;
            /// <summary>
            /// The minimum force applied (relative to the ejection point)
            /// </summary>
            public Vector3 shellEjectionMinForce;
            /// <summary>
            /// The maximum force applied (relative to the ejection point)
            /// </summary>
            public Vector3 shellEjectionMaxForce;
            /// <summary>
            /// The minimum torque applied (relative to the ejection point)
            /// </summary>
            public Vector3 shellEjectionMinTorque;
            /// <summary>
            /// The maximum torque applied (relative to the ejection point)
            /// </summary>
            public Vector3 shellEjectionMaxTorque;
            #endregion

            #region Running
            [Header("Running")]
            /// <summary>
            /// Time in seconds that you cannot fire after you stopped running
            /// </summary>
            public float timeCannotFireAfterRun = 0.3f;
            #endregion

            #region Sounds
            [Header("Sounds")]
            /// <summary>
            /// Sound used for draw
            /// </summary>
            public AudioClip drawSound;
            /// <summary>
            /// Sound used for putaway
            /// </summary>
            public AudioClip putawaySound;
            /// <summary>
            /// Fire sound used for first person
            /// </summary>
            public AudioClip fireSound;
            /// <summary>
            /// Fire sound used for third person
            /// </summary>
            public AudioClip fireSoundThirdPerson;
            /// <summary>
            /// Delay for <see cref="boltActionSoundNormal"/> if this is a normal shot
            /// </summary>
            public float boltActionDelayNormal;
            /// <summary>
            /// Sound that plays for <see cref="FireMode.BoltAction"/> if this is a normal shot
            /// </summary>
            public AudioClip boltActionSoundNormal;
            /// <summary>
            /// Total time of bolt action if it is a normal shot
            /// </summary>
            public float boltActionTimeNormal = 0.3f;
            /// <summary>
            /// Delay for <see cref="boltActionSoundLast"/> if this is a normal shot
            /// </summary>
            public float boltActionDelayLast;
            /// <summary>
            /// Sound that plays for <see cref="FireMode.BoltAction"/> if this is the last shot
            /// </summary>
            public AudioClip boltActionSoundLast;
            /// <summary>
            /// Total time of bolt action if it is the last shot
            /// </summary>
            public float boltActionTimeLast = 0.3f;
            /// <summary>
            /// Max sound distance for third person bolt sound
            /// </summary>
            public float boltActionSoundThirdPersonMaxRange = 20f;
            /// <summary>
            /// Sound rolloff for third person bolt sound
            /// </summary>
            public AnimationCurve boltActionSoundThirdPersonRolloff = AnimationCurve.EaseInOut(0f, 1f, 20f, 0f);
            /// <summary>
            /// Max sound distance for third person fire
            /// </summary>
            public float fireSoundThirdPersonMaxRange = 300f;
            /// <summary>
            /// Sound rolloff for third person fire
            /// </summary>
            public AnimationCurve fireSoundThirdPersonRolloff = AnimationCurve.EaseInOut(0f, 1f, 300f, 0f);

            /// <summary>
            /// Dry fire sound (Shooting with 0 bullets left)
            /// </summary>
            public AudioClip dryFireSound;
            #endregion

            #region Walk Animations
            /// <summary>
            /// Should the walk animation still play while we are aiming?
            /// </summary>
            [Header("Walking")]
            public bool enableWalkAnimationWhileAiming;
            #endregion

            #region Generic Animations
            [Header("Generic Animations")]
            /// <summary>
            /// This animation controller holds the animations for generic gun movement (Idle, Walk, Run)
            /// </summary>
            public GameObject genericGunAnimatorControllerPrefab;

            /// <summary>
            /// Uses the generic walk anim if true
            /// </summary>
            public bool useGenericWalkAnim = true;

            /// <summary>
            /// Uses the generic run anim if true
            /// </summary>
            public bool useGenericRunAnim = true;
            #endregion


            #region Overriden functions
            public override WeaponDisplayData GetWeaponDisplayData(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                WeaponDisplayData wdd = new WeaponDisplayData();
                wdd.sprite = weaponHudPicture;
                wdd.name = weaponName.GetLocalizedString();
                return wdd;
            }

            public override void SetupFirstPerson(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                //Set RPM
                fireRate = 60f / RPM;

                Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                //Setup root for this weapon
                GameObject root = new GameObject("Weapon root");
                root.transform.parent = pb.weaponsGo; //Set root
                root.transform.localPosition = Vector3.zero; //Reset position
                root.transform.localRotation = Quaternion.identity; //Reset rotation
                root.transform.localScale = Vector3.one; //Reset scale

                //Setup generic animations
                GameObject genericAnimations = Instantiate(genericGunAnimatorControllerPrefab);
                genericAnimations.transform.parent = root.transform;
                genericAnimations.transform.localPosition = Vector3.zero; //Reset position
                genericAnimations.transform.localRotation = Quaternion.identity; //Reset rotation
                genericAnimations.transform.localScale = Vector3.one; //Reset scale

                //Get animator
                Animator anim = genericAnimations.GetComponent<Animator>(); ;
                anim.Play("Idle");
                data.genericAnimator = anim;

                //Setup aiming transform
                GameObject aimTrans = new GameObject("Weapon aiming");
                aimTrans.transform.parent = genericAnimations.transform; //Set root
                aimTrans.transform.localPosition = Vector3.zero; //Reset position
                aimTrans.transform.localRotation = Quaternion.identity; //Reset rotation
                aimTrans.transform.localScale = Vector3.one; //Reset scale

                //Assign it
                data.aimingTransform = aimTrans.transform;

                //Delay transform
                GameObject delayTrans = new GameObject("Weapon delay");
                delayTrans.transform.parent = aimTrans.transform; //Set root
                delayTrans.transform.localPosition = Vector3.zero; //Reset position
                delayTrans.transform.localRotation = Quaternion.identity; //Reset rotation
                delayTrans.transform.localScale = Vector3.one; //Reset scale

                //Assign it
                data.weaponDelayTransform = delayTrans.transform;

                //Delay transform
                GameObject fallTrans = new GameObject("Weapon fall");
                fallTrans.transform.parent = delayTrans.transform; //Set root
                fallTrans.transform.localPosition = Vector3.zero; //Reset position
                fallTrans.transform.localRotation = Quaternion.identity; //Reset rotation
                fallTrans.transform.localScale = Vector3.one; //Reset scale

                //Assign it
                data.weaponFallTransform = fallTrans.transform;

                //Get Fire Audio (Needs to be consistent)
                if (pb.weaponsGo.GetComponent<AudioSource>()) data.soundFire = pb.weaponsGo.GetComponent<AudioSource>();
                else data.soundFire = pb.weaponsGo.gameObject.AddComponent<AudioSource>();

                //Setup reload sound
                GameObject soundReload = new GameObject("SoundReload"); //Create
                soundReload.transform.parent = root.transform;
                soundReload.transform.localPosition = Vector3.zero; //Reset position
                soundReload.transform.localRotation = Quaternion.identity; //Reset rotation
                soundReload.transform.localScale = Vector3.one; //Reset scale
                                                                //Add audio source
                data.soundReload = soundReload.AddComponent<AudioSource>();

                //Setup other sound
                GameObject soundOther = new GameObject("SoundOther"); //Create
                soundOther.transform.parent = root.transform;
                soundOther.transform.localPosition = Vector3.zero; //Reset position
                soundOther.transform.localRotation = Quaternion.identity; //Reset rotation
                soundOther.transform.localScale = Vector3.one; //Reset scale
                                                               //Add audio source
                data.soundOther = soundOther.AddComponent<AudioSource>();

                //Copy data first
                data.fireMode = fireMode;
                data.fireRate = 60f / RPM;
                data.bulletsPerMag = bulletsPerMag;
                data.bulletsToReloadAtStart = bulletsToReloadAtStart;
                data.baseDamage = baseDamage;
                data.range = range;
                data.damageDropoff = damageDropoff;
                data.fireTypeMode = fireTypeMode;
                data.burstBulletsPerShot = burstBulletsPerShot;
                data.burstTimeBetweenShots = burstTimeBetweenShots;
                data.amountOfPellets = amountOfPellets;
                data.speedMultiplierBase = speedMultiplierBase;
                data.ragdollForce = ragdollForce;

                data.bulletsMode = bulletsMode;
                data.bulletsPenetrationEnabled = bulletsPenetrationEnabled;
                data.bulletsPenetrationForce = bulletsPenetrationForce;
                data.bulletPrefab = bulletPrefab;
                data.bulletSpeed = bulletSpeed;
                data.bulletHideForFrames = bulletHideForFrames;
                data.bulletGravityMultiplier = bulletGravityMultiplier;
                data.bulletLifeTime = bulletLifeTime;
                data.bulletStaysAliveAfterDeath = bulletStaysAliveAfterDeath;
                data.bulletStaysAliveAfterDeathTime = bulletStaysAliveAfterDeathTime;

                data.bulletSpreadMode = bulletSpreadMode;
                data.bulletSpreadHipBase = bulletSpreadHipBase;
                data.bulletSpreadHipVelocityAdd = bulletSpreadHipVelocityAdd;
                data.bulletSpreadHipVelocityReference = bulletSpreadHipVelocityReference;
                data.bulletSpreadAimBase = bulletSpreadAimBase;
                data.bulletSpreadAimVelocityAdd = bulletSpreadAimVelocityAdd;
                data.bulletSpreadAimVelocityReference = bulletSpreadAimVelocityReference;

                data.bulletSpreadSprayPattern = bulletSpreadSprayPattern;
                data.bulletSpreadSprayPatternRecoverySpeed = bulletSpreadSprayPatternRecoverySpeed;

                data.recoilPerShotMin = recoilPerShotMin;
                data.recoilPerShotMax = recoilPerShotMax;
                data.recoilApplyTime = recoilApplyTime;
                data.recoilReturnSpeed = recoilReturnSpeed;

                //Setup the first person prefab
                GameObject fpRuntime = Instantiate(firstPersonPrefab, fallTrans.transform, false);
                fpRuntime.transform.localScale = Vector3.one; //Reset scale

                //Setup renderer
                data.weaponRenderer = fpRuntime.GetComponent<Kit_WeaponRenderer>();
                //Set Attachments
                data.weaponRenderer.SetAttachments(data.attachments.ToArray(), this, pb, data);

                //Play Dependent arms
                if (data.weaponRenderer.playerModelDependentArmsEnabled && pb.thirdPersonPlayerModel.firstPersonArmsPrefab.Contains(data.weaponRenderer.playerModelDependentArmsKey))
                {
                    //Create Prefab
                    GameObject fpArms = Instantiate(pb.thirdPersonPlayerModel.firstPersonArmsPrefab[data.weaponRenderer.playerModelDependentArmsKey], fallTrans.transform, false);
                    //Get Arms
                    Kit_FirstPersonArms fpa = fpArms.GetComponent<Kit_FirstPersonArms>();

                    if (fpa.cameraBoneOverride)
                    {
                        data.weaponRenderer.cameraAnimationBone = fpa.cameraBoneOverride;
                    }

                    if (fpa.cameraBoneTargetOverride)
                    {
                        data.weaponRenderer.cameraAnimationTarget = fpa.cameraBoneTargetOverride;
                    }

#if INTEGRATION_FPV2
                        //Set shaders
                        FirstPersonView.ShaderMaterialSolution.FPV_SM_Object armsObj = fpArms.GetComponent<FirstPersonView.ShaderMaterialSolution.FPV_SM_Object>();
                        if (armsObj)
                        {
                            //Set as first person object
                            armsObj.SetAsFirstPersonObject();
                        }
                        else
                        {
                            Debug.LogError("FPV2 is enabled but first person prefab does not have FPV_SM_Object assigned!");
                        }

#elif INTEGRATION_FPV3
                        //Set shaders
                        FirstPersonView.FPV_Object armsObj = fpArms.GetComponent<FirstPersonView.FPV_Object>();
                        if (armsObj)
                        {
                            //Set as first person object
                            armsObj.SetAsFirstPersonObject();
                        }
                        else
                        {
                            Debug.LogError("FPV3 is enabled but first person prefab does not have FPV_Object assigned!");
                        }
#endif

                    //Reparent
                    for (int i = 0; i < fpa.reparents.Length; i++)
                    {
                        if (fpa.reparents[i])
                        {
                            fpa.reparents[i].transform.parent = data.weaponRenderer.playerModelDependentArmsRoot;
                        }
                        else
                        {
                            Debug.LogWarning("First Person Arm Renderer at index " + i + " is not assigned", fpa);
                        }
                    }
                    //Merge Array
                    data.weaponRenderer.allWeaponRenderers = data.weaponRenderer.allWeaponRenderers.Concat(fpa.renderers).ToArray();
                    //Rebind so that the animator animates our freshly reparented transforms too!
                    if (data.weaponRenderer.anim)
                    {
                        data.weaponRenderer.anim.Rebind();

                        for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                        {
                            data.weaponRenderer.animAdditionals[i].Rebind();
                        }
                    }
                }

                //Hide
                data.weaponRenderer.visible = false;

#if INTEGRATION_FPV2
                    //Set shaders
                    FirstPersonView.ShaderMaterialSolution.FPV_SM_Object obj = fpRuntime.GetComponent<FirstPersonView.ShaderMaterialSolution.FPV_SM_Object>();
                    if (obj)
                    {
                        //Set as first person object
                        obj.SetAsFirstPersonObject();
                    }
                    else
                    {
                        Debug.LogError("FPV2 is enabled but first person prefab does not have FPV_SM_Object assigned!");
                    }
#elif INTEGRATION_FPV3
                    //Set shaders
                    FirstPersonView.FPV_Object obj = fpRuntime.GetComponent<FirstPersonView.FPV_Object>();
                    if (obj)
                    {
                        //Set as first person object
                        obj.SetAsFirstPersonObject();
                    }
                    else
                    {
                        Debug.LogError("FPV3 is enabled but first person prefab does not have FPV_Object assigned!");
                    }
#endif

                //Add to the list
                data.instantiatedObjects.Add(root);

                //Setup start values
                data.bulletsLeft = data.bulletsPerMag;
                data.bulletsLeftToReload = data.bulletsToReloadAtStart;

                //Object Pool the bullet
                Kit_IngameMain.instance.objectPooling.EnqueueInstantiateable(data.bulletPrefab, 50);
                //And shell
                if (shellEjectionPrefab)
                {
                    Kit_IngameMain.instance.objectPooling.EnqueueInstantiateable(shellEjectionPrefab, 50);
                }
            }

            public override void SetupThirdPerson(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                //Setup the third person prefab
                GameObject tpRuntime = Instantiate(thirdPersonPrefab, pb.thirdPersonPlayerModel.weaponsInHandsGo, false);
                //Set Scale
                tpRuntime.transform.localScale = Vector3.one;

                //Setup renderer
                data.tpWeaponRenderer = tpRuntime.GetComponent<Kit_ThirdPersonWeaponRenderer>();
                data.tpWeaponRenderer.visible = false;
                if (pb.isFirstPersonActive)
                {
                    //Make it shadows only
                    data.tpWeaponRenderer.shadowsOnly = true;
                }
                //Setup attachments
                data.tpWeaponRenderer.SetAttachments(data.attachments.ToArray(), this, pb, data);

                //Add to the list
                data.instantiatedObjects.Add(tpRuntime);

                //Object Pool the bullet
                Kit_IngameMain.instance.objectPooling.EnqueueInstantiateable(data.bulletPrefab, 50);
                //And shell
                if (shellEjectionPrefab)
                {
                    Kit_IngameMain.instance.objectPooling.EnqueueInstantiateable(shellEjectionPrefab, 50);
                }
            }

            public override void AuthorativeInput(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData, Kit_PlayerInput input, float delta, double revertTime)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;


                    //Set this weapon to selected and ready (for other things)
                    data.isSelectedAndReady = true;

                    //If we are not reloading
                    if (!data.reloadInProgress)
                    {
                        //Check if movement and time allows firing
                        if (pb.movement.CanFire(pb) && Time.time - timeCannotFireAfterRun > data.lastRun)
                        {
                            //Fire modes
                            if (data.fireMode == FireMode.Semi)
                            {
                                //We cannot fire full auto, set value
                                data.isFiring = false;
                                //Check for input
                                if (data.lastLmb != input.lmb)
                                {
                                    data.lastLmb = input.lmb;
                                    if (input.lmb)
                                    {
                                        //Compare with fire rate
                                        if (Time.time >= data.lastFire + data.fireRate)
                                        {
                                            if (data.bulletsLeft > 0)
                                            {
                                                FireOneShot(pb, data, delta, (float)revertTime, false);
                                            }
                                            else if (!Kit_IngameMain.instance.gameInformation.enableAutoReload || data.bulletsLeftToReload == 0) //No ammo, dry fire
                                            {
                                                DryFire(pb, data);
                                            }
                                        }
                                    }
                                }
                            }
                            else if (data.fireMode == FireMode.BoltAction)
                            {
                                //We cannot fire full auto, set value
                                data.isFiring = false;
                                //Check for input
                                if (data.lastLmb != input.lmb)
                                {
                                    data.lastLmb = input.lmb;
                                    if (input.lmb)
                                    {
                                        //In bolt action, lastFire already includes bolt time
                                        if (Time.time >= data.lastFire)
                                        {
                                            if (data.bulletsLeft > 0)
                                            {
                                                FireOneShot(pb, data, delta, (float)revertTime, false);
                                            }
                                            else if (!Kit_IngameMain.instance.gameInformation.enableAutoReload || data.bulletsLeftToReload == 0) //No ammo, dry fire
                                            {
                                                DryFire(pb, data);
                                            }
                                        }
                                    }
                                }
                            }
                            else if (data.fireMode == FireMode.Auto)
                            {
                                //Check for input
                                if (input.lmb)
                                {
                                    //Compare with fire rate
                                    if (Time.time >= data.lastFire + data.fireRate)
                                    {
                                        //Compare bullets left
                                        if (data.bulletsLeft > 0)
                                        {
                                            FireOneShot(pb, data, delta, (float)revertTime, false);
                                            //We are firing full auto, set value
                                            data.isFiring = true;
                                        }
                                        else if (!Kit_IngameMain.instance.gameInformation.enableAutoReload || data.bulletsLeftToReload == 0) //No ammo, dry fire
                                        {
                                            DryFire(pb, data);
                                            //We cannot fire, set value
                                            data.isFiring = false;
                                        }
                                    }
                                }
                                else
                                {
                                    //We cannot fire, set value
                                    data.isFiring = false;
                                }
                            }
                            else if (data.fireMode == FireMode.Burst)
                            {
                                //We cannot fire full auto, set value
                                data.isFiring = false;
                                //Check for input
                                if (data.lastLmb != input.lmb)
                                {
                                    data.lastLmb = input.lmb;
                                    if (input.lmb)
                                    {
                                        //Compare with fire rate
                                        if (Time.time >= data.lastFire + data.fireRate)
                                        {
                                            if (data.bulletsLeft > 0)
                                            {
                                                FireBurst(pb, data, delta, (float)revertTime, false);
                                            }
                                            else if (!Kit_IngameMain.instance.gameInformation.enableAutoReload || data.bulletsLeftToReload == 0) //No ammo, dry fire
                                            {
                                                DryFire(pb, data);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //We cannot fire, set value
                            data.isFiring = false;
                        }

                        //Aiming input
                        if (pb.movement.CanFire(pb) && aimEnabled)
                        {
                            //Check for input
                            if (input.aiming)
                            {
                                //Check if we can aim
                                if (data.isSelectedAndReady && !data.reloadInProgress)
                                {
                                    data.isAiming = true;
                                }
                                //Else we cannot aim, set to not aiming
                                else
                                {
                                    data.isAiming = false;
                                }
                            }
                            //Else we cannot aim, set to not aiming
                            else
                            {
                                data.isAiming = false;
                            }
                        }
                        //Else we cannot aim, set to not aiming
                        else
                        {
                            data.isAiming = false;
                        }

                        //Check for input
                        if (data.lastReload != input.reload || Kit_IngameMain.instance.gameInformation.enableAutoReload && data.bulletsLeft == 0 && data.bulletsLeftToReload > 0 && Time.time > data.lastFire + 0.5f)
                        {
                            data.lastReload = input.reload;
                            if (input.reload || Kit_IngameMain.instance.gameInformation.enableAutoReload && data.bulletsLeft == 0 && data.bulletsLeftToReload > 0)
                            {
                                //Check if we can start reload
                                if (data.fireMode != FireMode.BoltAction || data.fireMode == FireMode.BoltAction && Time.time > data.lastFire)
                                {
                                    //Check if we have spare ammo
                                    if (data.bulletsLeftToReload > 0)
                                    {
                                        //Check if the weapon isn't already full (Chambered means we can have one in the chamber)
                                        if ((reloadMode == ReloadMode.Chambered || reloadMode == ReloadMode.ProceduralChambered) && data.bulletsLeft != data.bulletsPerMag + 1 || reloadMode != ReloadMode.Chambered && reloadMode != ReloadMode.ProceduralChambered && data.bulletsLeft != data.bulletsPerMag)
                                        {
                                            data.reloadInProgress = true;
                                            //Play reload voice
                                            if (pb.voiceManager)
                                            {
                                                pb.voiceManager.Reloading(pb);
                                            }
                                            //Reset run animation
                                            data.startedRunAnimation = false;
                                            switch (reloadMode)
                                            {
                                                //Set reload time
                                                case ReloadMode.Simple:
                                                    //Simple reload, set time
                                                    data.reloadNextEnd = Time.time + reloadTimeOne;
                                                    data.reloadPhase = 0;
                                                    if (pb.isFirstPersonActive)
                                                    {
                                                        if (data.weaponRenderer.anim)
                                                        {
                                                            //Play animation
                                                            data.weaponRenderer.anim.Play("Reload Full", data.weaponRenderer.animActionLayer, 0f);

                                                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                            {
                                                                data.weaponRenderer.animAdditionals[i].Play("Reload Full", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                            }
                                                        }
                                                        else if (data.weaponRenderer.legacyAnim)
                                                        {
                                                            //Play animation
                                                            data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reload, 0.15f, PlayMode.StopAll);
                                                        }
                                                        //Play sound
                                                        data.soundReload.PlayOneShot(reloadSound);
                                                    }
                                                    else
                                                    {
                                                        //Set clip
                                                        pb.thirdPersonPlayerModel.soundReload.clip = reloadSound;
                                                        //Set distance
                                                        pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                        //Set rolloff
                                                        pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                        //Play
                                                        pb.thirdPersonPlayerModel.soundReload.Play();
                                                    }
                                                    //Call network
                                                    if (pb.isServer) pb.RpcWeaponReloadNetwork(false);
                                                    //Play third person reload anim
                                                    pb.thirdPersonPlayerModel.PlayWeaponReloadAnimation(thirdPersonAnimType, 0);
                                                    break;

                                                case ReloadMode.FullEmpty:
                                                    //Set time for full
                                                    if (data.bulletsLeft > 0)
                                                    {
                                                        //Set time
                                                        data.reloadNextEnd = Time.time + reloadTimeOne;
                                                        data.reloadPhase = 0;
                                                        if (pb.isFirstPersonActive)
                                                        {
                                                            //Play animation
                                                            if (data.weaponRenderer.anim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.anim.Play("Reload Full", data.weaponRenderer.animActionLayer, 0f);

                                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                                {
                                                                    data.weaponRenderer.animAdditionals[i].Play("Reload Full", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                                }
                                                            }
                                                            else if (data.weaponRenderer.legacyAnim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reload, 0.15f, PlayMode.StopAll);
                                                            }
                                                            //Play sound
                                                            data.soundReload.PlayOneShot(reloadSound);
                                                        }
                                                        else
                                                        {
                                                            //Set clip
                                                            pb.thirdPersonPlayerModel.soundReload.clip = reloadSound;
                                                            //Set distance
                                                            pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                            //Set rolloff
                                                            pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                            //Play
                                                            pb.thirdPersonPlayerModel.soundReload.Play();
                                                        }
                                                        //Call network
                                                        if (pb.isServer) pb.RpcWeaponReloadNetwork(false);
                                                        //Play third person reload anim
                                                        pb.thirdPersonPlayerModel.PlayWeaponReloadAnimation(thirdPersonAnimType, 0);
                                                    }
                                                    //Empty
                                                    else
                                                    {
                                                        //Set time
                                                        data.reloadNextEnd = Time.time + reloadEmptyTimeOne;
                                                        data.reloadPhase = 0;
                                                        if (pb.isFirstPersonActive)
                                                        {
                                                            //Play animation
                                                            if (data.weaponRenderer.anim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.anim.Play("Reload Empty", data.weaponRenderer.animActionLayer, 0f);

                                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                                {
                                                                    data.weaponRenderer.animAdditionals[i].Play("Reload Empty", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                                }
                                                            }
                                                            else if (data.weaponRenderer.legacyAnim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reloadEmpty, 0.15f, PlayMode.StopAll);
                                                            }
                                                            //Play sound
                                                            data.soundReload.PlayOneShot(reloadSoundEmpty);
                                                        }
                                                        else
                                                        {
                                                            //Play reload sound
                                                            //Set clip
                                                            pb.thirdPersonPlayerModel.soundReload.clip = reloadSoundEmpty;
                                                            //Set distance
                                                            pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                            //Set rolloff
                                                            pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                            //Play
                                                            pb.thirdPersonPlayerModel.soundReload.Play();
                                                        }
                                                        //Call network
                                                        if (pb.isServer) pb.RpcWeaponReloadNetwork(true);
                                                        //Play third person reload anim
                                                        pb.thirdPersonPlayerModel.PlayWeaponReloadAnimation(thirdPersonAnimType, 0);
                                                    }
                                                    break;
                                                case ReloadMode.Chambered:
                                                    //Set time for full
                                                    if (data.bulletsLeft > 0)
                                                    {
                                                        //Set time
                                                        data.reloadNextEnd = Time.time + reloadTimeOne;
                                                        data.reloadPhase = 0;
                                                        if (pb.isFirstPersonActive)
                                                        {
                                                            //Play animation
                                                            if (data.weaponRenderer.anim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.anim.Play("Reload Full", data.weaponRenderer.animActionLayer, 0f);

                                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                                {
                                                                    data.weaponRenderer.animAdditionals[i].Play("Reload Full", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                                }
                                                            }
                                                            else if (data.weaponRenderer.legacyAnim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reload, 0.15f, PlayMode.StopAll);
                                                            }
                                                            //Play sound
                                                            data.soundReload.PlayOneShot(reloadSound);
                                                        }
                                                        else
                                                        {
                                                            //Set clip
                                                            pb.thirdPersonPlayerModel.soundReload.clip = reloadSound;
                                                            //Set distance
                                                            pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                            //Set rolloff
                                                            pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                            //Play
                                                            pb.thirdPersonPlayerModel.soundReload.Play();
                                                        }
                                                        //Call network
                                                        if (pb.isServer) pb.RpcWeaponReloadNetwork(false);
                                                        //Play third person reload anim
                                                        pb.thirdPersonPlayerModel.PlayWeaponReloadAnimation(thirdPersonAnimType, 0);
                                                    }
                                                    //Empty
                                                    else
                                                    {
                                                        //Set time
                                                        data.reloadNextEnd = Time.time + reloadEmptyTimeOne;
                                                        data.reloadPhase = 0;
                                                        if (pb.isFirstPersonActive)
                                                        {
                                                            //Play animation
                                                            if (data.weaponRenderer.anim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.anim.Play("Reload Empty", data.weaponRenderer.animActionLayer, 0f);

                                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                                {
                                                                    data.weaponRenderer.animAdditionals[i].Play("Reload Empty", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                                }
                                                            }
                                                            else if (data.weaponRenderer.legacyAnim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reloadEmpty, 0.15f, PlayMode.StopAll);
                                                            }
                                                            //Play sound
                                                            data.soundReload.PlayOneShot(reloadSoundEmpty);
                                                        }
                                                        else
                                                        {
                                                            //Play reload sound
                                                            //Set clip
                                                            pb.thirdPersonPlayerModel.soundReload.clip = reloadSoundEmpty;
                                                            //Set distance
                                                            pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                            //Set rolloff
                                                            pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                            //Play
                                                            pb.thirdPersonPlayerModel.soundReload.Play();
                                                        }
                                                        //Call network
                                                        if (pb.isServer) pb.RpcWeaponReloadNetwork(true);
                                                        //Play third person reload anim
                                                        pb.thirdPersonPlayerModel.PlayWeaponReloadAnimation(thirdPersonAnimType, 0);
                                                    }
                                                    break;
                                                case ReloadMode.Procedural:
                                                    if (data.bulletsLeft > 0)
                                                    {
                                                        //Set phase
                                                        data.reloadPhase = 0;
                                                        //Set time
                                                        data.reloadNextEnd = Time.time + reloadProceduralStartTime;
                                                        if (pb.isFirstPersonActive)
                                                        {
                                                            //Play animation
                                                            if (data.weaponRenderer.anim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.anim.Play("Reload Procedural Start", data.weaponRenderer.animActionLayer, 0f);

                                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                                {
                                                                    data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Start", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                                }
                                                            }
                                                            else if (data.weaponRenderer.legacyAnim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reloadProceduralStart, 0.15f, PlayMode.StopAll);
                                                            }
                                                            //Play sound
                                                            data.soundReload.PlayOneShot(reloadProceduralStartSound);
                                                        }
                                                        else
                                                        {
                                                            //Play reload sound
                                                            //Set clip
                                                            pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralStartSound;
                                                            //Set distance
                                                            pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                            //Set rolloff
                                                            pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                            //Play
                                                            pb.thirdPersonPlayerModel.soundReload.Play();
                                                        }
                                                        //Set cancel state
                                                        data.cancelProceduralReload = false;
                                                        //Call network
                                                        if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(0);
                                                        //Set cancel state
                                                        data.cancelProceduralReload = false;
                                                    }
                                                    else
                                                    {
                                                        //Set phase
                                                        data.reloadPhase = 0;
                                                        //Set time
                                                        if (reloadProceduralAddBulletDuringStartEmpty && data.bulletsLeft == 0)
                                                        {
                                                            data.reloadNextEnd = Time.time + reloadProceduralEmptyInsertStartTimeOne;
                                                        }
                                                        else
                                                        {
                                                            data.reloadNextEnd = Time.time + reloadProceduralEmptyStartTime;
                                                        }
                                                        if (pb.isFirstPersonActive)
                                                        {
                                                            if (data.weaponRenderer.anim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.anim.Play("Reload Procedural Start Empty", data.weaponRenderer.animActionLayer, 0f);

                                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                                {
                                                                    data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Start Empty", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                                }
                                                            }
                                                            else if (data.weaponRenderer.legacyAnim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reloadProceduralStartEmpty, 0.15f, PlayMode.StopAll);
                                                            }
                                                            //Play sound
                                                            data.soundReload.PlayOneShot(reloadProceduralStartEmptySound);
                                                        }
                                                        else
                                                        {
                                                            //Play reload sound
                                                            //Set clip
                                                            pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralStartEmptySound;
                                                            //Set distance
                                                            pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                            //Set rolloff
                                                            pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                            //Play
                                                            pb.thirdPersonPlayerModel.soundReload.Play();
                                                        }
                                                        //Set cancel state
                                                        data.cancelProceduralReload = false;
                                                        //Call network
                                                        if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(1);
                                                    }
                                                    break;
                                                case ReloadMode.ProceduralChambered:
                                                    if (data.bulletsLeft > 0)
                                                    {
                                                        //Set phase
                                                        data.reloadPhase = 0;
                                                        //Set time
                                                        data.reloadNextEnd = Time.time + reloadProceduralStartTime;
                                                        if (pb.isFirstPersonActive)
                                                        {
                                                            //Play animation
                                                            if (data.weaponRenderer.anim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.anim.Play("Reload Procedural Start", data.weaponRenderer.animActionLayer, 0f);

                                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                                {
                                                                    data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Start", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                                }
                                                            }
                                                            else if (data.weaponRenderer.legacyAnim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reloadProceduralStart, 0.15f, PlayMode.StopAll);
                                                            }
                                                            //Play sound
                                                            data.soundReload.PlayOneShot(reloadProceduralStartSound);
                                                        }
                                                        else
                                                        {
                                                            //Play reload sound
                                                            //Set clip
                                                            pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralStartSound;
                                                            //Set distance
                                                            pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                            //Set rolloff
                                                            pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                            //Play
                                                            pb.thirdPersonPlayerModel.soundReload.Play();
                                                        }
                                                        //Set cancel state
                                                        data.cancelProceduralReload = false;
                                                        //Call network
                                                        if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(0);
                                                        //Set cancel state
                                                        data.cancelProceduralReload = false;
                                                    }
                                                    else
                                                    {
                                                        //Set phase
                                                        data.reloadPhase = 0;
                                                        //Set time
                                                        if (reloadProceduralAddBulletDuringStartEmpty && data.bulletsLeft == 0)
                                                        {
                                                            data.reloadNextEnd = Time.time + reloadProceduralEmptyInsertStartTimeOne;
                                                        }
                                                        else
                                                        {
                                                            data.reloadNextEnd = Time.time + reloadProceduralEmptyStartTime;
                                                        }
                                                        if (pb.isFirstPersonActive)
                                                        {
                                                            if (data.weaponRenderer.anim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.anim.Play("Reload Procedural Start Empty", data.weaponRenderer.animActionLayer, 0f);

                                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                                {
                                                                    data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Start Empty", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                                }
                                                            }
                                                            else if (data.weaponRenderer.legacyAnim)
                                                            {
                                                                //Play animation
                                                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reloadProceduralStartEmpty, 0.15f, PlayMode.StopAll);
                                                            }
                                                            //Play sound
                                                            data.soundReload.PlayOneShot(reloadProceduralStartEmptySound);
                                                        }
                                                        else
                                                        {
                                                            //Play reload sound
                                                            //Set clip
                                                            pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralStartEmptySound;
                                                            //Set distance
                                                            pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                            //Set rolloff
                                                            pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                            //Play
                                                            pb.thirdPersonPlayerModel.soundReload.Play();
                                                        }
                                                        //Set cancel state
                                                        data.cancelProceduralReload = false;
                                                        //Call network
                                                        if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(1);
                                                    }
                                                    break;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (data != null && data.weaponRenderer && data.weaponRenderer.cachedInteractionAttachments != null)
                        {
                            //Attachment interaction, only when we can control.
                            for (int i = 0; i < data.weaponRenderer.cachedInteractionAttachments.Length; i++)
                            {
                                data.weaponRenderer.cachedInteractionAttachments[i].Interaction(pb);
                            }
                        }

                        if (setEmptyBool && pb.isFirstPersonActive && data.weaponRenderer.anim)
                        {
                            //Set empty bool
                            data.weaponRenderer.anim.SetBool("empty", data.bulletsLeft == 0);

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].SetBool("empty", data.bulletsLeft == 0);
                            }
                        }
                    }
                    //Reloading
                    else
                    {
                        //When we are reloading, empty bool will be 'false'
                        if (setEmptyBool && pb.isFirstPersonActive && data.weaponRenderer.anim)
                        {
                            //Set empty bool
                            data.weaponRenderer.anim.SetBool("empty", false);

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].SetBool("empty", false);
                            }
                        }
                        //Reset run animation
                        data.startedRunAnimation = false;
                        //Make sure we are not aiming
                        data.isAiming = false;
                        //Make sure we are not firing either
                        data.isFiring = false;
                        //Check for cancelling
                        if (reloadMode == ReloadMode.Procedural || reloadMode == ReloadMode.ProceduralChambered)
                        {
                            if (data.lastLmb != input.lmb)
                            {
                                data.lastLmb = input.lmb;
                                if (input.lmb && data.bulletsLeft > 0)
                                {
                                    //User wants to cancel
                                    data.cancelProceduralReload = true;
                                    data.reloadPhase = 0;
                                    data.reloadInProgress = false;
                                    FireOneShot(pb, data, delta, (float)revertTime, false);
                                }
                            }
                        }
                        else
                        {
                            data.cancelProceduralReload = false;
                        }

                        //Check if a reload phase is over
                        if (Time.time >= data.reloadNextEnd)
                        {
                            switch (reloadMode)
                            {
                                //Simple reload
                                case ReloadMode.Simple:
                                    if (data.reloadPhase == 0)
                                    {
                                        //Update bullets
                                        if (data.bulletsLeftToReload > data.bulletsPerMag)
                                        {
                                            if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                                data.bulletsLeftToReload -= data.bulletsPerMag - data.bulletsLeft;
                                            data.bulletsLeft = data.bulletsPerMag;
                                        }
                                        else
                                        {
                                            int wepBullet = Mathf.Clamp(data.bulletsPerMag, data.bulletsLeftToReload, data.bulletsLeft + data.bulletsLeftToReload);
                                            if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                                data.bulletsLeftToReload -= (wepBullet - data.bulletsLeft);
                                            data.bulletsLeft = wepBullet;
                                        }
                                        //Proceed
                                        data.reloadPhase = 1;
                                        data.reloadNextEnd = Time.time + reloadTimeTwo;
                                    }
                                    else if (data.reloadPhase == 1)
                                    {
                                        //Reload is over
                                        data.reloadInProgress = false;
                                        data.reloadPhase = 0;
                                    }
                                    break;

                                //Reload with different anims / times for full / empty state
                                case ReloadMode.FullEmpty:
                                    if (data.reloadPhase == 0)
                                    {
                                        //Set time
                                        if (data.bulletsLeft > 0)
                                        {
                                            //Full reload
                                            data.reloadNextEnd = Time.time + reloadTimeTwo;
                                        }
                                        else
                                        {
                                            //Empty reload
                                            data.reloadNextEnd = Time.time + reloadEmptyTimeTwo;
                                        }

                                        //Update bullets
                                        if (data.bulletsLeftToReload > data.bulletsPerMag)
                                        {
                                            if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                                data.bulletsLeftToReload -= data.bulletsPerMag - data.bulletsLeft;
                                            data.bulletsLeft = data.bulletsPerMag;
                                        }
                                        else
                                        {
                                            int wepBullet = Mathf.Clamp(data.bulletsPerMag, data.bulletsLeftToReload, data.bulletsLeft + data.bulletsLeftToReload);
                                            if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                                data.bulletsLeftToReload -= (wepBullet - data.bulletsLeft);
                                            data.bulletsLeft = wepBullet;
                                        }
                                        //Proceed
                                        data.reloadPhase = 1;
                                    }
                                    else if (data.reloadPhase == 1)
                                    {
                                        //Reload is over
                                        data.reloadInProgress = false;
                                        data.reloadPhase = 0;
                                    }
                                    break;
                                //Reload with different anims / times for full / empty state and a bullet in the chamber
                                case ReloadMode.Chambered:
                                    if (data.reloadPhase == 0)
                                    {
                                        //Set time
                                        if (data.bulletsLeft > 0)
                                        {
                                            //Full reload
                                            data.reloadNextEnd = Time.time + reloadTimeTwo;
                                        }
                                        else
                                        {
                                            //Empty reload
                                            data.reloadNextEnd = Time.time + reloadEmptyTimeTwo;
                                        }

                                        //Update bullets
                                        if (data.bulletsLeftToReload > data.bulletsPerMag)
                                        {
                                            if (data.bulletsLeft > 0)
                                            {
                                                if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                                    data.bulletsLeftToReload -= (data.bulletsPerMag + 1) - data.bulletsLeft;
                                                data.bulletsLeft = data.bulletsPerMag + 1;
                                            }
                                            else
                                            {
                                                if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                                    data.bulletsLeftToReload -= data.bulletsPerMag - data.bulletsLeft;
                                                data.bulletsLeft = data.bulletsPerMag;
                                            }
                                        }
                                        else
                                        {
                                            if (data.bulletsLeft > 0)
                                            {
                                                int wepBullet = Mathf.Clamp(data.bulletsPerMag + 1, data.bulletsLeftToReload, data.bulletsLeft + data.bulletsLeftToReload);
                                                if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                                    data.bulletsLeftToReload -= (wepBullet - data.bulletsLeft);
                                                data.bulletsLeft = wepBullet;
                                            }
                                            else
                                            {
                                                int wepBullet = Mathf.Clamp(data.bulletsPerMag, data.bulletsLeftToReload, data.bulletsLeft + data.bulletsLeftToReload);
                                                if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                                    data.bulletsLeftToReload -= (wepBullet - data.bulletsLeft);
                                                data.bulletsLeft = wepBullet;
                                            }
                                        }
                                        //Proceed
                                        data.reloadPhase = 1;
                                    }
                                    else if (data.reloadPhase == 1)
                                    {
                                        //Reload is over
                                        data.reloadInProgress = false;
                                        data.reloadPhase = 0;
                                    }
                                    break;
                                case ReloadMode.Procedural:
                                    //Phase 0 = Start
                                    //Phase 1 = End of start (If bullet needs to be added)
                                    //Phase 2 = Loop
                                    //Phase 3 = Loop 2
                                    //Phase 4 = End
                                    if (data.reloadPhase == 0)
                                    {
                                        if (reloadProceduralAddBulletDuringStartEmpty && data.bulletsLeft == 0)
                                        {
                                            //Set phase
                                            data.reloadPhase = 1;
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralEmptyInsertStartTimeTwo;
                                            //Add bullet
                                            data.bulletsLeft++;
                                            //Substract
                                            if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                                data.bulletsLeftToReload--;
                                            //Sounds and animation is already being played, so ignore that
                                        }
                                        else
                                        {
                                            //Go to Phase 2
                                            data.reloadPhase = 2;
                                            //Here we don't need to check if ammo is left because we already did that
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralInsertTimeOne;
                                            if (pb.isFirstPersonActive)
                                            {
                                                //Play animation
                                                if (data.weaponRenderer.anim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.anim.Play("Reload Procedural Insert", data.weaponRenderer.animActionLayer, 0f);

                                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                    {
                                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Insert", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                    }
                                                }
                                                else if (data.weaponRenderer.legacyAnim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.legacyAnim.Rewind(data.weaponRenderer.legacyAnimData.reloadProceduralInsert);
                                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralInsert, PlayMode.StopAll);
                                                }
                                                //Play sound
                                                data.soundReload.PlayOneShot(reloadProceduralInsertSound);
                                            }
                                            else
                                            {
                                                //Play reload sound
                                                //Set clip
                                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralInsertSound;
                                                //Set distance
                                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                //Set rolloff
                                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                //Play
                                                pb.thirdPersonPlayerModel.soundReload.Play();
                                            }
                                            //Call network
                                            if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(2);
                                        }
                                    }
                                    else if (data.reloadPhase == 1)
                                    {
                                        //Insert is over, check if we have more bullets to reload
                                        if (data.bulletsLeftToReload > 0 && !data.cancelProceduralReload)
                                        {
                                            //Go to Phase 2
                                            data.reloadPhase = 2;
                                            //Here we don't need to check if ammo is left because we already did that
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralInsertTimeOne;
                                            if (pb.isFirstPersonActive)
                                            {
                                                //Play animation
                                                if (data.weaponRenderer.anim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.anim.Play("Reload Procedural Insert", data.weaponRenderer.animActionLayer, 0f);

                                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                    {
                                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Insert", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                    }
                                                }
                                                else if (data.weaponRenderer.legacyAnim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.legacyAnim.Rewind(data.weaponRenderer.legacyAnimData.reloadProceduralInsert);
                                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralInsert, PlayMode.StopAll);
                                                }
                                                //Play sound
                                                data.soundReload.PlayOneShot(reloadProceduralInsertSound);
                                            }
                                            else
                                            {
                                                //Play reload sound
                                                //Set clip
                                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralInsertSound;
                                                //Set distance
                                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                //Set rolloff
                                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                //Play
                                                pb.thirdPersonPlayerModel.soundReload.Play();
                                            }
                                            //Call network
                                            if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(2);
                                        }
                                        else
                                        {
                                            //End
                                            data.reloadPhase = 4;
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralEndTime;
                                            if (pb.isFirstPersonActive)
                                            {
                                                //Play animation
                                                if (data.weaponRenderer.anim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.anim.Play("Reload Procedural End", data.weaponRenderer.animActionLayer, 0f);

                                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                    {
                                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural End", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                    }
                                                }
                                                else if (data.weaponRenderer.legacyAnim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralEnd, PlayMode.StopAll);
                                                }
                                                //Play sound
                                                data.soundReload.PlayOneShot(reloadProceduralEndSound);
                                            }
                                            else
                                            {
                                                //Play reload sound
                                                //Set clip
                                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralEndSound;
                                                //Set distance
                                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                //Set rolloff
                                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                //Play
                                                pb.thirdPersonPlayerModel.soundReload.Play();
                                            }
                                            //Call network
                                            if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(4);
                                        }
                                    }
                                    else if (data.reloadPhase == 2)
                                    {
                                        //End insert
                                        data.bulletsLeft++;
                                        //Substract
                                        if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                            data.bulletsLeftToReload--;
                                        //Wait
                                        data.reloadPhase = 3;
                                        //Set time
                                        data.reloadNextEnd = Time.time + reloadProceduralInsertTimeTwo;
                                    }
                                    else if (data.reloadPhase == 3)
                                    {
                                        //Insert is over, check if we can insert some more
                                        if (data.bulletsLeftToReload > 0 && data.bulletsLeft < data.bulletsPerMag && !data.cancelProceduralReload)
                                        {
                                            //Go to Phase 2
                                            data.reloadPhase = 2;
                                            //Here we don't need to check if ammo is left because we already did that
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralInsertTimeOne;
                                            if (pb.isFirstPersonActive)
                                            {
                                                //Play animation
                                                if (data.weaponRenderer.anim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.anim.Play("Reload Procedural Insert", data.weaponRenderer.animActionLayer, 0f);

                                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                    {
                                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Insert", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                    }
                                                }
                                                else if (data.weaponRenderer.legacyAnim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.legacyAnim.Rewind(data.weaponRenderer.legacyAnimData.reloadProceduralInsert);
                                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralInsert, PlayMode.StopAll);
                                                }
                                                //Play sound
                                                data.soundReload.PlayOneShot(reloadProceduralInsertSound);
                                            }
                                            else
                                            {
                                                //Play reload sound
                                                //Set clip
                                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralInsertSound;
                                                //Set distance
                                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                //Set rolloff
                                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                //Play
                                                pb.thirdPersonPlayerModel.soundReload.Play();
                                            }
                                            //Call network
                                            if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(2);
                                        }
                                        else
                                        {
                                            //End
                                            data.reloadPhase = 4;
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralEndTime;
                                            if (pb.isFirstPersonActive)
                                            {
                                                //Play animation
                                                if (data.weaponRenderer.anim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.anim.Play("Reload Procedural End", data.weaponRenderer.animActionLayer, 0f);

                                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                    {
                                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural End", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                    }
                                                }
                                                else if (data.weaponRenderer.legacyAnim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralEnd, PlayMode.StopAll);
                                                }
                                                //Play sound
                                                data.soundReload.PlayOneShot(reloadProceduralEndSound);
                                            }
                                            else
                                            {
                                                //Play reload sound
                                                //Set clip
                                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralEndSound;
                                                //Set distance
                                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                //Set rolloff
                                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                //Play
                                                pb.thirdPersonPlayerModel.soundReload.Play();
                                            }
                                            //Call network
                                            if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(4);
                                        }
                                    }
                                    else if (data.reloadPhase == 4)
                                    {
                                        //It is over, end reload
                                        data.reloadInProgress = false;
                                        data.reloadPhase = 0;
                                    }
                                    break;
                                case ReloadMode.ProceduralChambered:

                                    //Phase 0 = Start
                                    //Phase 1 = End of start (If bullet needs to be added)
                                    //Phase 2 = Loop
                                    //Phase 3 = Loop 2
                                    //Phase 4 = End
                                    if (data.reloadPhase == 0)
                                    {
                                        if (reloadProceduralAddBulletDuringStartEmpty && data.bulletsLeft == 0)
                                        {
                                            //Set phase
                                            data.reloadPhase = 1;
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralEmptyInsertStartTimeTwo;
                                            //Add bullet
                                            data.bulletsLeft++;
                                            //Substract
                                            if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                                data.bulletsLeftToReload--;
                                            //Sounds and animation is already being played, so ignore that
                                        }
                                        else
                                        {
                                            //Go to Phase 2
                                            data.reloadPhase = 2;
                                            //Here we don't need to check if ammo is left because we already did that
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralInsertTimeOne;
                                            if (pb.isFirstPersonActive)
                                            {
                                                //Play animation
                                                if (data.weaponRenderer.anim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.anim.Play("Reload Procedural Insert", data.weaponRenderer.animActionLayer, 0f);

                                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                    {
                                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Insert", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                    }
                                                }
                                                else if (data.weaponRenderer.legacyAnim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.legacyAnim.Rewind(data.weaponRenderer.legacyAnimData.reloadProceduralInsert);
                                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralInsert, PlayMode.StopAll);
                                                }
                                                //Play sound
                                                data.soundReload.PlayOneShot(reloadProceduralInsertSound);
                                            }
                                            else
                                            {
                                                //Play reload sound
                                                //Set clip
                                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralInsertSound;
                                                //Set distance
                                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                //Set rolloff
                                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                //Play
                                                pb.thirdPersonPlayerModel.soundReload.Play();
                                            }
                                            //Call network
                                            if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(2);
                                        }
                                    }
                                    else if (data.reloadPhase == 1)
                                    {
                                        //Insert is over, check if we have more bullets to reload
                                        if (data.bulletsLeftToReload > 0 && !data.cancelProceduralReload)
                                        {
                                            //Go to Phase 2
                                            data.reloadPhase = 2;
                                            //Here we don't need to check if ammo is left because we already did that
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralInsertTimeOne;
                                            if (pb.isFirstPersonActive)
                                            {
                                                //Play animation
                                                if (data.weaponRenderer.anim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.anim.Play("Reload Procedural Insert", data.weaponRenderer.animActionLayer, 0f);

                                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                    {
                                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Insert", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                    }
                                                }
                                                else if (data.weaponRenderer.legacyAnim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.legacyAnim.Rewind(data.weaponRenderer.legacyAnimData.reloadProceduralInsert);
                                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralInsert, PlayMode.StopAll);
                                                }
                                                //Play sound
                                                data.soundReload.PlayOneShot(reloadProceduralInsertSound);
                                            }
                                            else
                                            {
                                                //Play reload sound
                                                //Set clip
                                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralInsertSound;
                                                //Set distance
                                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                //Set rolloff
                                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                //Play
                                                pb.thirdPersonPlayerModel.soundReload.Play();
                                            }
                                            //Call network
                                            if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(2);
                                        }
                                        else
                                        {
                                            //End
                                            data.reloadPhase = 4;
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralEndTime;
                                            if (pb.isFirstPersonActive)
                                            {
                                                //Play animation
                                                if (data.weaponRenderer.anim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.anim.Play("Reload Procedural End", data.weaponRenderer.animActionLayer, 0f);

                                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                    {
                                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural End", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                    }
                                                }
                                                else if (data.weaponRenderer.legacyAnim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralEnd, PlayMode.StopAll);
                                                }
                                                //Play sound
                                                data.soundReload.PlayOneShot(reloadProceduralEndSound);
                                            }
                                            else
                                            {
                                                //Play reload sound
                                                //Set clip
                                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralEndSound;
                                                //Set distance
                                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                //Set rolloff
                                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                //Play
                                                pb.thirdPersonPlayerModel.soundReload.Play();
                                            }
                                            //Call network
                                            if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(4);
                                        }
                                    }
                                    else if (data.reloadPhase == 2)
                                    {
                                        //End insert
                                        data.bulletsLeft++;
                                        //Substract
                                        if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedReloads)
                                            data.bulletsLeftToReload--;
                                        //Wait
                                        data.reloadPhase = 3;
                                        //Set time
                                        data.reloadNextEnd = Time.time + reloadProceduralInsertTimeTwo;
                                    }
                                    else if (data.reloadPhase == 3)
                                    {
                                        //Insert is over, check if we can insert some more
                                        if (data.bulletsLeftToReload > 0 && data.bulletsLeft < data.bulletsPerMag + 1 && !data.cancelProceduralReload)
                                        {
                                            //Go to Phase 2
                                            data.reloadPhase = 2;
                                            //Here we don't need to check if ammo is left because we already did that
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralInsertTimeOne;
                                            if (pb.isFirstPersonActive)
                                            {
                                                //Play animation
                                                if (data.weaponRenderer.anim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.anim.Play("Reload Procedural Insert", data.weaponRenderer.animActionLayer, 0f);

                                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                    {
                                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Insert", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                    }
                                                }
                                                else if (data.weaponRenderer.legacyAnim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.legacyAnim.Rewind(data.weaponRenderer.legacyAnimData.reloadProceduralInsert);
                                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralInsert, PlayMode.StopAll);
                                                }
                                                //Play sound
                                                data.soundReload.PlayOneShot(reloadProceduralInsertSound);
                                            }
                                            else
                                            {
                                                //Play reload sound
                                                //Set clip
                                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralInsertSound;
                                                //Set distance
                                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                //Set rolloff
                                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                //Play
                                                pb.thirdPersonPlayerModel.soundReload.Play();
                                            }
                                            //Call network
                                            if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(2);
                                        }
                                        else
                                        {
                                            //End
                                            data.reloadPhase = 4;
                                            //Set time
                                            data.reloadNextEnd = Time.time + reloadProceduralEndTime;
                                            if (pb.isFirstPersonActive)
                                            {
                                                //Play animation
                                                if (data.weaponRenderer.anim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.anim.Play("Reload Procedural End", data.weaponRenderer.animActionLayer, 0f);

                                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                    {
                                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural End", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                                    }
                                                }
                                                else if (data.weaponRenderer.legacyAnim)
                                                {
                                                    //Play animation
                                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralEnd, PlayMode.StopAll);
                                                }
                                                //Play sound
                                                data.soundReload.PlayOneShot(reloadProceduralEndSound);
                                            }
                                            else
                                            {
                                                //Play reload sound
                                                //Set clip
                                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralEndSound;
                                                //Set distance
                                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                                //Set rolloff
                                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                                //Play
                                                pb.thirdPersonPlayerModel.soundReload.Play();
                                            }
                                            //Call network
                                            if (pb.isServer) pb.RpcWeaponProceduralReloadNetwork(4);
                                        }
                                    }
                                    else if (data.reloadPhase == 4)
                                    {
                                        //It is over, end reload
                                        data.reloadInProgress = false;
                                        data.reloadPhase = 0;
                                    }
                                    break;
                            }
                        }
                    }

                    //Update aiming
                    if (data.isAiming)
                    {
                        //Increase progress
                        if (aimInTime > 0)
                        {
                            if (data.aimingProgress < 1) data.aimingProgress += Time.deltaTime / aimInTime;
                            //Clamp
                            data.aimingProgress = Mathf.Clamp01(data.aimingProgress);
                        }
                        else
                        {
                            //Instant mode
                            data.aimingProgress = 1f;
                        }
                    }
                    else
                    {
                        //Decrease progress
                        if (aimOutTime > 0)
                        {
                            if (data.aimingProgress > 0) data.aimingProgress -= Time.deltaTime / aimOutTime;
                            //Clamp
                            data.aimingProgress = Mathf.Clamp01(data.aimingProgress);
                        }
                        else
                        {
                            //Instant mode
                            data.aimingProgress = 0;
                        }
                    }

                    if (pb.isFirstPersonActive)
                    {
                        if (data.weaponRenderer.cachedUseFullscreenScope)
                        {
                            if (data.isAimedIn)
                            {
                                //We are aimed in, show scope
                                Kit_IngameMain.instance.hud.DisplaySniperScope(true);
                                //Snap fov
                                Kit_IngameMain.instance.mainCamera.fieldOfView = data.weaponRenderer.cachedAimingFov;
                                //Hide weapon
                                if (!data.sniperWeaponHidden)
                                {
                                    data.sniperWeaponHidden = true;
                                    data.weaponRenderer.visible = false;
                                }
                            }
                            else
                            {
                                //We are not aimed in, hide the scope
                                Kit_IngameMain.instance.hud.DisplaySniperScope(false);
                                //Smoothly fade FoV
                                Kit_IngameMain.instance.mainCamera.fieldOfView = Mathf.Lerp(Kit_GameSettings.baseFov, Kit_GameSettings.baseFov - 5f, data.aimingProgress);
                                //Show weapon
                                if (data.sniperWeaponHidden)
                                {
                                    data.sniperWeaponHidden = false;
                                    data.weaponRenderer.visible = true;
                                }
                            }
                        }
                        else
                        {
                            //Sniper scope is not active, just hide it
                            Kit_IngameMain.instance.hud.DisplaySniperScope(false);
                            //Smoothly fade FoV
                            Kit_IngameMain.instance.mainCamera.fieldOfView = Mathf.Lerp(Kit_GameSettings.baseFov, data.weaponRenderer.cachedAimingFov, data.aimingProgress);
                        }

                        //Update position and rotation
                        data.aimingTransform.localPosition = Vector3.Lerp(Vector3.zero, data.weaponRenderer.cachedAimingPos, data.aimingProgress);
                        data.aimingTransform.localRotation = Quaternion.Slerp(Quaternion.identity, Quaternion.Euler(data.weaponRenderer.cachedAimingRot), data.aimingProgress);
                    }

                    if (data.bulletSpreadMode == SpreadMode.SprayPattern && !data.isFiring)
                    {
                        //Spray pattern recovery
                        if (data.sprayPatternState > 0f)
                        {
                            data.sprayPatternState -= Time.deltaTime * data.bulletSpreadSprayPatternRecoverySpeed;
                        }
                        else
                        {
                            data.sprayPatternState = 0f;
                        }
                    }

                    //Shell ejection
                    if (data.shellEjectEnabled) //Check if shell ejection is enabled
                    {
                        //Check if enough time has passed
                        if (Time.time >= data.shellEjectNext || shellEjectionTime <= 0)
                        {
                            //Set ejection bool
                            data.shellEjectEnabled = false;
                            //Eject shell
                            EjectShell(pb, data);
                        }
                    }

                    //Check for bolt action
                    if (data.boltActionState == 1 || data.boltActionState == 2)
                    {
                        //Check if the time has passed
                        if (Time.time > data.boltActionTime)
                        {
                            if (pb.isFirstPersonActive)
                            {
                                //Set values
                                data.soundOther.loop = false;


                                //Set correct clip
                                if (data.boltActionState == 1)
                                {
                                    data.soundOther.clip = boltActionSoundNormal;
                                }
                                else
                                {
                                    data.soundOther.clip = boltActionSoundLast;
                                }

                                //Play
                                data.soundOther.Play();
                            }

                            //Set back to 0
                            data.boltActionState = 0;
                        }
                    }

                    if (pb.isFirstPersonActive)
                    {
                        //Update HUD
                        Kit_IngameMain.instance.hud.DisplayAmmo(data.bulletsLeft, data.bulletsLeftToReload);
                        Kit_IngameMain.instance.hud.DisplayCrosshair(GetCrosshairSize(pb, data), pb.looking.GetPerspective(pb) == Kit_GameInformation.Perspective.ThirdPerson);
                    }
                }
            }

            public override void PredictionInput(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData, Kit_PlayerInput input, float delta)
            {

            }

            public override void CalculateWeaponUpdate(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                if (pb.isServer || pb.isLocalPlayer)
                {

                }
                else
                {
                    //Fire Replica
                    if (data.fireMode == FireMode.Auto)
                    {
                        if (data.isFiring)
                        {
                            //Compare with fire rate
                            if (Time.time >= data.lastFire + data.fireRate)
                            {
                                FireOneShot(pb, data, 0, 0, true);
                            }
                        }
                    }
                }
            }

            public override void AnimateWeapon(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData, int id, float speed)
            {
                if (pb.isServer || pb.isOwned)
                {
                    if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                    {
                        Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                        //Recoil
                        //Apply to transform
                        pb.recoilApplyRotation = Quaternion.Slerp(pb.recoilApplyRotation, Quaternion.identity, Time.deltaTime * data.recoilReturnSpeed);
                    }
                }

                if (pb.isFirstPersonActive)
                {
                    if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                    {
                        Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;


                        data.weaponRenderer.WeaponUpdate(this, data);

                        //Camera animation
                        if (data.weaponRenderer.cameraAnimationEnabled)
                        {
                            if (data.weaponRenderer.cameraAnimationType == CameraAnimationType.Copy)
                            {
                                if (data.weaponRenderer.cameraAnimationBone) pb.playerCameraAnimationTransform.localRotation = Quaternion.Euler(data.weaponRenderer.cameraAnimationReferenceRotation) * data.weaponRenderer.cameraAnimationBone.localRotation;
                                else pb.playerCameraAnimationTransform.localRotation = Quaternion.Slerp(pb.playerCameraAnimationTransform.localRotation, Quaternion.identity, Time.deltaTime * 5f);
                            }
                            else if (data.weaponRenderer.cameraAnimationType == CameraAnimationType.LookAt)
                            {
                                if (data.weaponRenderer.cameraAnimationBone && data.weaponRenderer.cameraAnimationTarget) pb.playerCameraAnimationTransform.localRotation = Quaternion.Euler(data.weaponRenderer.cameraAnimationReferenceRotation) * Quaternion.LookRotation(data.weaponRenderer.cameraAnimationTarget.localPosition - data.weaponRenderer.cameraAnimationBone.localPosition);
                                else pb.playerCameraAnimationTransform.localRotation = Quaternion.Slerp(pb.playerCameraAnimationTransform.localRotation, Quaternion.identity, Time.deltaTime * 5f);
                            }
                        }
                        else
                        {
                            //Go back to 0,0,0
                            pb.playerCameraAnimationTransform.localRotation = Quaternion.Slerp(pb.playerCameraAnimationTransform.localRotation, Quaternion.identity, Time.deltaTime * 5f);
                        }

                        //Weapon delay calculation
                        data.weaponDelayLastDifference = data.weaponDelayLastRotation * Quaternion.Inverse(pb.mouseLookObject.rotation);
                        Vector3 differenceEulerAngles = data.weaponDelayLastDifference.eulerAngles;
                        float x = differenceEulerAngles.y;
                        float y = differenceEulerAngles.x;

                        if (x > 180) x -= 360f;
                        if (y > 180) y -= 360f;

                        //Get input from the mouse
                        data.weaponDelayCurrentX = x * weaponDelayBaseAmount * Time.deltaTime;
                        data.weaponDelayCurrentY = -y * weaponDelayBaseAmount * Time.deltaTime;

                        data.weaponDelayLastRotation = pb.mouseLookObject.rotation;

                        //Clamp
                        data.weaponDelayCurrentX = Mathf.Clamp(data.weaponDelayCurrentX, -weaponDelayMaxAmount, weaponDelayMaxAmount);
                        data.weaponDelayCurrentY = Mathf.Clamp(data.weaponDelayCurrentY, -weaponDelayMaxAmount, weaponDelayMaxAmount);

                        //Aiming multiplier
                        if (data.isAiming)
                        {
                            data.weaponDelayCurrentX *= weaponDelayAimingMultiplier;
                            data.weaponDelayCurrentY *= weaponDelayAimingMultiplier;
                        }

                        //Update Vector
                        data.weaponDelayCur.x = data.weaponDelayCurrentX;
                        data.weaponDelayCur.y = data.weaponDelayCurrentY;
                        data.weaponDelayCur.z = 0f;

                        //Smooth move towards the target
                        data.weaponDelayTransform.localPosition = Vector3.Lerp(data.weaponDelayTransform.localPosition, data.weaponDelayCur, Time.deltaTime * weaponDelaySmooth);

                        //Weapon tilt
                        if (weaponTiltEnabled)
                        {
                            if (!weaponTiltEnabledWhileAiming && data.isAiming)
                            {
                                data.weaponDelayTransform.localRotation = Quaternion.Slerp(data.weaponDelayTransform.localRotation, Quaternion.identity, Time.deltaTime * weaponTiltReturnSpeed);
                            }
                            else
                            {
                                data.weaponDelayTransform.localRotation = Quaternion.Slerp(data.weaponDelayTransform.localRotation, Quaternion.Euler(0, 0, -pb.movement.GetMovementDirection(pb).x * weaponTiltIntensity), Time.deltaTime * weaponTiltReturnSpeed);
                            }
                        }
                        else
                        {
                            data.weaponDelayTransform.localRotation = Quaternion.Slerp(data.weaponDelayTransform.localRotation, Quaternion.identity, Time.deltaTime * weaponTiltReturnSpeed);
                        }

                        //Weapon Fall
                        data.weaponFallTransform.localRotation = Quaternion.Slerp(data.weaponFallTransform.localRotation, Quaternion.identity, Time.deltaTime * fallDownReturnSpeed);

                        //Set speed
                        if (id != 0)
                        {
                            data.genericAnimator.SetFloat("speed", speed);
                        }
                        //If idle, set speed to 1
                        else
                        {
                            data.genericAnimator.SetFloat("speed", 1f);
                        }

                        //Run position and rotation
                        //Check state and if we can move (Selected, not reloading)
                        if (id == 2 && data.isSelectedAndReady && !data.reloadInProgress && data.weaponRenderer.useRunPosRot)
                        {
                            //Move to run pos
                            data.weaponRenderer.transform.localPosition = Vector3.Lerp(data.weaponRenderer.transform.localPosition, data.weaponRenderer.runPos, Time.deltaTime * data.weaponRenderer.runSmooth);
                            //Move to run rot
                            data.weaponRenderer.transform.localRotation = Quaternion.Slerp(data.weaponRenderer.transform.localRotation, Quaternion.Euler(data.weaponRenderer.runRot), Time.deltaTime * data.weaponRenderer.runSmooth);
                            //Set time
                            data.lastRun = Time.time;
                        }
                        else
                        {
                            //Move back to idle pos
                            data.weaponRenderer.transform.localPosition = Vector3.Lerp(data.weaponRenderer.transform.localPosition, Vector3.zero, Time.deltaTime * data.weaponRenderer.runSmooth * 2f);
                            //Move back to idle rot
                            data.weaponRenderer.transform.localRotation = Quaternion.Slerp(data.weaponRenderer.transform.localRotation, Quaternion.identity, Time.deltaTime * data.weaponRenderer.runSmooth * 2f);
                        }

                        //Make sure idle anim is playing if no anim is playing
                        if (data.weaponRenderer.legacyAnim && !data.weaponRenderer.legacyAnim.isPlaying && data.isSelectedAndReady)
                        {
                            if (data.bulletsLeft == 0)
                            {
                                data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].wrapMode = WrapMode.Loop;
                                data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idleEmpty, 0.3f, PlayMode.StopAll);
                            }
                            else
                            {
                                data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].wrapMode = WrapMode.Loop;
                                data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idle, 0.3f, PlayMode.StopAll);
                            }
                        }

                        //If we are aiming, force idle animation
                        if (data.isAiming && !enableWalkAnimationWhileAiming)
                        {
                            //Play idle animation
                            data.genericAnimator.CrossFade("Idle", 0.3f);
                            //Also set last id to 0, so it can be updated if we stop aiming
                            data.lastWeaponAnimationID = 0;

                            if (sendRunningEvents)
                            {
                                //End run animation on weapon animator
                                if (data.startedRunAnimation)
                                {
                                    data.startedRunAnimation = false;
                                    if (data.weaponRenderer.anim)
                                    {
                                        data.weaponRenderer.anim.ResetTrigger("Start Run");
                                        data.weaponRenderer.anim.SetTrigger("End Run");

                                        for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                        {
                                            data.weaponRenderer.animAdditionals[i].ResetTrigger("Start Run");
                                            data.weaponRenderer.animAdditionals[i].SetTrigger("End Run");
                                        }
                                    }
                                    else if (data.weaponRenderer.legacyAnim)
                                    {
                                        if (data.bulletsLeft == 0)
                                        {
                                            data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].wrapMode = WrapMode.Loop;
                                            data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                            data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idleEmpty, 0.3f, PlayMode.StopAll);
                                        }
                                        else
                                        {
                                            data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].wrapMode = WrapMode.Loop;
                                            data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                            data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idle, 0.3f, PlayMode.StopAll);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            //Check if state changed
                            if (id != data.lastWeaponAnimationID)
                            {
                                //Idle
                                if (id == 0)
                                {
                                    //Play idle animation
                                    data.genericAnimator.CrossFade("Idle", 0.3f);

                                    if (sendRunningEvents)
                                    {
                                        //End run animation on weapon animator
                                        if (data.startedRunAnimation)
                                        {
                                            data.startedRunAnimation = false;
                                            if (data.weaponRenderer.anim)
                                            {
                                                data.weaponRenderer.anim.ResetTrigger("Start Run");
                                                data.weaponRenderer.anim.SetTrigger("End Run");

                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                {
                                                    data.weaponRenderer.animAdditionals[i].ResetTrigger("Start Run");
                                                    data.weaponRenderer.animAdditionals[i].SetTrigger("End Run");
                                                }
                                            }
                                            else if (data.weaponRenderer.legacyAnim)
                                            {
                                                if (data.bulletsLeft == 0)
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idleEmpty, 0.3f, PlayMode.StopAll);
                                                }
                                                else
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idle, 0.3f, PlayMode.StopAll);
                                                }
                                            }
                                        }
                                    }
                                }
                                //Walk
                                else if (id == 1 && (!data.isAiming || enableWalkAnimationWhileAiming))
                                {
                                    //Check if we should use generic anim
                                    if (useGenericWalkAnim)
                                    {
                                        //Play run animation
                                        data.genericAnimator.CrossFade("Walk", 0.2f);
                                    }
                                    //If not continue to play Idle
                                    else
                                    {
                                        //Play idle animation
                                        data.genericAnimator.CrossFade("Idle", 0.3f);
                                    }

                                    if (sendRunningEvents)
                                    {
                                        //End run animation on weapon animator
                                        if (data.startedRunAnimation)
                                        {
                                            data.startedRunAnimation = false;
                                            if (data.weaponRenderer.anim)
                                            {
                                                data.weaponRenderer.anim.ResetTrigger("Start Run");
                                                data.weaponRenderer.anim.SetTrigger("End Run");

                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                {
                                                    data.weaponRenderer.animAdditionals[i].ResetTrigger("Start Run");
                                                    data.weaponRenderer.animAdditionals[i].SetTrigger("End Run");
                                                }
                                            }
                                            else if (data.weaponRenderer.legacyAnim)
                                            {
                                                if (data.bulletsLeft == 0)
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idleEmpty, 0.3f, PlayMode.StopAll);
                                                }
                                                else
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idle, 0.3f, PlayMode.StopAll);
                                                }
                                            }
                                        }
                                    }
                                }
                                //Run
                                else if (id == 2 && (!data.isAiming || enableWalkAnimationWhileAiming))
                                {
                                    //Check if we should use generic anim
                                    if (useGenericRunAnim)
                                    {
                                        //Play run animation
                                        data.genericAnimator.CrossFade("Run", 0.2f);
                                    }
                                    //If not continue to play Idle
                                    else if (sendRunningEvents)
                                    {
                                        //Play idle animation
                                        data.genericAnimator.CrossFade("Idle", 0.3f);
                                        //Start run animation on weapon animator
                                        if (!data.startedRunAnimation && !data.reloadInProgress && data.isSelectedAndReady)
                                        {
                                            data.startedRunAnimation = true;
                                            if (data.weaponRenderer.anim)
                                            {
                                                data.weaponRenderer.anim.ResetTrigger("End Run");
                                                data.weaponRenderer.anim.SetTrigger("Start Run");

                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                {
                                                    data.weaponRenderer.animAdditionals[i].ResetTrigger("End Run");
                                                    data.weaponRenderer.animAdditionals[i].SetTrigger("Start Run");
                                                }
                                            }
                                            else if (data.weaponRenderer.legacyAnim)
                                            {
                                                if (data.bulletsLeft == 0)
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.runEmpty].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.runEmpty, 0.3f, PlayMode.StopAll);
                                                }
                                                else
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.run].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.run, 0.3f, PlayMode.StopAll);
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //End run animation on weapon animator
                                    if (data.startedRunAnimation)
                                    {
                                        data.startedRunAnimation = false;
                                        if (data.weaponRenderer.anim)
                                        {
                                            data.weaponRenderer.anim.ResetTrigger("Start Run");
                                            data.weaponRenderer.anim.SetTrigger("End Run");

                                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                            {
                                                data.weaponRenderer.animAdditionals[i].ResetTrigger("Start Run");
                                                data.weaponRenderer.animAdditionals[i].SetTrigger("End Run");
                                            }
                                        }
                                        else if (data.weaponRenderer.legacyAnim)
                                        {
                                            if (data.bulletsLeft == 0)
                                            {
                                                data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].wrapMode = WrapMode.Loop;
                                                data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idleEmpty, 0.3f, PlayMode.StopAll);
                                            }
                                            else
                                            {
                                                data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].wrapMode = WrapMode.Loop;
                                                data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idle, 0.3f, PlayMode.StopAll);
                                            }
                                        }
                                    }
                                }
                                //Update last state
                                data.lastWeaponAnimationID = id;
                            }
                            else
                            {
                                if (sendRunningEvents)
                                {
                                    //Idle
                                    if (id == 0)
                                    {
                                        //End run animation on weapon animator
                                        if (data.startedRunAnimation)
                                        {
                                            data.startedRunAnimation = false;
                                            if (data.weaponRenderer.anim)
                                            {
                                                data.weaponRenderer.anim.ResetTrigger("Start Run");
                                                data.weaponRenderer.anim.SetTrigger("End Run");

                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                {
                                                    data.weaponRenderer.animAdditionals[i].ResetTrigger("Start Run");
                                                    data.weaponRenderer.animAdditionals[i].SetTrigger("End Run");
                                                }
                                            }
                                            else if (data.weaponRenderer.legacyAnim)
                                            {
                                                if (data.bulletsLeft == 0)
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idleEmpty, 0.3f, PlayMode.StopAll);
                                                }
                                                else
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idle, 0.3f, PlayMode.StopAll);
                                                }
                                            }
                                        }
                                    }
                                    //Walk
                                    else if (id == 1 && (!data.isAiming || enableWalkAnimationWhileAiming))
                                    {
                                        //End run animation on weapon animator
                                        if (data.startedRunAnimation)
                                        {
                                            data.startedRunAnimation = false;
                                            if (data.weaponRenderer.anim)
                                            {
                                                data.weaponRenderer.anim.ResetTrigger("Start Run");
                                                data.weaponRenderer.anim.SetTrigger("End Run");

                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                {
                                                    data.weaponRenderer.animAdditionals[i].ResetTrigger("Start Run");
                                                    data.weaponRenderer.animAdditionals[i].SetTrigger("End Run");
                                                }
                                            }
                                            else if (data.weaponRenderer.legacyAnim)
                                            {
                                                if (data.bulletsLeft == 0)
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idleEmpty, 0.3f, PlayMode.StopAll);
                                                }
                                                else
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idle, 0.3f, PlayMode.StopAll);
                                                }
                                            }
                                        }
                                    }
                                    //Run
                                    else if (id == 2 && !data.isAiming)
                                    {
                                        //Start run animation on weapon animator
                                        if (!data.startedRunAnimation && !data.reloadInProgress && data.isSelectedAndReady)
                                        {
                                            data.startedRunAnimation = true;
                                            if (data.weaponRenderer.anim)
                                            {
                                                data.weaponRenderer.anim.ResetTrigger("End Run");
                                                data.weaponRenderer.anim.SetTrigger("Start Run");

                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                {
                                                    data.weaponRenderer.animAdditionals[i].ResetTrigger("End Run");
                                                    data.weaponRenderer.animAdditionals[i].SetTrigger("Start Run");
                                                }
                                            }
                                            else if (data.weaponRenderer.legacyAnim)
                                            {
                                                if (data.bulletsLeft == 0)
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.runEmpty].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.runEmpty, 0.3f, PlayMode.StopAll);
                                                }
                                                else
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.run].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.run, 0.3f, PlayMode.StopAll);
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //End run animation on weapon animator
                                        if (data.startedRunAnimation)
                                        {
                                            data.startedRunAnimation = false;
                                            if (data.weaponRenderer.anim)
                                            {
                                                data.weaponRenderer.anim.ResetTrigger("Start Run");
                                                data.weaponRenderer.anim.SetTrigger("End Run");

                                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                                {
                                                    data.weaponRenderer.animAdditionals[i].ResetTrigger("Start Run");
                                                    data.weaponRenderer.animAdditionals[i].SetTrigger("End Run");
                                                }
                                            }
                                            else if (data.weaponRenderer.legacyAnim)
                                            {
                                                if (data.bulletsLeft == 0)
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idleEmpty].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idleEmpty, 0.3f, PlayMode.StopAll);
                                                }
                                                else
                                                {
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].wrapMode = WrapMode.Loop;
                                                    data.weaponRenderer.legacyAnim[data.weaponRenderer.legacyAnimData.idle].speed = data.weaponRenderer.legacyAnimData.idleAnimationSpeed;
                                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.idle, 0.3f, PlayMode.StopAll);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (setRunningBool && pb.isFirstPersonActive && data.weaponRenderer.anim)
                        {
                            //Set empty bool 
                            data.weaponRenderer.anim.SetBool("running", id == 2 && !data.reloadInProgress);

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].SetBool("running", id == 2 && !data.reloadInProgress);
                            }
                        }

                        if (setAimingProgress && pb.isFirstPersonActive && data.weaponRenderer.anim)
                        {
                            //Set empty bool
                            data.weaponRenderer.anim.SetFloat("aimingProgress", data.aimingProgress);

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].SetFloat("aimingProgress", data.aimingProgress);
                            }
                        }

                        if (setAimingBool && pb.isFirstPersonActive && data.weaponRenderer.anim)
                        {
                            //Set empty bool
                            data.weaponRenderer.anim.SetBool("aiming", data.isAiming);

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].SetBool("aiming", data.isAiming);
                            }
                        }

                        if (setMovementDirection && pb.isFirstPersonActive && data.weaponRenderer.anim)
                        {
                            Vector3 dir = pb.movement.GetMovementDirection(pb);
                            //Set empty bool
                            data.weaponRenderer.anim.SetFloat("ver", dir.z, 0.1f, Time.deltaTime);
                            data.weaponRenderer.anim.SetFloat("hor", dir.x, 0.1f, Time.deltaTime);
                            data.weaponRenderer.anim.SetFloat("walkSpeed", pb.movement.GetVelocity(pb).magnitude);

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].SetFloat("ver", dir.z, 0.1f, Time.deltaTime);
                                data.weaponRenderer.animAdditionals[i].SetFloat("hor", dir.x, 0.1f, Time.deltaTime);
                                data.weaponRenderer.animAdditionals[i].SetFloat("walkSpeed", pb.movement.GetVelocity(pb).magnitude);
                            }
                        }
                    }
                }
            }

            public override void FallDownEffect(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData, bool wasFallDamageApplied)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;
                    if (wasFallDamageApplied)
                    {
                        Kit_ScriptableObjectCoroutineHelper.instance.StartCoroutine(Kit_ScriptableObjectCoroutineHelper.instance.Kick(data.weaponFallTransform, new Vector3(fallDownAmount, Random.Range(fallDownMinOffset, fallDownMaxoffset), 0), fallDownTime));
                    }
                    else
                    {
                        Kit_ScriptableObjectCoroutineHelper.instance.StartCoroutine(Kit_ScriptableObjectCoroutineHelper.instance.Kick(data.weaponFallTransform, new Vector3(fallDownAmount / 3, Random.Range(fallDownMinOffset, fallDownMaxoffset) / 2, 0), fallDownTime));
                    }
                }
            }

            public override void DrawWeapon(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    //Reset firing
                    data.isFiring = false;
                    //Set selected
                    data.isSelected = true;
                    if (pb.isFirstPersonActive)
                    {
                        //Reset pos & rot of the renderer
                        data.weaponRenderer.transform.localPosition = Vector3.zero;
                        data.weaponRenderer.transform.localRotation = Quaternion.identity;
                        //Reset fov
                        Kit_IngameMain.instance.mainCamera.fieldOfView = Kit_GameSettings.baseFov;
                        //Reset delay
                        data.weaponDelayCur = Vector3.zero;
                        //Call renderer
                        data.weaponRenderer.WeaponDraw();
                    }
                    //Reset aiming
                    data.aimingProgress = 0f;
                    if (pb.isFirstPersonActive)
                    {
                        data.aimingTransform.localPosition = Vector3.zero;
                        data.aimingTransform.localRotation = Quaternion.identity;
                    }
                    data.isAiming = false;
                    //Set default values
                    data.reloadInProgress = false;
                    //Reset spray pattern
                    data.sprayPatternState = 0f;
                    if (pb.isFirstPersonActive)
                    {
                        //Enable anim
                        if (data.weaponRenderer.anim)
                        {
                            //Disable anim
                            data.weaponRenderer.anim.enabled = true;
                            //Play animation
                            data.weaponRenderer.anim.Play("Draw", data.weaponRenderer.animActionLayer, 0f);

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].enabled = true;
                                data.weaponRenderer.animAdditionals[i].Play("Draw", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                            }

                            if (setEmptyBool)
                            {
                                //Set empty bool
                                data.weaponRenderer.anim.SetBool("empty", data.bulletsLeft == 0);

                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                {
                                    data.weaponRenderer.animAdditionals[i].SetBool("empty", data.bulletsLeft == 0);
                                }
                            }
                        }
                        else if (data.weaponRenderer.legacyAnim)
                        {
                            data.weaponRenderer.legacyAnim.enabled = true;
                            if (data.bulletsLeft == 0)
                            {
                                //Play animation
                                data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.drawEmpty, PlayMode.StopAll);
                            }
                            else
                            {
                                //Play animation
                                data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.draw, PlayMode.StopAll);
                            }
                        }
                        //Reset shell ejection
                        data.shellEjectEnabled = false;
                        data.shellEjectNext = 0f;
                    }
                    //Reset bolt
                    data.boltActionState = 0;
                    data.boltActionTime = 0f;
                    if (pb.isFirstPersonActive)
                    {
                        //Play sound if it is assigned
                        if (drawSound) data.soundOther.PlayOneShot(drawSound);
                        if (pb.looking.GetPerspective(pb) == Kit_GameInformation.Perspective.FirstPerson)
                        {
                            //Show weapon
                            data.weaponRenderer.visible = true;
                        }
                        else
                        {
                            data.weaponRenderer.visible = false;
                        }
                    }
                    if (pb.looking.GetPerspective(pb) == Kit_GameInformation.Perspective.FirstPerson && pb.isFirstPersonActive)
                    {
                        //Show tp weapon and hide
                        data.tpWeaponRenderer.visible = true;
                        data.tpWeaponRenderer.shadowsOnly = true;
                    }
                    else
                    {
                        //Show tp weapon and show
                        data.tpWeaponRenderer.visible = true;
                        data.tpWeaponRenderer.shadowsOnly = false;
                    }
                    //Make sure it is not ready yet
                    data.isSelectedAndReady = false;
                    //Reset run animation
                    data.startedRunAnimation = false;
                    //Set third person anim type
                    pb.thirdPersonPlayerModel.SetAnimType(thirdPersonAnimType);
                    //Stop third person anims
                    pb.thirdPersonPlayerModel.AbortWeaponAnimations();
                }
            }

            public override void PutawayWeapon(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    //Reset firing
                    data.isFiring = false;
                    //Reset aiming
                    data.aimingProgress = 0f;
                    //Reset reload
                    data.reloadInProgress = false;
                    if (pb.isFirstPersonActive)
                    {
                        data.aimingTransform.localPosition = Vector3.zero;
                        data.aimingTransform.localRotation = Quaternion.identity;
                        //Call renderer
                        data.weaponRenderer.WeaponPutaway();
                    }
                    data.isAiming = false;
                    if (pb.isFirstPersonActive)
                    {
                        //Check if we need to hide scope
                        if (data.weaponRenderer.cachedUseFullscreenScope)
                        {
                            //Hide
                            Kit_IngameMain.instance.hud.DisplaySniperScope(false);
                        }
                        //Reset fov
                        Kit_IngameMain.instance.mainCamera.fieldOfView = Kit_GameSettings.baseFov;
                        //Enable anim
                        if (data.weaponRenderer.anim)
                        {
                            //Disable anim
                            data.weaponRenderer.anim.enabled = true;

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].enabled = true;
                            }
                        }
                        else if (data.weaponRenderer.legacyAnim)
                        {
                            data.weaponRenderer.legacyAnim.enabled = true;
                        }
                        if (setEmptyBool)
                        {
                            //Set empty bool
                            data.weaponRenderer.anim.SetBool("empty", data.bulletsLeft == 0);

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].SetBool("empty", data.bulletsLeft == 0);
                            }
                        }
                        //Play animation
                        if (data.weaponRenderer.anim)
                        {
                            //Play animation
                            data.weaponRenderer.anim.Play("Putaway", data.weaponRenderer.animActionLayer, 0f);

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].Play("Putaway", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                            }
                        }
                        else if (data.weaponRenderer.legacyAnim)
                        {
                            //Play animation
                            if (data.bulletsLeft == 0)
                            {
                                data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.putawayEmpty, PlayMode.StopAll);
                            }
                            else
                            {
                                data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.putaway, PlayMode.StopAll);
                            }
                        }
                        //Stop reload sound
                        data.soundReload.Stop();
                        //Play sound if it is assigned
                        if (putawaySound) data.soundOther.PlayOneShot(putawaySound);
                        if (pb.looking.GetPerspective(pb) == Kit_GameInformation.Perspective.FirstPerson)
                        {
                            //Show weapon
                            data.weaponRenderer.visible = true;
                        }
                        else
                        {
                            //Hide
                            data.weaponRenderer.visible = false;
                        }
                    }
                    if (pb.looking.GetPerspective(pb) == Kit_GameInformation.Perspective.FirstPerson && pb.isFirstPersonActive)
                    {
                        //Show tp weapon
                        data.tpWeaponRenderer.visible = true;
                        data.tpWeaponRenderer.shadowsOnly = true;
                    }
                    else
                    {
                        data.tpWeaponRenderer.visible = true;
                        data.tpWeaponRenderer.shadowsOnly = false;
                    }
                    //Make sure it is not ready yet
                    data.isSelectedAndReady = false;
                    //Stop third person anims
                    pb.thirdPersonPlayerModel.AbortWeaponAnimations();
                }
            }

            public override void PutawayWeaponHide(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    //Set selected
                    data.isSelected = false;
                    //Reset run animation
                    data.startedRunAnimation = false;
                    //Reset firing
                    data.isFiring = false;
                    //Reset aiming
                    data.aimingProgress = 0f;
                    if (pb.isFirstPersonActive)
                    {
                        data.aimingTransform.localPosition = Vector3.zero;
                        data.aimingTransform.localRotation = Quaternion.identity;
                        //Call renderer
                        data.weaponRenderer.WeaponPutawayHide();
                    }
                    data.isAiming = false;
                    if (pb.isFirstPersonActive)
                    {
                        //Check if we need to hide scope
                        if (data.weaponRenderer.cachedUseFullscreenScope)
                        {
                            //Hide
                            Kit_IngameMain.instance.hud.DisplaySniperScope(false);
                        }
                        //Reset fov
                        Kit_IngameMain.instance.mainCamera.fieldOfView = Kit_GameSettings.baseFov;
                        //Hide weapon
                        data.weaponRenderer.visible = false;
                        if (data.weaponRenderer.anim)
                        {
                            //Disable anim
                            data.weaponRenderer.anim.enabled = false;

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].enabled = false;
                            }
                        }
                        else if (data.weaponRenderer.legacyAnim)
                        {
                            data.weaponRenderer.legacyAnim.enabled = false;
                        }
                        //Reset pos & rot of the renderer
                        data.weaponRenderer.transform.localPosition = Vector3.zero;
                        data.weaponRenderer.transform.localRotation = Quaternion.identity;
                        //Reset delay
                        data.weaponDelayCur = Vector3.zero;
                    }
                    //Hide tp weapon
                    data.tpWeaponRenderer.visible = false;
                    //Make sure it is not ready
                    data.isSelectedAndReady = false;
                    //Stop third person anims
                    pb.thirdPersonPlayerModel.AbortWeaponAnimations();
                }
            }

            public override void QuickUseOnOtherWeaponBegin(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    if (pb.isFirstPersonActive)
                    {
                        data.soundReload.Stop();
                        data.soundOther.Stop();
                    }

                    pb.thirdPersonPlayerModel.soundReload.Stop();
                    pb.thirdPersonPlayerModel.soundOther.Stop();
                }
            }

            public override void NetworkSemiRPCReceived(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (!pb.isLocalPlayer && !pb.isServer)
                {
                    if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                    {
                        Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;
                        FireOneShot(pb, data, 0, 0, true);
                    }
                }
            }

            public override void NetworkBoltActionRPCReceived(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData, int state)
            {
                if (!pb.isLocalPlayer && !pb.isServer)
                {
                    if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                    {
                        Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;
                        FireOneShot(pb, data, 0, 0, true);
                    }
                }
            }

            public override void NetworkBurstRPCReceived(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData, int burstLength)
            {
                if (!pb.isLocalPlayer && !pb.isServer)
                {
                    if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                    {
                        Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;
                        FireBurst(pb, data, 0, 0, true);
                    }
                }
            }

            public override void NetworkReloadRPCReceived(Kit_PlayerBehaviour pb, bool isEmpty, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (!pb.isLocalPlayer && !pb.isServer)
                {
                    if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                    {
                        Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                        //Play third person reload animation
                        pb.thirdPersonPlayerModel.PlayWeaponReloadAnimation(thirdPersonAnimType, isEmpty ? 1 : 0);
                        //Play reload sound
                        if (isEmpty)
                        {
                            if (pb.isFirstPersonActive)
                            {
                                //Set clip
                                data.soundReload.clip = reloadSoundEmpty;
                                //Play
                                data.soundReload.Play();

                                if (data.weaponRenderer.anim)
                                {
                                    //Play animation
                                    data.weaponRenderer.anim.Play("Reload Empty", data.weaponRenderer.animActionLayer, 0f);

                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                    {
                                        data.weaponRenderer.animAdditionals[i].Play("Reload Empty", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                    }
                                }
                                else if (data.weaponRenderer.legacyAnim)
                                {
                                    //Play animation
                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reloadEmpty, 0.15f, PlayMode.StopAll);
                                }
                            }
                            else
                            {
                                //Set clip
                                pb.thirdPersonPlayerModel.soundReload.clip = reloadSoundEmpty;
                                //Set distance
                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                //Set rolloff
                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                //Play
                                pb.thirdPersonPlayerModel.soundReload.Play();
                            }
                        }
                        else
                        {
                            if (pb.isFirstPersonActive)
                            {
                                //Set clip
                                data.soundReload.clip = reloadSound;
                                //Play
                                data.soundReload.Play();

                                if (data.weaponRenderer.anim)
                                {
                                    //Play animation
                                    data.weaponRenderer.anim.Play("Reload Full", data.weaponRenderer.animActionLayer, 0f);

                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                    {
                                        data.weaponRenderer.animAdditionals[i].Play("Reload Full", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                    }
                                }
                                else if (data.weaponRenderer.legacyAnim)
                                {
                                    //Play animation
                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reload, 0.15f, PlayMode.StopAll);
                                }
                            }
                            else
                            {
                                //Set clip
                                pb.thirdPersonPlayerModel.soundReload.clip = reloadSound;
                                //Set distance
                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                //Set rolloff
                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                //Play
                                pb.thirdPersonPlayerModel.soundReload.Play();
                            }
                        }
                    }
                }
            }

            public override void NetworkProceduralReloadRPCReceived(Kit_PlayerBehaviour pb, int stage, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (!pb.isLocalPlayer && !pb.isServer)
                {
                    if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                    {
                        Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                        //Play sounds
                        //0 = Start
                        if (stage == 0)
                        {
                            if (pb.isFirstPersonActive)
                            {
                                if (data.weaponRenderer.anim)
                                {
                                    //Play animation
                                    data.weaponRenderer.anim.Play("Reload Procedural Start", data.weaponRenderer.animActionLayer, 0f);

                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                    {
                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Start", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                    }
                                }
                                else if (data.weaponRenderer.legacyAnim)
                                {
                                    //Play animation
                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reloadProceduralStart, 0.15f, PlayMode.StopAll);
                                }
                                //Play sound
                                data.soundReload.PlayOneShot(reloadProceduralStartSound);
                            }
                            else
                            {
                                //Set clip
                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralStartSound;
                                //Set distance
                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                //Set rolloff
                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                //Play
                                pb.thirdPersonPlayerModel.soundReload.Play();
                            }
                        }
                        else if (stage == 1)
                        {
                            if (pb.isFirstPersonActive)
                            {
                                if (data.weaponRenderer.anim)
                                {
                                    //Play animation
                                    data.weaponRenderer.anim.Play("Reload Procedural Start Empty", data.weaponRenderer.animActionLayer, 0f);

                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                    {
                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Start Empty", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                    }
                                }
                                else if (data.weaponRenderer.legacyAnim)
                                {
                                    //Play animation
                                    data.weaponRenderer.legacyAnim.CrossFade(data.weaponRenderer.legacyAnimData.reloadProceduralStartEmpty, 0.15f, PlayMode.StopAll);
                                }
                                //Play sound
                                data.soundReload.PlayOneShot(reloadProceduralStartEmptySound);
                            }
                            else
                            {
                                //Set clip
                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralStartEmptySound;
                                //Set distance
                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                //Set rolloff
                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                //Play
                                pb.thirdPersonPlayerModel.soundReload.Play();
                            }
                        }
                        else if (stage == 2)
                        {
                            if (pb.isFirstPersonActive)
                            {
                                //Play animation
                                if (data.weaponRenderer.anim)
                                {
                                    //Play animation
                                    data.weaponRenderer.anim.Play("Reload Procedural Insert", data.weaponRenderer.animActionLayer, 0f);

                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                    {
                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural Insert", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                    }
                                }
                                else if (data.weaponRenderer.legacyAnim)
                                {
                                    //Play animation
                                    data.weaponRenderer.legacyAnim.Rewind(data.weaponRenderer.legacyAnimData.reloadProceduralInsert);
                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralInsert, PlayMode.StopAll);
                                }
                                //Play sound
                                data.soundReload.PlayOneShot(reloadProceduralInsertSound);
                            }
                            else
                            {
                                //Set clip
                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralInsertSound;
                                //Set distance
                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                //Set rolloff
                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                //Play
                                pb.thirdPersonPlayerModel.soundReload.Play();
                            }
                        }
                        else if (stage == 4)
                        {
                            if (pb.isFirstPersonActive)
                            {
                                //Play animation
                                if (data.weaponRenderer.anim)
                                {
                                    //Play animation
                                    data.weaponRenderer.anim.Play("Reload Procedural End", data.weaponRenderer.animActionLayer, 0f);

                                    for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                    {
                                        data.weaponRenderer.animAdditionals[i].Play("Reload Procedural End", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                    }
                                }
                                else if (data.weaponRenderer.legacyAnim)
                                {
                                    //Play animation
                                    data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.reloadProceduralEnd, PlayMode.StopAll);
                                }
                                //Play sound
                                data.soundReload.PlayOneShot(reloadProceduralEndSound);
                            }
                            else
                            {
                                //Set clip
                                pb.thirdPersonPlayerModel.soundReload.clip = reloadProceduralEndSound;
                                //Set distance
                                pb.thirdPersonPlayerModel.soundReload.maxDistance = reloadSoundThirdPersonMaxRange;
                                //Set rolloff
                                pb.thirdPersonPlayerModel.soundReload.SetCustomCurve(AudioSourceCurveType.CustomRolloff, reloadSoundThirdPersonRolloff);
                                //Play
                                pb.thirdPersonPlayerModel.soundReload.Play();
                            }
                        }
                    }
                }
            }

            public override WeaponIKValues GetIK(Kit_PlayerBehaviour pb, Animator anim, Kit_WeaponRuntimeDataBase runtimeData)
            {
                WeaponIKValues toReturn = new WeaponIKValues();
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    if (data.tpWeaponRenderer.leftHandIK.Length > 0)
                    {
                        toReturn.leftHandIK = data.tpWeaponRenderer.leftHandIK[Mathf.Clamp(pb.thirdPersonPlayerModel.inverseKinematicID, 0, data.tpWeaponRenderer.leftHandIK.Length - 1)];

                        //Check if third person reload animation is being played
                        if (anim.GetCurrentAnimatorStateInfo(1).IsName(thirdPersonAnimType + " Reload") || anim.GetCurrentAnimatorStateInfo(1).IsName(thirdPersonAnimType + " Reload Empty"))
                        {
                            toReturn.canUseIK = false;
                        }
                        else
                        {
                            toReturn.canUseIK = true;
                        }
                    }
                    else
                    {
                        //Can't use ik if none is assigned
                        toReturn.canUseIK = false;
                    }
                }
                return toReturn;
            }

            public override WeaponStats GetStats()
            {
                WeaponStats toReturn = new WeaponStats();
                //Set damage
                toReturn.damage = baseDamage;
                //Set Fire Rate
                toReturn.fireRate = RPM;
                //Set reach
                toReturn.reach = range;
                //Set recoil
                toReturn.recoil = ((Mathf.Abs(recoilPerShotMax.x) + Mathf.Abs(recoilPerShotMax.y) + Mathf.Abs(recoilPerShotMin.x) + Mathf.Abs(recoilPerShotMax.y)) / (float)recoilReturnSpeed);
                return toReturn;
            }

            public override float Sensitivity(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (pb.isBot) return 1f;

                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    if (data.isAimedIn)
                    {
                        if (data.weaponRenderer.cachedUseFullscreenScope)
                        {
                            return Kit_GameSettings.fullScreenAimSensitivity;
                        }
                        else
                        {
                            return Kit_GameSettings.aimSensitivity;
                        }
                    }
                    else
                    {
                        return Kit_GameSettings.hipSensitivity;
                    }
                }
                return 1f;

            }

            public override int WeaponState(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    if (data.bulletsLeft > 0) return 0;
                    else if (data.bulletsLeftToReload > 0) return 1;
                    else return 2;
                }
                return 0;
            }

            public override int GetWeaponType(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    if (data.fireMode == FireMode.Auto)
                    {
                        return 0;
                    }
                    else if (data.fireMode == FireMode.Semi)
                    {
                        if (data.fireTypeMode == FireTypeMode.Simple) return 1;
                        else return 2;
                    }
                    else if (data.fireMode == FireMode.BoltAction)
                    {
                        if (data.fireTypeMode == FireTypeMode.Simple) return 1;
                        else return 2;
                    }
                }
                return 1;
            }

            public override void FirstThirdPersonChanged(Kit_PlayerBehaviour pb, Kit_GameInformation.Perspective perspective, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    //Get runtime data
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    //Activate or deactivate based on bool
                    if (perspective == Kit_GameInformation.Perspective.ThirdPerson)
                    {
                        if (data.weaponRenderer)
                        {
                            data.weaponRenderer.visible = false;
                        }
                        if (data.tpWeaponRenderer)
                        {
                            data.tpWeaponRenderer.visible = true;
                            data.tpWeaponRenderer.shadowsOnly = false;
                        }
                    }
                    else
                    {
                        if (data.weaponRenderer && !data.sniperWeaponHidden)
                        {
                            data.weaponRenderer.visible = true;
                        }
                        if (data.tpWeaponRenderer)
                        {
                            data.tpWeaponRenderer.visible = true;
                            data.tpWeaponRenderer.shadowsOnly = true;
                        }
                    }
                }
            }
            #endregion

            #region Unique functions
            /// <summary>
            /// Fires one shot locally
            /// </summary>
            /// <param name="pb"></param>
            /// <param name="data"></param>
            public void FireOneShot(Kit_PlayerBehaviour pb, Kit_ModernWeaponScriptRuntimeData data, float delta, float revertBy, bool rpc)
            {
                //Update spawn protection
                if (pb.spawnProtection)
                {
                    pb.spawnProtection.GunFired(pb);
                }

                if (pb.isServer && !rpc)
                {
                    //Call network (if semi fire)
                    if (data.fireMode == FireMode.Semi)
                    {
                        if (pb.isServer) pb.RpcWeaponSemiFireNetwork();
                    }
                    else if (data.fireMode == FireMode.BoltAction)
                    {
                        if (pb.isServer) pb.RpcWeaponBoltActionFireNetwork((data.bulletsLeft == 1 ? 2 : 1));//2 = Last, 1 = Normal; 0 would be none
                    }
                }

                //Set bolt action data
                if (data.fireMode == FireMode.BoltAction)
                {
                    if (data.bulletsLeft == 1)
                    {
                        //Set delay
                        data.boltActionTime = Time.time + boltActionDelayLast;
                        //Set state
                        data.boltActionState = 2;
                        //Set fire rate
                        data.lastFire = Time.time + boltActionTimeLast;
                    }
                    else
                    {
                        //Set delay
                        data.boltActionTime = Time.time + boltActionDelayNormal;
                        //Set state
                        data.boltActionState = 1;
                        //Set fire rate
                        data.lastFire = Time.time + boltActionTimeNormal;
                    }
                }
                else
                {
                    //Set firerate
                    data.lastFire = Time.time;
                }

                if (pb.isFirstPersonActive && pb.looking.GetPerspective(pb) == Kit_GameInformation.Perspective.FirstPerson)
                {
                    //Play sound
                    data.soundFire.PlayOneShot(data.weaponRenderer.cachedFireSound);
                    //Play fire animation
                    if (data.bulletsLeft == 1)
                    {
                        //Last fire
                        if (data.weaponRenderer.anim)
                        {
                            //Play animation
                            data.weaponRenderer.anim.Play("Fire Last", data.weaponRenderer.animActionLayer, 0f);

                            for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                            {
                                data.weaponRenderer.animAdditionals[i].Play("Fire Last", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                            }
                        }
                        else if (data.weaponRenderer.legacyAnim)
                        {
                            //Play animation
                            data.weaponRenderer.legacyAnim.Rewind(data.weaponRenderer.legacyAnimData.fireLast);
                            data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.fireLast, PlayMode.StopAll);
                        }
                    }
                    else
                    {
                        if (data.isAiming)
                        {
                            //Normal fire (in aiming mode)
                            if (data.weaponRenderer.anim)
                            {
                                //Play animation
                                data.weaponRenderer.anim.Play("Fire Aim", data.weaponRenderer.animActionLayer, 0f);

                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                {
                                    data.weaponRenderer.animAdditionals[i].Play("Fire Aim", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                }
                            }
                            else if (data.weaponRenderer.legacyAnim)
                            {
                                //Play animation
                                data.weaponRenderer.legacyAnim.Rewind(data.weaponRenderer.legacyAnimData.fireAim);
                                data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.fireAim, PlayMode.StopAll);
                            }
                        }
                        else
                        {
                            //Normal fire
                            if (data.weaponRenderer.anim)
                            {
                                //Play animation
                                data.weaponRenderer.anim.Play("Fire", data.weaponRenderer.animActionLayer, 0f);

                                for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                                {
                                    data.weaponRenderer.animAdditionals[i].Play("Fire", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                                }
                            }
                            else if (data.weaponRenderer.legacyAnim)
                            {
                                //Play animation
                                data.weaponRenderer.legacyAnim.Rewind(data.weaponRenderer.legacyAnimData.fire);
                                data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.fire, PlayMode.StopAll);
                            }
                        }
                    }

                    //Play Muzzle Flash Particle System, if assigned
                    if (data.weaponRenderer.muzzleFlash && data.weaponRenderer.cachedMuzzleFlashEnabled)
                    {
                        data.weaponRenderer.muzzleFlash.Play(true);
                    }
                }
                else
                {
                    //Set clip
                    pb.thirdPersonPlayerModel.soundFire.clip = data.tpWeaponRenderer.cachedFireSoundThirdPerson;
                    //Update range
                    pb.thirdPersonPlayerModel.soundFire.maxDistance = data.tpWeaponRenderer.cachedFireSoundThirdPersonMaxRange;
                    //Update sound rolloff
                    pb.thirdPersonPlayerModel.soundFire.SetCustomCurve(AudioSourceCurveType.CustomRolloff, data.tpWeaponRenderer.cachedFireSoundThirdPersonRolloff);
                    //Play
                    pb.thirdPersonPlayerModel.soundFire.PlayOneShot(data.tpWeaponRenderer.cachedFireSoundThirdPerson);

                    //Play Muzzle Flash Particle System, if assigned
                    if (data.tpWeaponRenderer.muzzleFlash && data.tpWeaponRenderer.cachedMuzzleFlashEnabled)
                    {
                        data.tpWeaponRenderer.muzzleFlash.Play(true);
                    }
                }

                //Play third person fire animation
                pb.thirdPersonPlayerModel.PlayWeaponFireAnimation(thirdPersonAnimType);

                //Set shell ejection
                if (shellEjectionPrefab && pb.isFirstPersonActive)
                {
                    data.shellEjectEnabled = true;
                    data.shellEjectNext = Time.time + shellEjectionTime;
                    //The actual ejection is in the CustomUpdate part, so it is coroutine less
                }

                //Subtract bullets
                if (!Kit_IngameMain.instance.gameInformation.debugEnableUnlimitedBullets)
                    data.bulletsLeft--;

                //Simple fire
                if (data.fireTypeMode == FireTypeMode.Simple)
                {
                    if (data.bulletsMode == BulletMode.Raycast)
                    {
                        //Fire Raycast
                        FireRaycast(pb, data, delta, revertBy);
                    }
                    else if (data.bulletsMode == BulletMode.Physical)
                    {
                        //Fire Physical Bullet
                        FirePhysicalBullet(pb, data, rpc);
                    }
                }
                //Pellet fire
                else if (data.fireTypeMode == FireTypeMode.Pellets)
                {
                    //Count how many have been shot
                    int pelletsShot = 0;
                    while (pelletsShot < data.amountOfPellets)
                    {
                        //Increase amount of shot ones
                        pelletsShot++;
                        if (data.bulletsMode == BulletMode.Raycast)
                        {
                            //Fire Raycast
                            FireRaycast(pb, data, delta, revertBy);
                        }
                        else if (data.bulletsMode == BulletMode.Physical)
                        {
                            //Fire Physical Bullet
                            FirePhysicalBullet(pb, data, rpc);
                        }
                    }
                }

                //Increase spray pattern
                if (data.bulletSpreadMode == SpreadMode.SprayPattern)
                {
                    data.sprayPatternState++;
                }

                //Apply recoil using coroutine helper
                Kit_ScriptableObjectCoroutineHelper.instance.StartCoroutine(Kit_ScriptableObjectCoroutineHelper.instance.WeaponApplyRecoil(this, data, pb, RandomExtensions.RandomBetweenVector2(data.recoilPerShotMin, data.recoilPerShotMax), data.recoilApplyTime));
            }

            /// <summary>
            /// Fire one burst (local)
            /// </summary>
            /// <param name="pb"></param>
            /// <param name="data"></param>
            void FireBurst(Kit_PlayerBehaviour pb, Kit_ModernWeaponScriptRuntimeData data, float delta, float revertBy, bool rpc)
            {
                //Update spawn protection
                if (pb.spawnProtection)
                {
                    pb.spawnProtection.GunFired(pb);
                }

                if (pb.isServer && !rpc)
                {
                    //Call network and already tell how many shots are going to be fired
                    if (pb.isServer) pb.RpcWeaponBurstFireNetwork(Mathf.Clamp(data.bulletsLeft, 0, data.burstBulletsPerShot));
                }

                //Start Coroutine
                Kit_ScriptableObjectCoroutineHelper.instance.StartCoroutine(Kit_ScriptableObjectCoroutineHelper.instance.WeaponBurstFire(this, data, pb, delta, revertBy, rpc));
            }

            public void FireRaycast(Kit_PlayerBehaviour pb, Kit_ModernWeaponScriptRuntimeData data, float delta, float revertBy)
            {
                if (pb.isLocalPlayer || pb.isServer)
                {
                    if (data.bulletsPenetrationEnabled)
                    {
                        //Will be set to true again if bullet penetrated through something
                        bool continueLoop = true;

                        //Bullet penetration ability
                        int bulletLifeLeft = data.bulletsPenetrationForce;

                        //So that we may not damage the same player twice
                        List<Kit_PlayerBehaviour> damagedPlayers = new List<Kit_PlayerBehaviour>();


                        RaycastHit hit;
                        Vector3 dir = pb.playerCameraTransform.forward + GetSpread(pb, data);
                        Vector3 pos = pb.playerCameraTransform.position;

                        if (Vector3.Distance(pb.playerCameraTransform.position, pb.input.clientCamPos) < 1)
                        {
                            dir = pb.input.clientCamForward + GetSpread(pb, data);
                            pos = pb.input.clientCamPos;
                        }

                        /*
                        //Override if third person is active
                        if (pb.isFirstPersonActive && Kit_IngameMain.instance.gameInformation.thirdPersonCameraShooting && pb.looking.GetPerspective(pb) == Kit_GameInformation.Perspective.ThirdPerson)
                        {
                            dir = Kit_IngameMain.instance.mainCamera.transform.forward + GetSpread(pb, data);
                            pos = Kit_IngameMain.instance.mainCamera.transform.position;
                        }
                        */

                        RaycastHit[] hits = Physics.RaycastAll(pos, dir, data.range, pb.weaponHitLayers.value).OrderBy(h => h.distance).ToArray();
                        for (int i = 0; i < hits.Length && continueLoop; i++)
                        {
                            hit = hits[i];
                            //Check if we hit ourselves
                            if (hit.collider.gameObject.transform.root != pb.transform.root)
                            {
                                //Set Loop to false
                                continueLoop = false;
                                #region Damage
                                //Check if we hit a player
                                if (hit.collider.GetComponent<Kit_PlayerDamageMultiplier>() && Kit_IngameMain.instance.currentGameModeType == 2)
                                {
                                    if (pb.isLocalPlayer || pb.isServer && pb.isBot)
                                    {
                                        Kit_PlayerDamageMultiplier pdm = hit.collider.GetComponent<Kit_PlayerDamageMultiplier>();
                                        if (hit.collider.transform.root.GetComponent<Kit_PlayerBehaviour>())
                                        {
                                            Kit_PlayerBehaviour hitPb = hit.transform.root.GetComponent<Kit_PlayerBehaviour>();
                                            //Check if we damaged this player already
                                            if (!damagedPlayers.Contains(hitPb))
                                            {
                                                //Add player
                                                damagedPlayers.Add(hitPb);
                                                //Tell server
                                                data.FiredWeapon(hitPb, pdm.ragdollId, pos, hit.point);
                                            }
                                        }
                                    }

                                    if (pb.isServer)
                                    {
                                        //Tell other players we hit something
                                        pb.ClientImpactProcess(hit.point, hit.normal, hit.collider.tag);
                                    }
                                }
                                #endregion
                                #region Particles and Interface
                                else
                                {
                                    if (pb.isServer)
                                    {
                                        //Tell other players we hit something
                                        pb.ClientImpactProcess(hit.point, hit.normal, hit.collider.tag);
                                    }

                                    if (hit.collider.GetComponentInParent<IKitDamageable>() != null)
                                    {
                                        if (hit.collider.GetComponentInParent<IKitDamageable>().LocalDamage(GetDamage(data, Vector3.Distance(pb.playerCameraTransform.position, hit.point)), gameGunID, pb.transform.position, dir, data.ragdollForce, hit.point, pb.isBot, pb.id))
                                        {
                                            if (pb.isServer)
                                            {
                                                //Since we hit a player, show the hitmarker
                                                if (!pb.isBot) pb.TargetHitMarker(0);
                                            }
                                        }
                                    }
                                }
                                #endregion
                                #region Bullet Penetration
                                //Check if this object can be penetrated
                                if (hit.collider.GetComponent<Kit_PenetrateableObject>())
                                {
                                    Kit_PenetrateableObject penetration = hit.collider.GetComponent<Kit_PenetrateableObject>();
                                    if (bulletLifeLeft >= penetration.cost)
                                    {
                                        //We penetrated, subtract cost
                                        bulletLifeLeft -= penetration.cost;
                                        //Set bool
                                        continueLoop = true;
                                    }
                                }

                                //Abort loop if nothing was penetrated
                                if (!continueLoop) break;
                                #endregion
                            }
                        }

                    }
                    else
                    {
                        RaycastHit hit;
                        Vector3 dir = pb.playerCameraTransform.forward + GetSpread(pb, data);
                        Vector3 pos = pb.playerCameraTransform.position;

                        if (Vector3.Distance(pb.playerCameraTransform.position, pb.input.clientCamPos) < 1)
                        {
                            dir = pb.input.clientCamForward + GetSpread(pb, data);
                            pos = pb.input.clientCamPos;
                        }

                        /*
                        //Override if third person is active
                        if (pb.isFirstPersonActive && Kit_IngameMain.instance.gameInformation.thirdPersonCameraShooting && pb.looking.GetPerspective(pb) == Kit_GameInformation.Perspective.ThirdPerson)
                        {
                            dir = Kit_IngameMain.instance.mainCamera.transform.forward + GetSpread(pb, data);
                            pos = Kit_IngameMain.instance.mainCamera.transform.position;
                        }
                        */

                        RaycastHit[] hits = Physics.RaycastAll(pos, dir, data.range, pb.weaponHitLayers.value).OrderBy(h => h.distance).ToArray();
                        for (int i = 0; i < hits.Length; i++)
                        {
                            hit = hits[i];
                            Debug.Log(hit.collider.gameObject.name, hit.collider);
                            //Check if we hit ourselves
                            if (hit.collider.gameObject.transform.root != pb.transform.root)
                            {
                                //Check if we hit a player
                                if (hit.transform.GetComponent<Kit_PlayerDamageMultiplier>())
                                {
                                    if (pb.isLocalPlayer || pb.isServer && pb.isBot)
                                    {
                                        Kit_PlayerDamageMultiplier pdm = hit.transform.GetComponent<Kit_PlayerDamageMultiplier>();
                                        if (hit.transform.root.GetComponent<Kit_PlayerBehaviour>())
                                        {
                                            Kit_PlayerBehaviour hitPb = hit.transform.root.GetComponent<Kit_PlayerBehaviour>();
                                            //Tell server
                                            data.FiredWeapon(hitPb, pdm.ragdollId, pos, hit.point);
                                            break;
                                        }
                                    }

                                    if (pb.isServer)
                                    {
                                        //Tell other players we hit something
                                        pb.ClientImpactProcess(hit.point, hit.normal, hit.collider.tag);
                                    }
                                }
                                else
                                {
                                    if (pb.isServer)
                                    {
                                        //Tell other players we hit something
                                        pb.ClientImpactProcess(hit.point, hit.normal, hit.collider.tag);
                                    }

                                    if (hits[i].collider.GetComponentInParent<IKitDamageable>() != null)
                                    {
                                        if (hits[i].collider.GetComponentInParent<IKitDamageable>().LocalDamage(GetDamage(data, Vector3.Distance(pb.playerCameraTransform.position, hit.point)), gameGunID, pb.transform.position, dir, data.ragdollForce, hit.point, pb.isBot, pb.id))
                                        {

                                            if (pb.isServer)
                                            {
                                                //Since we hit a player, show the hitmarker
                                                if (!pb.isBot) pb.TargetHitMarker(0);
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }

                    //Because these are calculated on the master client, we need to call shoot here too
                    if (Kit_IngameMain.instance.minimap)
                    {
                        Kit_IngameMain.instance.minimap.PlayerShoots(pb, data.tpWeaponRenderer.isWeaponSilenced);
                    }
                }
            }

            public override void NetworkPhysicalBulletFired(Kit_PlayerBehaviour pb, Vector3 pos, Vector3 dir, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    //Get runtime data
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    //Instantiate Game Object
                    GameObject bullet = Kit_IngameMain.instance.objectPooling.GetInstantiateable(data.bulletPrefab, pos, Quaternion.LookRotation(dir));
                    //Call setup
                    bullet.GetComponent<Kit_BulletBase>().Setup(this, data, pb, dir);
                }
            }

            public void FirePhysicalBullet(Kit_PlayerBehaviour pb, Kit_ModernWeaponScriptRuntimeData data, bool rpc)
            {
                if (/*Kit_IngameMain.instance.gameInformation.fireShotsLocally ||*/ pb.isServer)
                {
                    Vector3 dir = pb.playerCameraTransform.forward + GetSpread(pb, data);
                    Vector3 pos = pb.playerCameraTransform.position;

                    if (Vector3.Distance(pb.playerCameraTransform.position, pb.input.clientCamPos) < 1)
                    {
                        dir = pb.input.clientCamForward + GetSpread(pb, data);
                        pos = pb.input.clientCamPos;
                    }

                    /*
                    //Override if third person is active
                    if (pb.isFirstPersonActive && Kit_IngameMain.instance.gameInformation.thirdPersonCameraShooting && pb.looking.GetPerspective(pb) == Kit_GameInformation.Perspective.ThirdPerson)
                    {
                        dir = Kit_IngameMain.instance.mainCamera.transform.forward + GetSpread(pb, data);
                        pos = Kit_IngameMain.instance.mainCamera.transform.position;
                    }
                    */

                    if (pb.isServer && !rpc)
                    {
                        //Send RPC
                        if (pb.isServer) pb.RpcWeaponFirePhysicalBulletOthers(pos, dir);
                    }

                    //Instantiate Game Object
                    GameObject bullet = Kit_IngameMain.instance.objectPooling.GetInstantiateable(data.bulletPrefab, pos, Quaternion.LookRotation(dir));

                    //Call setup
                    bullet.GetComponent<Kit_BulletBase>().Setup(this, data, pb, dir);

                    //Because these are calculated on the master client, we need to call shoot here too
                    if (Kit_IngameMain.instance.minimap)
                    {
                        Kit_IngameMain.instance.minimap.PlayerShoots(pb, data.tpWeaponRenderer.isWeaponSilenced);
                    }
                }
            }

            /// <summary>
            /// Returns the damage for given distance
            /// </summary>
            /// <param name="distance"></param>
            /// <returns></returns>
            public float GetDamage(Kit_ModernWeaponScriptRuntimeData data, float distance)
            {
                return data.baseDamage * data.damageDropoff.Evaluate(distance);
            }

            /// <summary>
            /// Returns a direction (for offset) based on data and this behaviour's stats
            /// </summary>
            /// <param name="pb"></param>
            /// <param name="data"></param>
            Vector3 GetSpread(Kit_PlayerBehaviour pb, Kit_ModernWeaponScriptRuntimeData data)
            {
                float velocity = pb.movement.GetVelocity(pb).magnitude;

                #region Hip Spread
                Vector3 spreadHip = Vector3.zero;
                spreadHip.x = Random.Range(-data.bulletSpreadHipBase, data.bulletSpreadHipBase);
                spreadHip.y = Random.Range(-data.bulletSpreadHipBase, data.bulletSpreadHipBase);
                spreadHip.z = Random.Range(-data.bulletSpreadHipBase, data.bulletSpreadHipBase);

                //Velocity add
                if (velocity > 0)
                {
                    spreadHip.x += RandomExtensions.RandomPosNeg() * data.bulletSpreadHipVelocityAdd * (velocity / data.bulletSpreadHipVelocityReference);
                    spreadHip.y += RandomExtensions.RandomPosNeg() * data.bulletSpreadHipVelocityAdd * (velocity / data.bulletSpreadHipVelocityReference);
                    spreadHip.z += RandomExtensions.RandomPosNeg() * data.bulletSpreadHipVelocityAdd * (velocity / data.bulletSpreadHipVelocityReference);
                }
                #endregion

                #region Aim Spread
                Vector3 spreadAim = Vector3.zero;
                spreadAim.x = Random.Range(-data.bulletSpreadAimBase, data.bulletSpreadAimBase);
                spreadAim.y = Random.Range(-data.bulletSpreadAimBase, data.bulletSpreadAimBase);
                spreadAim.z = Random.Range(-data.bulletSpreadAimBase, data.bulletSpreadAimBase);

                //Velocity add
                if (velocity > 0)
                {
                    spreadAim.x += RandomExtensions.RandomPosNeg() * data.bulletSpreadAimVelocityAdd * (velocity / data.bulletSpreadAimVelocityReference);
                    spreadAim.y += RandomExtensions.RandomPosNeg() * data.bulletSpreadAimVelocityAdd * (velocity / data.bulletSpreadAimVelocityReference);
                    spreadAim.z += RandomExtensions.RandomPosNeg() * data.bulletSpreadAimVelocityAdd * (velocity / data.bulletSpreadAimVelocityReference);
                }
                #endregion

                if (data.bulletSpreadMode == SpreadMode.Simple)
                {
                    //Interpolate between both based on aiming progress
                    return Vector3.Lerp(spreadHip, spreadAim, data.aimingProgress);
                }
                else if (data.bulletSpreadMode == SpreadMode.SprayPattern && data.bulletSpreadSprayPattern.Length > 0)
                {
                    //Interpolate between both based on aiming progress and add spray pattern
                    return Vector3.Lerp(spreadHip, spreadAim, data.aimingProgress) + data.bulletSpreadSprayPattern[Mathf.Clamp(Mathf.RoundToInt(data.sprayPatternState), 0, data.bulletSpreadSprayPattern.Length - 1)];
                }
                else
                {
                    //Interpolate between both based on aiming progress
                    return Vector3.Lerp(spreadHip, spreadAim, data.aimingProgress);
                }
            }

            float GetCrosshairSize(Kit_PlayerBehaviour pb, Kit_ModernWeaponScriptRuntimeData data)
            {
                if (crosshairEnabled)
                {
                    //This is essentially the bullet spread part without the random factors.
                    float velocity = pb.movement.GetVelocity(pb).magnitude;
                    float spreadHip = data.bulletSpreadHipBase;

                    //Velocity add
                    if (velocity > 0)
                    {
                        spreadHip += data.bulletSpreadHipVelocityAdd * (velocity / data.bulletSpreadHipVelocityReference);
                    }

                    return Mathf.Lerp(spreadHip, 0f, data.aimingProgress) * crosshairSizeMultiplier;
                }
                //If crosshair is not enablewd
                else
                {
                    //Return size of 0 which will disable the crosshair
                    return 0f;
                }
            }

            void DryFire(Kit_PlayerBehaviour pb, Kit_ModernWeaponScriptRuntimeData data)
            {
                if (pb.isFirstPersonActive)
                {
                    //Play sound (on Other channel so fire sound can still play)
                    data.soundOther.PlayOneShot(dryFireSound);
                    //Play Dry Fire animation
                    if (data.weaponRenderer.anim)
                    {
                        //Play animation
                        data.weaponRenderer.anim.Play("Dry Fire", data.weaponRenderer.animActionLayer, 0f);

                        for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                        {
                            data.weaponRenderer.animAdditionals[i].Play("Dry Fire", data.weaponRenderer.animAdditionalsActionLayer[i], 0f);
                        }
                    }
                    else if (data.weaponRenderer.legacyAnim && data.weaponRenderer.legacyAnimData.dryFire != "")
                    {
                        //Play animation
                        data.weaponRenderer.legacyAnim.Rewind(data.weaponRenderer.legacyAnimData.dryFire);
                        data.weaponRenderer.legacyAnim.Play(data.weaponRenderer.legacyAnimData.dryFire, PlayMode.StopAll);
                    }
                }
                //Set firerate
                data.lastFire = Time.time + 1f; //+1 so you don't dry fire too quick
            }

            /// <summary>
            /// Ejects a single shell
            /// </summary>
            /// <param name="pb"></param>
            /// <param name="data"></param>
            void EjectShell(Kit_PlayerBehaviour pb, Kit_ModernWeaponScriptRuntimeData data)
            {
                if (shellEjectionPrefab & data.weaponRenderer.shellEjectTransform)
                {
                    GameObject shellObj = null;
                    if (pb.looking.GetPerspective(pb) == Kit_GameInformation.Perspective.FirstPerson)
                    {
                        shellObj = Kit_IngameMain.instance.objectPooling.GetInstantiateable(shellEjectionPrefab, data.weaponRenderer.shellEjectTransform.position, data.weaponRenderer.shellEjectTransform.rotation);
                    }
                    else
                    {
                        shellObj = Kit_IngameMain.instance.objectPooling.GetInstantiateable(shellEjectionPrefab, data.tpWeaponRenderer.shellEjectTransform.position, data.weaponRenderer.shellEjectTransform.rotation);
                    }
                    if (!shellObj) return;
                    //Apply force
                    Rigidbody rb = shellObj.GetComponent<Rigidbody>();
                    rb.isKinematic = false;
                    rb.velocity = pb.movement.GetVelocity(pb);
                    //Add force
                    rb.AddRelativeForce(RandomExtensions.RandomBetweenVector3(shellEjectionMinForce, shellEjectionMaxForce));
                    //Add torque
                    rb.AddRelativeTorque(RandomExtensions.RandomBetweenVector3(shellEjectionMinTorque, shellEjectionMaxTorque));
                }
            }

            public override bool IsWeaponAiming(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    return data.isAiming; //Just relay
                }
                return false;
            }

            public override float GetAimingPercentage(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    return data.aimingProgress;
                }
                return base.GetAimingPercentage(pb, runtimeData);
            }

            public override bool ForceIntoFirstPerson(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    if (data.weaponRenderer)
                        return data.isAiming && data.weaponRenderer.cachedUseFullscreenScope; //Just relay
                }
                return false;
            }

            public override float AimInTime(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                return aimInTime;
            }

            public override float SpeedMultiplier(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    //Lerp from base multiplier to base multiplier multiplied with the aim speed multiplier
                    return Mathf.Lerp(data.speedMultiplierBase, data.speedMultiplierBase * aimSpeedMultiplier, data.aimingProgress);
                }
                return 1f;
            }

            public override void OnAmmoPickup(Kit_PlayerBehaviour pb, Kit_AmmoPickup pickup, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    //Add to bullets
                    data.bulletsLeftToReload += pickup.amountOfClipsToPickup * data.bulletsPerMag;
                }
            }

            public override bool IsWeaponFull(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    return data.bulletsLeftToReload >= data.bulletsToReloadAtStart;
                }

                return base.IsWeaponFull(pb, runtimeData);
            }

            public override void RestockAmmo(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                if (runtimeData != null && runtimeData.GetType() == typeof(Kit_ModernWeaponScriptRuntimeData))
                {
                    Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                    //Reset ammo
                    data.bulletsLeftToReload = data.bulletsToReloadAtStart;
                }
            }
            #endregion

            public override void BeginSpectating(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData, int[] attachments)
            {
                Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                //Create First Person renderer if it doesn't exist already
                if (!data.weaponRenderer)
                {
                    //Setup root for this weapon
                    GameObject root = new GameObject("Weapon root");
                    root.transform.parent = pb.weaponsGo; //Set root
                    root.transform.localPosition = Vector3.zero; //Reset position
                    root.transform.localRotation = Quaternion.identity; //Reset rotation
                    root.transform.localScale = Vector3.one; //Reset scale

                    //Setup generic animations
                    GameObject genericAnimations = Instantiate(genericGunAnimatorControllerPrefab);
                    genericAnimations.transform.parent = root.transform;
                    genericAnimations.transform.localPosition = Vector3.zero; //Reset position
                    genericAnimations.transform.localRotation = Quaternion.identity; //Reset rotation
                    genericAnimations.transform.localScale = Vector3.one; //Reset scale

                    //Get animator
                    Animator anim = genericAnimations.GetComponent<Animator>(); ;
                    anim.Play("Idle");
                    data.genericAnimator = anim;

                    //Setup aiming transform
                    GameObject aimTrans = new GameObject("Weapon aiming");
                    aimTrans.transform.parent = genericAnimations.transform; //Set root
                    aimTrans.transform.localPosition = Vector3.zero; //Reset position
                    aimTrans.transform.localRotation = Quaternion.identity; //Reset rotation
                    aimTrans.transform.localScale = Vector3.one; //Reset scale

                    //Assign it
                    data.aimingTransform = aimTrans.transform;

                    //Delay transform
                    GameObject delayTrans = new GameObject("Weapon delay");
                    delayTrans.transform.parent = aimTrans.transform; //Set root
                    delayTrans.transform.localPosition = Vector3.zero; //Reset position
                    delayTrans.transform.localRotation = Quaternion.identity; //Reset rotation
                    delayTrans.transform.localScale = Vector3.one; //Reset scale

                    //Assign it
                    data.weaponDelayTransform = delayTrans.transform;

                    //Delay transform
                    GameObject fallTrans = new GameObject("Weapon fall");
                    fallTrans.transform.parent = delayTrans.transform; //Set root
                    fallTrans.transform.localPosition = Vector3.zero; //Reset position
                    fallTrans.transform.localRotation = Quaternion.identity; //Reset rotation
                    fallTrans.transform.localScale = Vector3.one; //Reset scale

                    //Assign it
                    data.weaponFallTransform = fallTrans.transform;

                    //Get Fire Audio (Needs to be consistent)
                    if (pb.weaponsGo.GetComponent<AudioSource>()) data.soundFire = pb.weaponsGo.GetComponent<AudioSource>();
                    else data.soundFire = pb.weaponsGo.gameObject.AddComponent<AudioSource>();

                    //Setup reload sound
                    GameObject soundReload = new GameObject("SoundReload"); //Create
                    soundReload.transform.parent = root.transform;
                    soundReload.transform.localPosition = Vector3.zero; //Reset position
                    soundReload.transform.localRotation = Quaternion.identity; //Reset rotation
                    soundReload.transform.localScale = Vector3.one; //Reset scale
                                                                    //Add audio source
                    data.soundReload = soundReload.AddComponent<AudioSource>();

                    //Setup other sound
                    GameObject soundOther = new GameObject("SoundOther"); //Create
                    soundOther.transform.parent = root.transform;
                    soundOther.transform.localPosition = Vector3.zero; //Reset position
                    soundOther.transform.localRotation = Quaternion.identity; //Reset rotation
                    soundOther.transform.localScale = Vector3.one; //Reset scale
                                                                   //Add audio source
                    data.soundOther = soundOther.AddComponent<AudioSource>();

                    //Setup the first person prefab
                    GameObject fpRuntime = Instantiate(firstPersonPrefab, fallTrans.transform, false);
                    fpRuntime.transform.localScale = Vector3.one; //Reset scale

                    //Setup renderer
                    data.weaponRenderer = fpRuntime.GetComponent<Kit_WeaponRenderer>();
                    //Set Attachments
                    data.weaponRenderer.SetAttachments(attachments, this, pb, null);

                    //Play Dependent arms
                    if (data.weaponRenderer.playerModelDependentArmsEnabled && pb.thirdPersonPlayerModel.firstPersonArmsPrefab.Contains(data.weaponRenderer.playerModelDependentArmsKey))
                    {
                        //Create Prefab
                        GameObject fpArms = Instantiate(pb.thirdPersonPlayerModel.firstPersonArmsPrefab[data.weaponRenderer.playerModelDependentArmsKey], fallTrans.transform, false);
                        //Get Arms
                        Kit_FirstPersonArms fpa = fpArms.GetComponent<Kit_FirstPersonArms>();

#if INTEGRATION_FPV2
                        //Set shaders
                        FirstPersonView.ShaderMaterialSolution.FPV_SM_Object armsObj = fpArms.GetComponent<FirstPersonView.ShaderMaterialSolution.FPV_SM_Object>();
                        if (armsObj)
                        {
                            //Set as first person object
                            armsObj.SetAsFirstPersonObject();
                        }
                        else
                        {
                            Debug.LogError("FPV2 is enabled but first person prefab does not have FPV_SM_Object assigned!");
                        }
#elif INTEGRATION_FPV3
                        //Set shaders
                        FirstPersonView.FPV_Object armsObj = fpArms.GetComponent<FirstPersonView.FPV_Object>();
                        if (armsObj)
                        {
                            //Set as first person object
                            armsObj.SetAsFirstPersonObject();
                        }
                        else
                        {
                            Debug.LogError("FPV3 is enabled but first person prefab does not have FPV_Object assigned!");
                        }
#endif

                        //Reparent
                        for (int i = 0; i < fpa.reparents.Length; i++)
                        {
                            if (fpa.reparents[i])
                            {
                                fpa.reparents[i].transform.parent = data.weaponRenderer.playerModelDependentArmsRoot;
                            }
                            else
                            {
                                Debug.LogWarning("First Person Arm Renderer at index " + i + " is not assigned", fpa);
                            }
                        }
                        //Merge Array
                        data.weaponRenderer.allWeaponRenderers = data.weaponRenderer.allWeaponRenderers.Concat(fpa.renderers).ToArray();
                        //Rebind so that the animator animates our freshly reparented transforms too!
                        if (data.weaponRenderer.anim)
                        {
                            data.weaponRenderer.anim.Rebind();
                        }

                        for (int i = 0; i < data.weaponRenderer.animAdditionals.Length; i++)
                        {
                            data.weaponRenderer.animAdditionals[i].Rebind();
                        }
                    }

                    //Hide
                    data.weaponRenderer.visible = false;

#if INTEGRATION_FPV2
                    //Set shaders
                    FirstPersonView.ShaderMaterialSolution.FPV_SM_Object obj = fpRuntime.GetComponent<FirstPersonView.ShaderMaterialSolution.FPV_SM_Object>();
                    if (obj)
                    {
                        //Set as first person object
                        obj.SetAsFirstPersonObject();
                    }
                    else
                    {
                        Debug.LogError("FPV2 is enabled but first person prefab does not have FPV_SM_Object assigned!");
                    }
#elif INTEGRATION_FPV3
                    //Set shaders
                    FirstPersonView.FPV_Object obj = fpRuntime.GetComponent<FirstPersonView.FPV_Object>();
                    if (obj)
                    {
                        //Set as first person object
                        obj.SetAsFirstPersonObject();
                    }
                    else
                    {
                        Debug.LogError("FPV3 is enabled but first person prefab does not have FPV_Object assigned!");
                    }
#endif


                    //Add to the list
                    data.instantiatedObjects.Add(root);
                }

                if (pb.looking.GetPerspective(pb) == Kit_GameInformation.Perspective.FirstPerson)
                {
                    //Show if selected
                    data.weaponRenderer.visible = data.isSelected;

                    //Hide tp
                    data.tpWeaponRenderer.shadowsOnly = true;
                }
                else
                {
                    //FP is definitely hidden, TP is already in the state that it should be in
                    data.weaponRenderer.visible = false;
                }
            }

            public override void EndSpectating(Kit_PlayerBehaviour pb, Kit_WeaponRuntimeDataBase runtimeData)
            {
                //Get data
                Kit_ModernWeaponScriptRuntimeData data = runtimeData as Kit_ModernWeaponScriptRuntimeData;

                //Hide weapon renderer if present
                if (data.weaponRenderer)
                {
                    data.weaponRenderer.visible = false;
                }

                data.tpWeaponRenderer.shadowsOnly = false;
            }
        }
    }
}
using MarsFPSKit.Networking;
using Mirror;
using System.Collections.Generic;
using Unity.Services.Lobbies.Models;
using UnityEngine;

namespace MarsFPSKit
{
    [System.Serializable]
    public class Kit_Bot
    {
        /// <summary>
        /// The ID of this bot
        /// </summary>
        public uint id;
        /// <summary>
        /// The name of this bot
        /// </summary>
        public string name;
        /// <summary>
        /// Team of this bot
        /// </summary>
        public sbyte team;
        /// <summary>
        /// Kills of this bot
        /// </summary>
        public ushort kills;
        /// <summary>
        /// Assists of this bot
        /// </summary>
        public ushort assists;
        /// <summary>
        /// Deaths of this bot
        /// </summary>
        public ushort deaths;
        /// <summary>
        /// Can this bot spawn?
        /// </summary>
        public bool canSpawn = true;
        /// <summary>
        /// Custom per-bot data that can be used by the game mode for example!
        /// </summary>
        public object customData;
        /// <summary>
        /// Custom data per bot for bots
        /// </summary>
        public List<object> pluginCustomBotData = new List<object>();
    }

    public class Kit_BotManager : NetworkBehaviour
    {
        public readonly SyncList<Kit_Bot> bots = new SyncList<Kit_Bot>();
        public List<Kit_PlayerBehaviour> activeBots = new List<Kit_PlayerBehaviour>();

        /// <summary>
        /// Bot name manager to use
        /// </summary>
        public Kit_BotNameManager nameManager;

        public Kit_BotLoadoutManager loadoutManager;

        public float spawnFrequency = 1f;
        private float lastSpawn;
        private uint lastId;

        // Insert here, after private uint lastId;
        [Header("Bot Ammo Settings")]
        [Tooltip("Enable or disable automatic ammo refill for bots.")]
        public bool enableBotAutoRefill = false;  // Default to false to allow ammo seeking behavior

        [Tooltip("Seconds between automatic ammo refill ticks for bots.")]
        public float ammoRefillInterval = 5f;

        private float lastRefillTime;

        private Kit_Bot dirtyBot = new Kit_Bot();

        void Awake()
        {
            // Assign instance
            Kit_IngameMain.instance.currentBotManager = this;
        }

        void Update()
        {
            if (!isServer) return;

            if (Time.time > lastSpawn)
            {
                lastSpawn = Time.time + spawnFrequency;
                SpawnBots();
            }

            if (enableBotAutoRefill)
            {
                // Use automatic refill every interval
                if (Time.time > lastRefillTime + ammoRefillInterval)
                {
                    lastRefillTime = Time.time;

                    for (int i = 0; i < activeBots.Count; i++)
                    {
                        Kit_PlayerBehaviour pb = activeBots[i];
                        if (pb != null && pb.isBot)
                        {
                            pb.RefillBotAmmo();
                        }
                    }
                }
            }
            else
            {
                // Automatic refill disabled - check ammo and seek ammo spawner
                for (int i = 0; i < activeBots.Count; i++)
                {
                    Kit_PlayerBehaviour pb = activeBots[i];
                    if (pb == null || !pb.isBot) continue;

                    // Optionally add IsDead check if applicable
                    // if (pb.IsDead) continue;

                    if (pb.IsAmmoLowOrEmpty())
                    {
                        if (!pb.IsSeekingAmmo)
                        {
                            // Find nearest ammo spawner and set bot to go there
                            Kit_AmmoSpawner nearestAmmo = Kit_AmmoSpawner.FindNearest(pb.transform.position);
                            if (nearestAmmo != null)
                            {
                                Debug.Log($"[Bot Ammo Debug] Bot {pb.id} found nearest ammo spawner at {nearestAmmo.transform.position}. Moving towards it.");
                                pb.GoToAmmoSpawner(nearestAmmo.transform.position);
                            }
                            else
                            {
                                Debug.Log($"[Bot Ammo Debug] Bot {pb.id} could not find any ammo spawner nearby!");
                            }
                        }
                    }
                    else
                    {
                        if (pb.IsSeekingAmmo)
                        {
                            Debug.Log($"[Bot Ammo Debug] Bot {pb.id} ammo is fine. Stopping ammo seeking.");
                            pb.StopSeekingAmmo();
                        }
                    }
                }
            }
        }

        void SpawnBots()
        {
            for (int i = 0; i < bots.Count; i++)
            {
                if (!IsBotAlive(bots[i]) && bots[i].canSpawn)
                {
                    SpawnBot(bots[i]);
                    break;
                }
            }
        }

        void SpawnBot(Kit_Bot bot)
        {
            if (Kit_IngameMain.instance.gameInformation.allPvpGameModes[Kit_IngameMain.instance.currentGameMode].CanSpawn(bot))
            {
                Transform spawnLocation = Kit_IngameMain.instance.gameInformation.allPvpGameModes[Kit_IngameMain.instance.currentGameMode].GetSpawn(bot);
                if (spawnLocation)
                {
                    if (!Kit_IngameMain.instance.currentPvPGameModeBehaviour.UsesCustomSpawn())
                    {
                        Loadout loadout = loadoutManager.GetBotLoadout();
                        GameObject go = Instantiate(Kit_IngameMain.instance.playerPrefab, spawnLocation.position, spawnLocation.rotation);
                        Kit_PlayerBehaviour pb = go.GetComponent<Kit_PlayerBehaviour>();
                        pb.myTeam = bot.team;
                        pb.isBot = true;
                        pb.id = bot.id;
                        pb.thirdPersonPlayerModelID = loadout.teamLoadout[bot.team].playerModelID;
                        pb.thirdPersonPlayerModelCustomizations.AddRange(loadout.teamLoadout[bot.team].playerModelCustomizations);
                        pb.weaponManager.SetupSpawnData(pb, loadout);
                        NetworkServer.Spawn(go);
                    }
                    else
                    {
                        Loadout loadout = Kit_IngameMain.instance.currentPvPGameModeBehaviour.DoCustomSpawnBot(bot);
                        GameObject go = Instantiate(Kit_IngameMain.instance.playerPrefab, spawnLocation.position, spawnLocation.rotation);
                        Kit_PlayerBehaviour pb = go.GetComponent<Kit_PlayerBehaviour>();
                        pb.myTeam = bot.team;
                        pb.isBot = true;
                        pb.id = bot.id;
                        pb.thirdPersonPlayerModelID = loadout.teamLoadout[bot.team].playerModelID;
                        pb.thirdPersonPlayerModelCustomizations.AddRange(loadout.teamLoadout[bot.team].playerModelCustomizations);
                        pb.weaponManager.SetupSpawnData(pb, loadout);
                        NetworkServer.Spawn(go);
                    }
                }
            }
        }

        /// <summary>
        /// Adds a new, empty bot
        /// </summary>
        /// <returns></returns>
        public Kit_Bot AddNewBot(sbyte team = 0)
        {
            Kit_Bot newBot = new Kit_Bot();
            newBot.id = lastId;
            lastId++;
            newBot.team = team;
            newBot.name = nameManager.GetRandomName(this);
            Kit_IngameMain.instance.chat.SendBotMessage(newBot, "Hey guys", 0);
            bots.Add(newBot);

            for (int i = 0; i < Kit_IngameMain.instance.gameInformation.plugins.Length; i++)
            {
                Kit_IngameMain.instance.gameInformation.plugins[i].BotWasCreated(this, newBot);
            }

            return newBot;
        }

        /// <summary>
        /// Removes a random bot
        /// </summary>
        public void RemoveRandomBot()
        {
            Kit_Bot toRemove = GetBotWithID((uint)Random.Range(0, bots.Count));
            Kit_IngameMain.instance.chat.SendBotMessage(toRemove, "Bye guys", 1);
            if (IsBotAlive(toRemove))
            {
                NetworkServer.Destroy(GetAliveBot(toRemove).gameObject);
            }
            bots.Remove(toRemove);
        }

        /// <summary>
        /// Removes a bot that is in this team
        /// </summary>
        /// <param name="team"></param>
        public void RemoveBotInTeam(int team)
        {
            Kit_Bot toRemove = bots.Find(x => x.team == team);
            if (toRemove != null)
            {
                Kit_IngameMain.instance.chat.SendBotMessage(toRemove, "Bye guys", 1);
                if (IsBotAlive(toRemove))
                {
                    NetworkServer.Destroy(GetAliveBot(toRemove).gameObject);
                }
                bots.Remove(toRemove);
            }
        }

        public Kit_Bot GetBotWithID(uint id)
        {
            for (int i = 0; i < bots.Count; i++)
            {
                if (bots[i].id == id)
                {
                    return bots[i];
                }
            }
            return null;
        }

        public bool IsBotAlive(Kit_Bot bot)
        {
            for (int i = 0; i < activeBots.Count; i++)
            {
                if (activeBots[i] && activeBots[i].isBot && activeBots[i].id == bot.id)
                {
                    return true;
                }
            }
            return false;
        }

        public Kit_PlayerBehaviour GetAliveBot(Kit_Bot bot)
        {
            for (int i = 0; i < activeBots.Count; i++)
            {
                if (activeBots[i] && activeBots[i].isBot && activeBots[i].id == bot.id)
                {
                    return activeBots[i];
                }
            }
            return null;
        }

        public void AddActiveBot(Kit_PlayerBehaviour bot)
        {
            activeBots.Add(bot);
        }

        /// <summary>
        /// How many bots are there?
        /// </summary>
        public int GetAmountOfBots()
        {
            return bots.Count;
        }

        /// <summary>
        /// How many bots are in team one?
        /// </summary>
        /// <returns></returns>
        public int GetBotsInTeamX(int team)
        {
            int toReturn = 0;
            for (int i = 0; i < bots.Count; i++)
            {
                if (bots[i].team == team) toReturn++;
            }
            return toReturn;
        }

        /// <summary>
        /// How many players are there?
        /// </summary>
        /// <returns></returns>
        public int GetAmountOfPlayers()
        {
            return Kit_NetworkPlayerManager.instance.players.Count;
        }

        /// <summary>
        /// How many players are in team one?
        /// </summary>
        /// <returns></returns>
        public int GetPlayersInTeamX(int team)
        {
            int toReturn = 0;
            for (int i = 0; i < Kit_NetworkPlayerManager.instance.players.Count; i++)
            {
                if (Kit_NetworkPlayerManager.instance.players[i].team == team) toReturn++;
            }
            return toReturn;
        }

        public void KillAllBots()
        {
            if (NetworkServer.active)
            {
                Kit_PlayerBehaviour[] players = FindObjectsOfType<Kit_PlayerBehaviour>();

                for (int i = 0; i < players.Length; i++)
                {
                    if (players[i] && players[i].isBot)
                    {
                        NetworkServer.Destroy(players[i].gameObject);
                    }
                }
            }
        }

        /// <summary>
        /// Every time a player is modified, he has to be re set, otherwise Mirror will not update his data to the other clients in the list.
        /// </summary>
        /// <param name="player"></param>
        public void ModifyBotData(Kit_Bot bot)
        {
            int index = bots.IndexOf(bot);
            bots[index] = dirtyBot;
            bots[index] = bot;
        }
    }
}
using MarsFPSKit.Weapons;
using System;
using UnityEngine;

using Random = UnityEngine.Random;

namespace MarsFPSKit
{
    /// <summary>
    /// Creates random valid loadouts for bots
    /// </summary>
    [CreateAssetMenu(menuName = "MarsFPSKit/Bots/Loadout/Random")]
    public class Kit_BotRandomLoadoutManager : Kit_BotLoadoutManager
    {
        public override Loadout GetBotLoadout()
        {
            Kit_GameInformation game = Kit_IngameMain.instance.gameInformation;
            Loadout toReturn = new Loadout();
            //Find a primary
            Kit_WeaponBase[] primaries = Array.FindAll(game.allWeapons, x => x.CanBeSelectedInLoadout() && x.weaponType.GetLocalizedString() == game.allWeaponCategories[0].GetLocalizedString());
            Kit_WeaponBase primary = primaries[Random.Range(0, primaries.Length)];
            int primaryIndex = Array.IndexOf(Kit_IngameMain.instance.gameInformation.allWeapons, primary);
            //Find a secondary
            Kit_WeaponBase[] secondaries = Array.FindAll(Kit_IngameMain.instance.gameInformation.allWeapons, x => x.CanBeSelectedInLoadout() && x.weaponType.GetLocalizedString() == game.allWeaponCategories[1].GetLocalizedString());
            Kit_WeaponBase secondary = secondaries[Random.Range(0, secondaries.Length)];
            int secondaryIndex = Array.IndexOf(Kit_IngameMain.instance.gameInformation.allWeapons, secondary);

            toReturn.loadoutWeapons = new LoadoutWeapon[2];
            toReturn.loadoutWeapons[0] = new LoadoutWeapon();
            toReturn.loadoutWeapons[1] = new LoadoutWeapon();

            toReturn.loadoutWeapons[0].weaponID = primaryIndex;
            if (primary is Kit_ModernWeaponScript)
            {
                Kit_ModernWeaponScript mp = primary as Kit_ModernWeaponScript;
                int length = mp.attachmentSlots.Length;
                toReturn.loadoutWeapons[0].attachments = new int[length];
                for (int i = 0; i < toReturn.loadoutWeapons[0].attachments.Length; i++)
                {
                    toReturn.loadoutWeapons[0].attachments[i] = Random.Range(0, mp.attachmentSlots[i].availableAttachments.Length);
                }
            }
            else
            {
                toReturn.loadoutWeapons[0].attachments = new int[0];
            }

            toReturn.loadoutWeapons[1].weaponID = secondaryIndex;
            if (secondary is Kit_ModernWeaponScript)
            {
                Kit_ModernWeaponScript sp = secondary as Kit_ModernWeaponScript;
                int length = sp.attachmentSlots.Length;
                toReturn.loadoutWeapons[1].attachments = new int[length];
                for (int i = 0; i < toReturn.loadoutWeapons[1].attachments.Length; i++)
                {
                    toReturn.loadoutWeapons[1].attachments[i] = Random.Range(0, sp.attachmentSlots[i].availableAttachments.Length);
                }
            }
            else
            {
                toReturn.loadoutWeapons[1].attachments = new int[0];
            }

            toReturn.teamLoadout = new TeamLoadout[Kit_IngameMain.instance.gameInformation.allPvpTeams.Length];

            for (int i = 0; i < toReturn.teamLoadout.Length; i++)
            {
                toReturn.teamLoadout[i] = new TeamLoadout();
                toReturn.teamLoadout[i].playerModelID = Random.Range(0, Kit_IngameMain.instance.gameInformation.allPvpTeams[i].playerModels.Length);
                toReturn.teamLoadout[i].playerModelCustomizations = new int[Kit_IngameMain.instance.gameInformation.allPvpTeams[i].playerModels[toReturn.teamLoadout[i].playerModelID].prefab.GetComponent<Kit_ThirdPersonPlayerModel>().customizationSlots.Length];
            }

            /*
            //Assign
            toReturn.primaryWeapon = primaryIndex;
            if (primary.firstPersonPrefab.GetComponent<Weapons.Kit_WeaponRenderer>())
            {
                toReturn.primaryAttachments = new int[primary.firstPersonPrefab.GetComponent<Weapons.Kit_WeaponRenderer>().attachmentSlots.Length];
            }
            else
            {
                toReturn.primaryAttachments = new int[0];
            }
            toReturn.secondaryWeapon = secondaryIndex;
            if (secondary.firstPersonPrefab.GetComponent<Weapons.Kit_WeaponRenderer>())
            {
                toReturn.secondaryAttachments = new int[secondary.firstPersonPrefab.GetComponent<Weapons.Kit_WeaponRenderer>().attachmentSlots.Length];
            }
            else
            {
                toReturn.secondaryAttachments = new int[0];
            }
            */
            return toReturn;
        }
    }
}
using UnityEngine;

namespace MarsFPSKit
{
    public abstract class Kit_BotLoadoutManager : ScriptableObject
    {
        /// <summary>
        /// Gets a loadout for a bot
        /// </summary>
        /// <param name="main"></param>
        /// <returns></returns>
        public abstract Loadout GetBotLoadout();
    }
}
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Localization;
using UnityEngine.UI;

namespace MarsFPSKit
{
    public class Kit_LoadoutNew : Kit_LoadoutBase
    {
        /// <summary>
        /// Main Menu
        /// </summary>
        private UI.Kit_MenuManager menu;

        private Kit_GameInformation game
        {
            get
            {
                if (Kit_IngameMain.instance) return Kit_IngameMain.instance.gameInformation;
                if (menu) return menu.game;

                return null;
            }
        }

        /// <summary>
        /// The loadouts
        /// </summary>
        public Loadout[] allLoadouts;
        /// <summary>
        /// The currently selected loadout
        /// </summary>
        public int currentlySelectedLoadout;
        [Header("Loadout Selection")]
        /// <summary>
        /// How many loadouts do we allow?
        /// </summary>
        public int amountOfLoadouts = 5;
        /// <summary>
        /// What is shown
        /// </summary>
        public LocalizedString loadoutText;
        /// <summary>
        /// Screen id of the loadout selection
        /// </summary>
        public int loadoutScreenID = 0;
        /// <summary>
        /// Where the loadouts go
        /// </summary>
        public RectTransform loadoutGo;
        /// <summary>
        /// Prefab for the loadouts
        /// </summary>
        public GameObject loadoutPrefab;

        /// <summary>
        /// Main Category screen
        /// </summary>
        [Header("Main Category Selection")]
        public int mainCategoryScreenID = 1;

        /// <summary>
        /// Where the weapon category buttons go
        /// </summary>
        [Header("Weapon Category Selection")]
        public RectTransform weaponCategoryGo;
        /// <summary>
        /// Button prefab for weapon category selection
        /// </summary>
        public GameObject weaponCategoryPrefab;
        /// <summary>
        /// Screen ID for selecting the weapon category
        /// </summary>
        public int weaponCategoryScreenId = 6;
        /// <summary>
        /// The category that we selected last
        /// </summary>
        public int currentSelectedWeaponCategory;

        /// <summary>
        /// Where the weapon subcategory buttons go
        /// </summary>
        [Header("Weapon Sub-Category Selection")]
        public RectTransform weaponSubCategoryGo;
        /// <summary>
        /// Button prefab for weapon subcategory selection
        /// </summary>
        public GameObject weaponSubCategoryPrefab;
        /// <summary>
        /// Screen ID for selecting the weapon subcategory
        /// </summary>
        public int weaponSubCategoryScreenId = 7;
        /// <summary>
        /// Active sub category entries
        /// </summary>
        public List<GameObject> weaponSubCategoryActives = new List<GameObject>();

        /// <summary>
        /// Where the weapon buttons go
        /// </summary>
        [Header("Weapon Selection")]
        public RectTransform weaponSelectionGo;
        /// <summary>
        /// Button prefab for weapon selection
        /// </summary>
        public GameObject weaponSelectionPrefab;
        /// <summary>
        /// Shows us when that weapon is being unlocked
        /// </summary>
        public LocalizedString weaponSelectionUnlocksAtLevelText;
        /// <summary>
        /// Screen ID for selecting the weapon
        /// </summary>
        public int weaponSelectionScreenId = 8;
        /// <summary>
        /// Active weapon entries
        /// </summary>
        public List<GameObject> weaponSelectionActives = new List<GameObject>();

        /// <summary>
        /// Where the weapon customization category buttons go
        /// </summary>
        [Header("Weapon Customization Category Selection")]
        public RectTransform weaponCustomizationCategoryGo;
        /// <summary>
        /// Button prefab for weapon customization category selection
        /// </summary>
        public GameObject weaponCustomizationCategoryPrefab;
        /// <summary>
        /// Screen ID for selecting the weapon customization category
        /// </summary>
        public int weaponCustomizationCategoryScreenId = 9;
        /// <summary>
        /// Active weapon customization category entries
        /// </summary>
        public List<GameObject> weaponCustomizationCategoryActives = new List<GameObject>();


        /// <summary>
        /// Where the weapon customization attachment buttons go
        /// </summary>
        [Header("Weapon Customization Attachment Selection")]
        public RectTransform weaponCustomizationAttachmentGo;
        /// <summary>
        /// Button prefab for weapon customization attachment selection
        /// </summary>
        public GameObject weaponCustomizationAttachmentPrefab;
        /// <summary>
        /// Screen ID for selecting the weapon customization attachments
        /// </summary>
        public int weaponCustomizationAttachmentScreenId = 10;
        /// <summary>
        /// Active weapon customization attachments entries
        /// </summary>
        public List<GameObject> weaponCustomizationAttachmentActives = new List<GameObject>();

        /// <summary>
        /// Currently active third person preview
        /// </summary>
        [Header("Weapon Preview")]
        public GameObject weaponPreviewObjectThirdPerson;
        /// <summary>
        /// Where the FP goes
        /// </summary>
        public Transform weaponPreviewFirstPersonGo;
        /// <summary>
        /// Currently active first person preview
        /// </summary>
        public GameObject weaponPreviewObjectFirstPerson;
        /// <summary>
        /// Camera that renders the weapon
        /// </summary>
        public Camera weaponPreviewRenderCam;

        /// <summary>
        /// Where the team buttons go
        /// </summary>
        [Header("Player Model Team Selection")]
        public RectTransform playerModelTeamGo;
        /// <summary>
        /// Button prefab for player model selection (team)
        /// </summary>
        public GameObject playerModelTeamPrefab;
        /// <summary>
        /// Screen ID for selecting the team to customize your player model
        /// </summary>
        public int playerModelTeamScreenId = 2;
        /// <summary>
        /// The team that we selected last
        /// </summary>
        public int currentSelectedTeamForPlayerModel;

        /// <summary>
        /// Where the player model buttons go
        /// </summary>
        [Header("Player Model Selection")]
        public RectTransform playerModelSelectionGo;
        /// <summary>
        /// Button prefab for player model selection
        /// </summary>
        public GameObject playerModelSelectionPrefab;
        /// <summary>
        /// Screen ID for selecting the model to use and customize
        /// </summary>
        public int playerModelSelectionScreenId = 3;
        /// <summary>
        /// Currently active buttons
        /// </summary>
        public List<GameObject> playerModelSelectionActives = new List<GameObject>();

        /// <summary>
        /// Where the player model buttons go
        /// </summary>
        [Header("Player Model Customization Category Selection")]
        public RectTransform playerModelCustomizationCategoryGo;
        /// <summary>
        /// Button prefab for player model selection
        /// </summary>
        public GameObject playerModelCustomizationCategoryPrefab;
        /// <summary>
        /// Screen ID for selecting the customization category
        /// </summary>
        public int playerModelCustomizationCategoryScreenId = 4;
        /// <summary>
        /// Currently active buttons
        /// </summary>
        public List<GameObject> playerModelCustomizationCategoryActives = new List<GameObject>();

        /// <summary>
        /// Where the player model buttons go
        /// </summary>
        [Header("Player Model Customization Selection")]
        public RectTransform playerModelCustomizationGo;
        /// <summary>
        /// Button prefab for player model selection
        /// </summary>
        public GameObject playerModelCustomizationPrefab;
        /// <summary>
        /// Screen ID for selecting the customization category
        /// </summary>
        public int playerModelCustomizationScreenId = 5;
        /// <summary>
        /// Currently active buttons
        /// </summary>
        public List<GameObject> playerModelCustomizationActives = new List<GameObject>();


        /// <summary>
        /// Where the actual visible player model goes
        /// </summary>
        [Header("Player Model Preview")]
        public Transform playerModelPreviewGo;
        /// <summary>
        /// Currently visible player model
        /// </summary>
        public Kit_ThirdPersonPlayerModel playerModelCurrent;
        /// <summary>
        /// Script to help with IK
        /// </summary>
        private Kit_LoadoutIKHelper playerModelIkHelper;
        /// <summary>
        /// The camera that renders the player model
        /// </summary>
        public Camera playerModelRenderCam;
        /// <summary>
        /// Render cam current target position
        /// </summary>
        public Vector3 playerModelRenderCamPosition;
        /// <summary>
        /// How far from the camera it should be
        /// </summary>
        public float playerModelRenderCamCustomizationDistance = 0.75f;

        /// <summary>
        /// The loadout submenus
        /// </summary>
        [Header("Menu")]
        public UI.MenuScreen[] subMenus;
        /// <summary>
        /// Currently visible subscreen
        /// </summary>
        private int currentSubScreen = 0;
        /// <summary>
        /// True if we are currently switching a screen
        /// </summary>
        private bool isSwitchingScreens;
        /// <summary>
        /// Where we are currently switching screens to
        /// </summary>
        private Coroutine currentlySwitchingScreensTo;

        private void Awake()
        {
            //Disable all the roots
            for (int i = 0; i < subMenus.Length; i++)
            {
                if (subMenus[i].root)
                {
                    //Disable
                    subMenus[i].root.SetActive(false);
                }
                else
                {
                    Debug.LogError("Submenu root at index " + i + " is not assigned.", this);
                }
            }

            //Enable Loadout Screen ID
            currentSubScreen = loadoutScreenID;
            subMenus[currentSubScreen].root.SetActive(true);

            //Disable cameras
            playerModelRenderCam.enabled = false;
            weaponPreviewRenderCam.enabled = false;

            //Cam default position
            playerModelRenderCamPosition = playerModelRenderCam.transform.parent.position;
        }

        private void Update()
        {
            //Smoothly move the player model camera where we want it to look at :)
            playerModelRenderCam.transform.position = Vector3.Lerp(playerModelRenderCam.transform.position, playerModelRenderCamPosition, Time.deltaTime * 5f);
        }

        public override void ForceClose()
        {
            if (menu)
            {
                if (menu.currentScreen == menuScreenId)
                {
                    menu.SwitchMenu(menu.mainScreen);
                }
            }

            if (Kit_IngameMain.instance)
            {
                if (Kit_IngameMain.instance.currentScreen == menuScreenId)
                {
                    Kit_IngameMain.instance.SwitchMenu(Kit_IngameMain.instance.pauseMenu.pauseMenuId);
                }
            }

            //Disable cameras
            playerModelRenderCam.enabled = false;
            weaponPreviewRenderCam.enabled = false;

            isOpen = false;
        }

        public override Loadout GetCurrentLoadout()
        {
            Loadout loadout = new Loadout();

            //We create a fully copy of the loadout that we selected so that modifying our loadout (attachments) does not update the attachments you currently have selected (on your player)
            loadout.loadoutWeapons = new LoadoutWeapon[allLoadouts[currentlySelectedLoadout].loadoutWeapons.Length];

            for (int i = 0; i < loadout.loadoutWeapons.Length; i++)
            {
                loadout.loadoutWeapons[i] = new LoadoutWeapon();
                loadout.loadoutWeapons[i].weaponID = allLoadouts[currentlySelectedLoadout].loadoutWeapons[i].weaponID;
                loadout.loadoutWeapons[i].attachments = new int[allLoadouts[currentlySelectedLoadout].loadoutWeapons[i].attachments.Length];

                for (int o = 0; o < loadout.loadoutWeapons[i].attachments.Length; o++)
                {
                    loadout.loadoutWeapons[i].attachments[o] = allLoadouts[currentlySelectedLoadout].loadoutWeapons[i].attachments[o];
                }
            }

            loadout.teamLoadout = new TeamLoadout[allLoadouts[currentlySelectedLoadout].teamLoadout.Length];

            for (int i = 0; i < loadout.teamLoadout.Length; i++)
            {
                loadout.teamLoadout[i] = new TeamLoadout();
                loadout.teamLoadout[i].playerModelID = allLoadouts[currentlySelectedLoadout].teamLoadout[i].playerModelID;

                loadout.teamLoadout[i].playerModelCustomizations = new int[allLoadouts[currentlySelectedLoadout].teamLoadout[i].playerModelCustomizations.Length];

                for (int o = 0; o < loadout.teamLoadout[i].playerModelCustomizations.Length; o++)
                {
                    loadout.teamLoadout[i].playerModelCustomizations[o] = allLoadouts[currentlySelectedLoadout].teamLoadout[i].playerModelCustomizations[o];
                }
            }

            return loadout;
        }

        public override void Initialize()
        {
            menu = FindObjectOfType<UI.Kit_MenuManager>();

            //Create Loadouts
            for (int i = 0; i < amountOfLoadouts; i++)
            {
                int id = i;
                //Create
                GameObject go = Instantiate(loadoutPrefab, loadoutGo, false);
                //Setup text
                TextMeshProUGUI txt = go.GetComponentInChildren<TextMeshProUGUI>();
                if (txt) txt.text = string.Format(loadoutText.GetLocalizedString(), (id + 1));
                //Setup Button
                Button btn = go.GetComponentInChildren<Button>();
                btn.onClick.AddListener(delegate { SelectLoadout(id); });
            }

            allLoadouts = new Loadout[amountOfLoadouts];

            //Setup default blank loadout
            for (int i = 0; i < allLoadouts.Length; i++)
            {
                int id = i;

                allLoadouts[id] = new Loadout();

                //Weapon selection
                allLoadouts[id].loadoutWeapons = new LoadoutWeapon[game.allWeaponCategories.Length];

                for (int j = 0; j < allLoadouts[id].loadoutWeapons.Length; j++)
                {
                    int jd = j;
                    allLoadouts[id].loadoutWeapons[jd] = new LoadoutWeapon();
                    //Set default one
                    allLoadouts[id].loadoutWeapons[jd].weaponID = System.Array.IndexOf(game.allWeapons, game.defaultWeaponsInSlot[jd]);

                    Weapons.Kit_ModernWeaponScript wpnRender = game.allWeapons[allLoadouts[id].loadoutWeapons[jd].weaponID] as Weapons.Kit_ModernWeaponScript;

                    //Kit_ModernWeaponScript attachments
                    if (wpnRender)
                    {
                        allLoadouts[id].loadoutWeapons[jd].attachments = new int[wpnRender.attachmentSlots.Length];
                    }
                    //No script with attachments.
                    else
                    {
                        allLoadouts[id].loadoutWeapons[jd].attachments = new int[0];
                    }
                }

                //Player Model selection
                allLoadouts[id].teamLoadout = new TeamLoadout[game.allPvpTeams.Length];

                for (int j = 0; j < allLoadouts[id].teamLoadout.Length; j++)
                {
                    //Setup Player Model Customization for default model
                    int jd = j;
                    allLoadouts[id].teamLoadout[jd] = new TeamLoadout();
                    allLoadouts[id].teamLoadout[jd].playerModelID = game.allPvpTeams[jd].playerModelDefault;
                    allLoadouts[id].teamLoadout[jd].playerModelCustomizations = new int[game.allPvpTeams[jd].playerModels[allLoadouts[id].teamLoadout[jd].playerModelID].prefab.GetComponent<Kit_ThirdPersonPlayerModel>().customizationSlots.Length];
                }
            }

            //Create Weapon Categories
            for (int i = 0; i < game.allWeaponCategories.Length; i++)
            {
                int id = i;
                //Create
                GameObject go = Instantiate(weaponCategoryPrefab, weaponCategoryGo, false);
                //Setup text
                TextMeshProUGUI txt = go.GetComponentInChildren<TextMeshProUGUI>();
                if (txt) txt.text = game.allWeaponCategories[id].GetLocalizedString();
                //Setup Button
                Button btn = go.GetComponentInChildren<Button>();
                btn.onClick.AddListener(delegate { WeaponSelectCategory(id); });
            }

            //Create Team selection for player model
            for (int i = 0; i < game.allPvpTeams.Length; i++)
            {
                int id = i;
                //Create
                GameObject go = Instantiate(playerModelTeamPrefab, playerModelTeamGo, false);
                //Setup text
                TextMeshProUGUI txt = go.GetComponentInChildren<TextMeshProUGUI>();
                if (txt) txt.text = game.allPvpTeams[id].teamName.GetLocalizedString();
                //Setup Button
                Button btn = go.GetComponentInChildren<Button>();
                btn.onClick.AddListener(delegate { PlayerModelSelectTeam(id); });
            }

            Load();
            //Redraw
            RedrawPlayerModel();
        }

        public override void Open()
        {
            if (amountOfLoadouts > 1)
            {
                if (menu)
                {
                    if (!menu.SwitchMenu(menuScreenId)) return;
                }

                if (Kit_IngameMain.instance)
                {
                    if (!Kit_IngameMain.instance.SwitchMenu(menuScreenId)) return;
                }
            }
            else
            {
                if (menu)
                {
                    if (!menu.SwitchMenu(menuScreenId)) return;
                }

                if (Kit_IngameMain.instance)
                {
                    if (!Kit_IngameMain.instance.SwitchMenu(menuScreenId)) return;
                }

                SwitchMenu(mainCategoryScreenID);
            }



            playerModelRenderCam.enabled = true;
            weaponPreviewRenderCam.enabled = true;

            isOpen = true;
        }

        public void Back()
        {
            if (currentSubScreen == loadoutScreenID)
            {
                ForceClose();
            }
            else if (currentSubScreen == mainCategoryScreenID)
            {
                if (amountOfLoadouts > 1)
                {
                    SwitchMenu(loadoutScreenID);
                }
                else
                {
                    ForceClose();
                }
            }
            else if (currentSubScreen == playerModelTeamScreenId)
            {
                SwitchMenu(mainCategoryScreenID);
            }
            else if (currentSubScreen == playerModelSelectionScreenId)
            {
                SwitchMenu(playerModelTeamScreenId);
            }
            else if (currentSubScreen == playerModelCustomizationCategoryScreenId)
            {
                if (!SwitchMenu(playerModelSelectionScreenId)) return;
            }
            else if (currentSubScreen == playerModelCustomizationScreenId)
            {
                if (!SwitchMenu(playerModelCustomizationCategoryScreenId)) return;
                //Reset
                playerModelRenderCamPosition = playerModelRenderCam.transform.parent.position;
            }
            else if (currentSubScreen == weaponCategoryScreenId)
            {
                SwitchMenu(mainCategoryScreenID);
            }
            else if (currentSubScreen == weaponSubCategoryScreenId)
            {
                SwitchMenu(weaponCategoryScreenId);
            }
            else if (currentSubScreen == weaponSelectionScreenId)
            {
                SwitchMenu(weaponSubCategoryScreenId);
            }
            else if (currentSubScreen == weaponCustomizationCategoryScreenId)
            {
                SwitchMenu(weaponSelectionScreenId);
            }
            else if (currentSubScreen == weaponCustomizationAttachmentScreenId)
            {
                SwitchMenu(weaponCustomizationCategoryScreenId);
            }

            Save();
        }

        public void SelectLoadout(int id)
        {
            currentlySelectedLoadout = id;
            SwitchMenu(mainCategoryScreenID);

            RedrawPlayerModel();
        }

        public void CategoryWeapons()
        {
            SwitchMenu(weaponCategoryScreenId);
        }

        public void WeaponSelectCategory(int id)
        {
            //Select category
            currentSelectedWeaponCategory = id;

            //Delete actives
            for (int i = 0; i < weaponSubCategoryActives.Count; i++)
            {
                Destroy(weaponSubCategoryActives[i]);
            }
            //Reset list
            weaponSubCategoryActives = new List<GameObject>();

            //Fetch subcategories for this weapon category
            List<string> subcategories = new List<string>();

            for (int i = 0; i < game.allWeapons.Length; i++)
            {
                if (game.allWeapons[i].CanBeSelectedInLoadout())
                {
                    //Check if weapon is for our category
                    if (game.allWeapons[i].weaponType.GetLocalizedString() == game.allWeaponCategories[currentSelectedWeaponCategory].GetLocalizedString())
                    {
                        //Add our sub category if its not added yet
                        if (!subcategories.Contains(game.allWeapons[i].weaponLoadoutSubCategory.GetLocalizedString()))
                        {
                            subcategories.Add(game.allWeapons[i].weaponLoadoutSubCategory.GetLocalizedString());
                        }
                    }
                }
            }

            for (int i = 0; i < subcategories.Count; i++)
            {
                int catId = i;
                //Create
                GameObject go = Instantiate(weaponSubCategoryPrefab, weaponSubCategoryGo, false);
                //Setup text
                TextMeshProUGUI txt = go.GetComponentInChildren<TextMeshProUGUI>();
                if (txt) txt.text = subcategories[catId];
                //Setup Button
                Button btn = go.GetComponentInChildren<Button>();
                btn.onClick.AddListener(delegate { WeaponSelectSubcategory(id, subcategories[catId]); });
                //Add to list
                weaponSubCategoryActives.Add(go);
            }

            SwitchMenu(weaponSubCategoryScreenId);

            RedrawWeapon();
        }

        public void WeaponSelectSubcategory(int cat, string subCat)
        {
            //Destroy old ones
            for (int i = 0; i < weaponSelectionActives.Count; i++)
            {
                Destroy(weaponSelectionActives[i]);
            }
            //Reset list
            weaponSelectionActives = new List<GameObject>();

            for (int i = 0; i < game.allWeapons.Length; i++)
            {
                int id = i;
                if (game.allWeapons[id].CanBeSelectedInLoadout())
                {
                    //Check if weapon is for our category
                    if (game.allWeapons[id].weaponType.GetLocalizedString() == game.allWeaponCategories[currentSelectedWeaponCategory].GetLocalizedString())
                    {
                        //Check if weapon is in that sub category
                        if (game.allWeapons[id].weaponLoadoutSubCategory.GetLocalizedString() == subCat)
                        {
                            //Create
                            GameObject go = Instantiate(weaponSelectionPrefab, weaponSelectionGo, false);
                            //Setup text
                            TextMeshProUGUI txt = go.GetComponentInChildren<TextMeshProUGUI>();
                            if (txt)
                            {
                                if (game.allWeapons[id].IsWeaponUnlocked(game))
                                {
                                    txt.text = game.allWeapons[id].weaponName.GetLocalizedString();
                                }
                                else
                                {
                                    txt.text = string.Format(weaponSelectionUnlocksAtLevelText.GetLocalizedString(), game.allWeapons[id].weaponName.GetLocalizedString(), game.allWeapons[id].levelToUnlockAt);
                                }
                            }
                            //Setup Button
                            Button btn = go.GetComponentInChildren<Button>();
                            btn.onClick.AddListener(delegate { WeaponSelect(cat, id); });
                            //Add to list
                            weaponSelectionActives.Add(go);
                        }
                    }
                }
            }

            SwitchMenu(weaponSelectionScreenId);
        }

        public void WeaponSelect(int slot, int id)
        {
            //Check if weapon is unlocked
            if (game.allWeapons[id].IsWeaponUnlocked(game))
            {
                Weapons.Kit_ModernWeaponScript wpnRender = game.allWeapons[id] as Weapons.Kit_ModernWeaponScript;

                if (allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].weaponID != id)
                {         //Select
                    allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].weaponID = id;

                    //Kit_ModernWeaponScript attachments
                    if (wpnRender)
                    {
                        allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].attachments = new int[wpnRender.attachmentSlots.Length];
                    }
                    //No script with attachments.
                    else
                    {
                        allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].attachments = new int[0];
                    }
                }
                else
                {
                    if (wpnRender)
                    {
                        //Size doesnt match up
                        if (allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].attachments.Length != wpnRender.attachmentSlots.Length)
                        {
                            allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].attachments = new int[wpnRender.attachmentSlots.Length];
                        }
                        //Make sure no invalid selections are present
                        else
                        {
                            for (int i = 0; i < allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].attachments.Length; i++)
                            {
                                //Clamp it up to a valid selection, 0 length is invalid configuration anyway
                                allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].attachments[i] = Mathf.Clamp(allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].attachments[i], 0, wpnRender.attachmentSlots[i].availableAttachments.Length - 1);
                            }
                        }
                    }
                    else
                    {
                        //No valid attachment possible
                        allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].attachments = new int[0];
                    }
                }


                //Proceed to customization
                if (wpnRender && wpnRender.attachmentSlots.Length > 0)
                {
                    //Destroy
                    for (int i = 0; i < weaponCustomizationCategoryActives.Count; i++)
                    {
                        Destroy(weaponCustomizationCategoryActives[i]);
                    }
                    //Reset
                    weaponCustomizationCategoryActives = new List<GameObject>();

                    for (int i = 0; i < wpnRender.attachmentSlots.Length; i++)
                    {
                        int catId = i;
                        //Create
                        GameObject go = Instantiate(weaponCustomizationCategoryPrefab, weaponCustomizationCategoryGo, false);
                        //Setup text
                        TextMeshProUGUI txt = go.GetComponentInChildren<TextMeshProUGUI>();
                        if (txt) txt.text = wpnRender.attachmentSlots[catId].slotName.GetLocalizedString();
                        //Setup Button
                        Button btn = go.GetComponentInChildren<Button>();
                        btn.onClick.AddListener(delegate { WeaponCustomizationSelectCategory(slot, id, catId); });
                        //Add to list
                        weaponCustomizationCategoryActives.Add(go);
                    }

                    SwitchMenu(weaponCustomizationCategoryScreenId);
                }

                //Redraw
                RedrawWeapon();
            }
        }

        public void WeaponCustomizationSelectCategory(int slot, int wep, int catId)
        {
            //Destroy
            for (int i = 0; i < weaponCustomizationAttachmentActives.Count; i++)
            {
                Destroy(weaponCustomizationAttachmentActives[i]);
            }
            //Reset
            weaponCustomizationAttachmentActives = new List<GameObject>();

            Weapons.Kit_ModernWeaponScript wpnRender = game.allWeapons[wep] as Weapons.Kit_ModernWeaponScript;

            if (wpnRender)
            {
                for (int i = 0; i < wpnRender.attachmentSlots[catId].availableAttachments.Length; i++)
                {
                    int id = i;
                    //Create
                    GameObject go = Instantiate(weaponCustomizationAttachmentPrefab, weaponCustomizationAttachmentGo, false);
                    //Setup text
                    TextMeshProUGUI txt = go.GetComponentInChildren<TextMeshProUGUI>();
                    if (txt) txt.text = wpnRender.attachmentSlots[catId].availableAttachments[id].displayName.GetLocalizedString();
                    //Setup Button
                    Button btn = go.GetComponentInChildren<Button>();
                    btn.onClick.AddListener(delegate { SelectAttachment(slot, catId, id); });
                    //Add to list
                    weaponCustomizationAttachmentActives.Add(go);
                }

                SwitchMenu(weaponCustomizationAttachmentScreenId);
            }
        }

        public void SelectAttachment(int slot, int attachmentSlot, int attachment)
        {
            allLoadouts[currentlySelectedLoadout].loadoutWeapons[slot].attachments[attachmentSlot] = attachment;
            RedrawWeapon();
        }

        public void CategoryPlayerModel()
        {
            SwitchMenu(playerModelTeamScreenId);
        }

        public void PlayerModelSelectTeam(int team)
        {
            if (!SwitchMenu(playerModelSelectionScreenId)) return;
            currentSelectedTeamForPlayerModel = team;

            //Delete old ones
            for (int i = 0; i < playerModelSelectionActives.Count; i++)
            {
                Destroy(playerModelSelectionActives[i]);
            }
            //Reset list
            playerModelSelectionActives = new List<GameObject>();
            //List player models

            for (int i = 0; i < game.allPvpTeams[currentSelectedTeamForPlayerModel].playerModels.Length; i++)
            {
                int id = i;
                //Create
                GameObject go = Instantiate(playerModelSelectionPrefab, playerModelSelectionGo, false);
                //Setup text
                TextMeshProUGUI txt = go.GetComponentInChildren<TextMeshProUGUI>();
                if (txt) txt.text = game.allPvpTeams[currentSelectedTeamForPlayerModel].playerModels[id].displayName.GetLocalizedString();
                //Setup Button
                Button btn = go.GetComponentInChildren<Button>();
                btn.onClick.AddListener(delegate { PlayerModelSelect(team, id); });
                //Add to list
                playerModelSelectionActives.Add(go);
            }

            RedrawPlayerModel();
        }

        public void PlayerModelSelect(int team, int id)
        {
            Kit_ThirdPersonPlayerModel model = game.allPvpTeams[team].playerModels[id].prefab.GetComponent<Kit_ThirdPersonPlayerModel>();

            if (allLoadouts[currentlySelectedLoadout].teamLoadout[team].playerModelID != id)
            {
                //Assign
                allLoadouts[currentlySelectedLoadout].teamLoadout[team].playerModelID = id;
                //Customization slots
                allLoadouts[currentlySelectedLoadout].teamLoadout[team].playerModelCustomizations = new int[model.customizationSlots.Length];
            }
            else
            {
                //Now this is where thigns can go wrong. We have to make SURE that the length is good AND that even if it is good, no invalid options are picked.

                //Check if length matches.
                if (allLoadouts[currentlySelectedLoadout].teamLoadout[team].playerModelCustomizations.Length != model.customizationSlots.Length)
                {
                    allLoadouts[currentlySelectedLoadout].teamLoadout[team].playerModelCustomizations = new int[model.customizationSlots.Length];
                }
                else
                {
                    //Make sure no invalid options are picked.

                    for (int i = 0; i < allLoadouts[currentlySelectedLoadout].teamLoadout[team].playerModelCustomizations.Length; i++)
                    {
                        int cId = i;
                        //Clamp, a slot with 0 customizations is illegal anyway and a configuration error.
                        allLoadouts[currentlySelectedLoadout].teamLoadout[team].playerModelCustomizations[cId] = Mathf.Clamp(allLoadouts[currentlySelectedLoadout].teamLoadout[team].playerModelCustomizations[cId], 0, model.customizationSlots[cId].customizations.Length - 1);
                    }
                }
            }

            //Switch to customization menu :)
            if (allLoadouts[currentlySelectedLoadout].teamLoadout[team].playerModelCustomizations.Length > 0)
            {
                if (!SwitchMenu(playerModelCustomizationCategoryScreenId)) return;

                for (int i = 0; i < playerModelCustomizationCategoryActives.Count; i++)
                {
                    Destroy(playerModelCustomizationCategoryActives[i]);
                }

                playerModelCustomizationCategoryActives = new List<GameObject>();

                for (int i = 0; i < model.customizationSlots.Length; i++)
                {
                    int cId = i;

                    //Create
                    GameObject go = Instantiate(playerModelCustomizationCategoryPrefab, playerModelCustomizationCategoryGo, false);
                    //Setup text
                    TextMeshProUGUI txt = go.GetComponentInChildren<TextMeshProUGUI>();
                    if (txt) txt.text = model.customizationSlots[cId].name.GetLocalizedString();
                    //Setup Button
                    Button btn = go.GetComponentInChildren<Button>();
                    btn.onClick.AddListener(delegate { PlayerModelCustomizeSlot(team, id, cId); });
                    //Add to list
                    playerModelCustomizationCategoryActives.Add(go);
                }
            }

            RedrawPlayerModel();
        }

        public void PlayerModelCustomizeSlot(int team, int id, int slot)
        {
            SwitchMenu(playerModelCustomizationScreenId, true);

            //Get the model
            Kit_ThirdPersonPlayerModel model = game.allPvpTeams[team].playerModels[id].prefab.GetComponent<Kit_ThirdPersonPlayerModel>();
            //Look at the right thing
            playerModelRenderCamPosition = playerModelCurrent.customizationSlots[slot].uiPosition.position - playerModelRenderCam.transform.forward * playerModelRenderCamCustomizationDistance;

            for (int i = 0; i < playerModelCustomizationActives.Count; i++)
            {
                Destroy(playerModelCustomizationActives[i]);
            }

            playerModelCustomizationActives = new List<GameObject>();

            for (int i = 0; i < model.customizationSlots[slot].customizations.Length; i++)
            {
                int cId = i;

                //Create
                GameObject go = Instantiate(playerModelCustomizationPrefab, playerModelCustomizationGo, false);
                //Setup text
                TextMeshProUGUI txt = go.GetComponentInChildren<TextMeshProUGUI>();
                if (txt) txt.text = model.customizationSlots[slot].customizations[cId].name.GetLocalizedString();
                //Setup Button
                Button btn = go.GetComponentInChildren<Button>();
                btn.onClick.AddListener(delegate { PlayerModelChangeCustomize(team, slot, cId); });
                //Add to list
                playerModelCustomizationActives.Add(go);
            }
        }

        public void PlayerModelChangeCustomize(int team, int slot, int newCustomization)
        {
            //Update loadout
            allLoadouts[currentlySelectedLoadout].teamLoadout[team].playerModelCustomizations[slot] = newCustomization;
            //Only update customization
            RedrawPlayerModel(true);
        }

        public void RedrawPlayerModel(bool onlyUpdateCustomization = false)
        {
            if (!onlyUpdateCustomization)
            {
                if (playerModelCurrent)
                {
                    Destroy(playerModelCurrent.gameObject);
                }

                GameObject playerModel = Instantiate(game.allPvpTeams[currentSelectedTeamForPlayerModel].playerModels[allLoadouts[currentlySelectedLoadout].teamLoadout[currentSelectedTeamForPlayerModel].playerModelID].prefab, playerModelPreviewGo, false);

                playerModelCurrent = playerModel.GetComponent<Kit_ThirdPersonPlayerModel>();

                //Setup IK helper
                if (playerModelCurrent.anim)
                {
                    playerModelIkHelper = playerModelCurrent.anim.gameObject.AddComponent<Kit_LoadoutIKHelper>();
                    playerModelIkHelper.anim = playerModelCurrent.anim;
                    playerModelIkHelper.applyIk = false;
                }

                //Set Anim Type
                playerModelCurrent.SetAnimType(game.allWeapons[allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].weaponID].thirdPersonAnimType, true);

                RedrawWeapon();
            }
            //Apply customization
            playerModelCurrent.SetCustomizations(allLoadouts[currentlySelectedLoadout].teamLoadout[currentSelectedTeamForPlayerModel].playerModelCustomizations, null);
            RedrawWeapon();
        }

        public void RedrawWeapon()
        {
            if (weaponPreviewObjectThirdPerson)
            {
                //Destroy old one
                Destroy(weaponPreviewObjectThirdPerson);
            }

            //Create new third person one
            weaponPreviewObjectThirdPerson = Instantiate(game.allWeapons[allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].weaponID].thirdPersonPrefab, playerModelCurrent.weaponsInHandsGo, false);

            //Set Anim Type
            playerModelCurrent.SetAnimType(game.allWeapons[allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].weaponID].thirdPersonAnimType, true);

            Weapons.Kit_ThirdPersonWeaponRenderer tpWpnRender = weaponPreviewObjectThirdPerson.GetComponent<Weapons.Kit_ThirdPersonWeaponRenderer>();

            //Set attachments
            if (tpWpnRender)
            {
                tpWpnRender.SetAttachments(allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].attachments, game.allWeapons[allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].weaponID] as Weapons.Kit_ModernWeaponScript, null, null);

                if (tpWpnRender.leftHandIK.Length > 0)
                {
                    playerModelIkHelper.leftHandGoal = tpWpnRender.leftHandIK[Mathf.Clamp(playerModelCurrent.inverseKinematicID, 0, tpWpnRender.leftHandIK.Length - 1)];
                    playerModelIkHelper.applyIk = true;
                }
                else
                {
                    playerModelIkHelper.applyIk = false;
                }
            }

            if (weaponPreviewObjectFirstPerson)
            {
                Destroy(weaponPreviewObjectFirstPerson);
            }

            weaponPreviewObjectFirstPerson = Instantiate(game.allWeapons[allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].weaponID].firstPersonPrefab, weaponPreviewFirstPersonGo, false);

            Weapons.Kit_WeaponRenderer wpnRender = weaponPreviewObjectFirstPerson.GetComponent<Weapons.Kit_WeaponRenderer>();

            if (wpnRender)
            {
                if (wpnRender.anim) wpnRender.anim.enabled = false;

                for (int i = 0; i < wpnRender.animAdditionals.Length; i++)
                {
                    wpnRender.animAdditionals[i].enabled = false;
                }

                if (wpnRender.legacyAnim) wpnRender.legacyAnim.enabled = false;

                for (int i = 0; i < wpnRender.hideInCustomiazionMenu.Length; i++)
                {
                    wpnRender.hideInCustomiazionMenu[i].enabled = false;
                }

                wpnRender.transform.localPosition = wpnRender.customizationMenuOffset;

                wpnRender.SetAttachments(allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].attachments, game.allWeapons[allLoadouts[currentlySelectedLoadout].loadoutWeapons[currentSelectedWeaponCategory].weaponID] as Weapons.Kit_ModernWeaponScript, null, null);
            }

            Weapons.Kit_MeleeRenderer mlRender = weaponPreviewObjectFirstPerson.GetComponent<Weapons.Kit_MeleeRenderer>();

            if (mlRender)
            {
                if (mlRender.anim) mlRender.anim.enabled = false;
                if (mlRender.legacyAnim) mlRender.legacyAnim.enabled = false;

                for (int i = 0; i < mlRender.hideInCustomiazionMenu.Length; i++)
                {
                    mlRender.hideInCustomiazionMenu[i].enabled = false;
                }

                mlRender.transform.localPosition = mlRender.customizationMenuOffset;
            }

            Weapons.Kit_GrenadeRenderer grRender = weaponPreviewObjectFirstPerson.GetComponent<Weapons.Kit_GrenadeRenderer>();

            if (grRender)
            {
                if (grRender.anim) grRender.anim.enabled = false;
                if (grRender.legacyAnim) grRender.legacyAnim.enabled = false;

                for (int i = 0; i < grRender.hideInCustomiazionMenu.Length; i++)
                {
                    grRender.hideInCustomiazionMenu[i].enabled = false;
                }

                grRender.transform.localPosition = grRender.customizationMenuOffset;
            }
        }

        #region Save Load
        /// <summary>
        /// Did we load at least ONCE already?
        /// </summary>
        private bool wasLoaded;

        public void Load()
        {
            for (int i = 0; i < allLoadouts.Length; i++)
            {
                int id = i;

                //Check if a saved loadout for this slot is present
                if (PlayerPrefs.HasKey("loadout_" + id + "_weapons"))
                {
                    int amountOfWeapons = PlayerPrefs.GetInt("loadout_" + id + "_weapons", 0);

                    //Slot configuration matches. Very important!
                    if (game.allWeaponCategories.Length == allLoadouts[id].loadoutWeapons.Length)
                    {
                        for (int j = 0; j < allLoadouts[id].loadoutWeapons.Length; j++)
                        {
                            int jd = j;

                            int savedWeapon = PlayerPrefs.GetInt("loadout_" + id + "_weapon_" + jd, 0);
                            string savedweaponName = PlayerPrefs.GetString("loadout_" + id + "_weapon_" + jd + "_name", "");

                            //Check if loaded weapon is valid
                            if (savedWeapon < game.allWeapons.Length)
                            {
                                //Check if it is the same weapon
                                if (game.allWeapons[savedWeapon].name == savedweaponName)
                                {
                                    //It is the same weapon, assign it!
                                    allLoadouts[id].loadoutWeapons[jd].weaponID = savedWeapon;

                                    //Attachment loading
                                    int[] savedAttachments = PlayerPrefsExtended.GetIntArray("loadout_" + id + "_weapon_" + jd + "_attachments", 0, 0);

                                    Weapons.Kit_ModernWeaponScript wpnRender = game.allWeapons[savedWeapon] as Weapons.Kit_ModernWeaponScript;

                                    //Kit_ModernWeaponScript attachments
                                    if (wpnRender)
                                    {
                                        //Check if size matches
                                        if (savedAttachments.Length == wpnRender.attachmentSlots.Length)
                                        {
                                            //Size matches, assign
                                            allLoadouts[id].loadoutWeapons[jd].attachments = savedAttachments;
                                            //Then clamp!
                                            for (int o = 0; o < allLoadouts[id].loadoutWeapons[jd].attachments.Length; o++)
                                            {
                                                int od = o;
                                                allLoadouts[id].loadoutWeapons[jd].attachments[od] = Mathf.Clamp(allLoadouts[id].loadoutWeapons[jd].attachments[od], 0, wpnRender.attachmentSlots[od].availableAttachments.Length - 1);
                                            }
                                        }
                                        else
                                        {
                                            //Doesn't match, reset.
                                            allLoadouts[id].loadoutWeapons[jd].attachments = new int[wpnRender.attachmentSlots.Length];
                                        }
                                    }
                                    else
                                    {
                                        //No attachments supported, doesn't matter.
                                        allLoadouts[id].loadoutWeapons[jd].attachments = new int[0];
                                    }
                                }
                            }
                        }
                    }

                    int amountOfTeams = PlayerPrefs.GetInt("loadout_" + id + "_teams", 0);

                    //Team configuration matches
                    if (amountOfTeams == allLoadouts[id].teamLoadout.Length)
                    {
                        for (int j = 0; j < allLoadouts[id].teamLoadout.Length; j++)
                        {
                            int jd = j;
                            int savedPlayerModel = PlayerPrefs.GetInt("loadout_" + id + "_pm_" + jd, 0);

                            //Check if it's a valid one
                            if (savedPlayerModel < game.allPvpTeams[jd].playerModels.Length)
                            {
                                string savedPlayerModelName = PlayerPrefs.GetString("loadout_" + id + "_pm_" + jd + "_name", "");

                                //Check if it's still the same one
                                if (game.allPvpTeams[jd].playerModels[savedPlayerModel].name == savedPlayerModelName)
                                {
                                    //It is! Assign it!
                                    allLoadouts[id].teamLoadout[jd].playerModelID = savedPlayerModel;

                                    Kit_ThirdPersonPlayerModel model = game.allPvpTeams[jd].playerModels[savedPlayerModel].prefab.GetComponent<Kit_ThirdPersonPlayerModel>();

                                    //Load customization
                                    int[] savedPlayerModelCustomization = PlayerPrefsExtended.GetIntArray("loadout_" + id + "_pm_" + jd + "_customization", 0, 0);

                                    //Check if size of customizations matches
                                    if (savedPlayerModelCustomization.Length == model.customizationSlots.Length)
                                    {
                                        //Size matches, assign
                                        allLoadouts[id].teamLoadout[jd].playerModelCustomizations = savedPlayerModelCustomization;
                                        //Then clamp
                                        for (int o = 0; o < allLoadouts[id].teamLoadout[jd].playerModelCustomizations.Length; o++)
                                        {
                                            int od = o;
                                            allLoadouts[id].teamLoadout[jd].playerModelCustomizations[od] = Mathf.Clamp(allLoadouts[id].teamLoadout[jd].playerModelCustomizations[od], 0, model.customizationSlots[od].customizations.Length - 1);
                                        }
                                    }
                                    else
                                    {
                                        //It doesn't, create new array
                                        allLoadouts[id].teamLoadout[jd].playerModelCustomizations = new int[model.customizationSlots.Length];
                                    }
                                }
                            }
                        }
                    }
                }

            }

            int selectedLoadout = PlayerPrefs.GetInt("loadoutSelected", 0);

            //Check if it can be selected
            if (selectedLoadout < allLoadouts.Length)
            {
                currentlySelectedLoadout = selectedLoadout;
            }

            wasLoaded = true;
        }

        public void Save()
        {
            if (wasLoaded)
            {
                for (int i = 0; i < allLoadouts.Length; i++)
                {
                    int id = i;
                    PlayerPrefs.SetInt("loadout_" + id + "_weapons", allLoadouts[id].loadoutWeapons.Length);
                    for (int j = 0; j < allLoadouts[id].loadoutWeapons.Length; j++)
                    {
                        int jd = j;
                        PlayerPrefs.SetString("loadout_" + id + "_weapon_" + jd + "_name", game.allWeapons[allLoadouts[id].loadoutWeapons[jd].weaponID].name);
                        PlayerPrefs.SetInt("loadout_" + id + "_weapon_" + jd, allLoadouts[id].loadoutWeapons[jd].weaponID);
                        PlayerPrefsExtended.SetIntArray("loadout_" + id + "_weapon_" + jd + "_attachments", allLoadouts[id].loadoutWeapons[jd].attachments);
                    }

                    PlayerPrefs.SetInt("loadout_" + id + "_teams", allLoadouts[id].teamLoadout.Length);

                    for (int j = 0; j < allLoadouts[id].teamLoadout.Length; j++)
                    {
                        int jd = j;
                        PlayerPrefs.SetString("loadout_" + id + "_pm_" + jd + "_name", game.allPvpTeams[jd].playerModels[allLoadouts[id].teamLoadout[jd].playerModelID].name);
                        PlayerPrefs.SetInt("loadout_" + id + "_pm_" + jd, allLoadouts[id].teamLoadout[jd].playerModelID);
                        PlayerPrefsExtended.SetIntArray("loadout_" + id + "_pm_" + jd + "_customization", allLoadouts[id].teamLoadout[jd].playerModelCustomizations);
                    }
                }

                PlayerPrefs.SetInt("loadoutSelected", currentlySelectedLoadout);
            }
        }
        #endregion

        #region SubMenu
        /// <summary>
        /// Switch to the given menu
        /// </summary>
        /// <param name="newMenu"></param>
        /// <returns></returns>
        public bool SwitchMenu(int newMenu)
        {
            if (!isSwitchingScreens)
            {
                //Start the coroutine
                currentlySwitchingScreensTo = StartCoroutine(SwitchRoutine(newMenu));
                //We are now switching
                return true;
            }

            //Not able to switch screens
            return false;
        }

        /// <summary>
        /// Switch to the given menu
        /// </summary>
        /// <param name="newMenu"></param>
        /// <returns></returns>
        public bool SwitchMenu(int newMenu, bool force)
        {
            if (!isSwitchingScreens || force)
            {
                if (force)
                {
                    if (currentlySwitchingScreensTo != null)
                    {
                        StopCoroutine(currentlySwitchingScreensTo);
                    }

                    //Make sure all correct ones ARE disabled
                    //Disable all the roots
                    for (int i = 0; i < subMenus.Length; i++)
                    {
                        if (i != currentSubScreen)
                        {
                            if (subMenus[i].root)
                            {
                                //Disable
                                subMenus[i].root.SetActive(false);
                            }
                        }
                    }
                }

                //Start the coroutine
                currentlySwitchingScreensTo = StartCoroutine(SwitchRoutine(newMenu));
                //We are now switching
                return true;
            }

            //Not able to switch screens
            return false;
        }

        private IEnumerator SwitchRoutine(int newMenu)
        {
            //Set bool
            isSwitchingScreens = true;
            //Fade out screen
            //Play Animation
            subMenus[currentSubScreen].anim.Play("Fade Out", 0, 0f);
            //Wait
            yield return new WaitForSeconds(subMenus[currentSubScreen].fadeOutLength);
            subMenus[currentSubScreen].root.SetActive(false);

            //Fade in new screen
            //Set screen
            currentSubScreen = newMenu;
            //Disable
            subMenus[currentSubScreen].root.SetActive(true);
            //Play Animation
            subMenus[currentSubScreen].anim.Play("Fade In", 0, 0f);
            //Wait
            yield return new WaitForSeconds(subMenus[currentSubScreen].fadeInLength);
            //Done
            isSwitchingScreens = false;
        }
        #endregion
    }
}
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace MarsFPSKit
{
    public class Kit_LoadoutPlayerModelCategory : MonoBehaviour
    {
        /// <summary>
        /// Event trigger to get the hover!
        /// </summary>
        public EventTrigger eventTrigger;
        /// <summary>
        /// Dropdown button
        /// </summary>
        public Dropdown dropdown;
        /// <summary>
        /// Customize button
        /// </summary>
        public Button customizeButton;
        /// <summary>
        /// Team name
        /// </summary>
        public Text teamText;
    }
}
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace MarsFPSKit
{
    public class Kit_LoadoutWeaponCategory : MonoBehaviour
    {
        /// <summary>
        /// Event trigger to get the hover!
        /// </summary>
        public EventTrigger eventTrigger;
        /// <summary>
        /// Picture of the currently selected weapon
        /// </summary>
        public Image currentWeaponImage;
        /// <summary>
        /// Dropdown that has all weapons
        /// </summary>
        public Dropdown weaponsInDropdown;
        /// <summary>
        /// Converts <see cref="weaponsInDropdown"/> to global ones
        /// </summary>
        public List<int> dropdownLocalToGlobal = new List<int>();
        /// <summary>
        /// The button that triggers the customize
        /// </summary>
        public Button customizeWeaponButton;
        /// <summary>
        /// How this category is called
        /// </summary>
        public Text weaponCategoryName;
        /// <summary>
        /// Statistics root object (to hide or unhide dependent on weapon)
        /// </summary>
        public GameObject statsRoot;
        /// <summary>
        /// Damage stats
        /// </summary>
        public Image statsDamageFill;
        /// <summary>
        /// Fire Rate stats
        /// </summary>
        public Image statsFireRateFill;
        /// <summary>
        /// Recoil stats
        /// </summary>
        public Image statsRecoilFill;
        /// <summary>
        /// Reach stats
        /// </summary>
        public Image statsReachFill;
    }
}
fix the errors. Check all scripts. I want the weapon prifab to be picked up and change the primary weapon (which is does) this should also work for bots. It should be possible to kill bots and players with the picked up weapon without any error. It should also be possible for bots to kill other bots and players when they pick it up.

I do not want to edit original MMFPSE scripts. create 100% of a script that is fully compatible with mmfpse scripts. Show me step by step how to integrate that.