Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

weapon switching unity

using UnityEngine;

public class WeaponSwitching : MonoBehaviour
{
    public int selectedWeapon = 0;

    // Start is called before the first frame update
    void Start()
    {
        selectWeapon();
    }

    // Update is called once per frame
    void Update()
    {
        int previousSelectedWeapon = selectedWeapon;

        if(Input.GetAxis("Mouse ScrollWheel") > 0f)
        {
            if(selectedWeapon >= transform.childCount - 1)
                selectedWeapon = 0;
            else
                selectedWeapon++;
        }
        if(Input.GetAxis("Mouse ScrollWheel") < 0f)
        {
            if(selectedWeapon <= 0)
                selectedWeapon = transform.childCount - 1;
            else
                selectedWeapon--;
        }

        if(Input.GetKeyDown(KeyCode.Alpha1))
        {
            selectedWeapon = 0;
        }

        if(Input.GetKeyDown(KeyCode.Alpha2) && transform.childCount >= 2)
        {
            selectedWeapon = 1;
        }
        if(Input.GetKeyDown(KeyCode.Alpha3) && transform.childCount >= 3)
        {
            selectedWeapon = 2;
        }

        if(previousSelectedWeapon != selectedWeapon)
        {
            selectWeapon();
        }
    }

    void selectWeapon()
    {
        int i =  0;
        foreach(Transform weapon in transform)
        {
            if(i == selectedWeapon)
                weapon.gameObject.SetActive(true);
            else
                weapon.gameObject.SetActive(false);
            i++;
        }
    }
}
Comment

PREVIOUS NEXT
Code Example
Csharp :: how to run async void function c# 
Csharp :: raylib c# 
Csharp :: array sort c# 
Csharp :: unity c# get direction of object 
Csharp :: c# dictionary values to list 
Csharp :: get tree node godot 
Csharp :: how to set a transform equal to something unity 
Csharp :: dns ttl meaning 
Csharp :: Gameobject.Find in unityC# 
Csharp :: how to open onscreen keyboard c# 
Csharp :: c# edit element in list 
Csharp :: read file using c# 
Csharp :: sleep in c# 
Csharp :: unity no serializefield 
Csharp :: or c# 
Csharp :: or in if statement c# 
Csharp :: find how many digits a number has 
Csharp :: unity 2d 
Csharp :: minimize maximize restore wpf buttons 
Csharp :: Long, Max and Min value 
Csharp :: array object to datatable c# 
Csharp :: how to acivate a game object unity 
Csharp :: c# csvhelper 
Csharp :: unity get component in parent 
Csharp :: .net core identity get user id 
Csharp :: cs string to enum 
Csharp :: Sort ListBox numerically in C# 
Csharp :: set current date to textbox in asp.net 
Csharp :: unity time scale 
Csharp :: print a file from C# 
ADD CONTENT
Topic
Content
Source link
Name
8+1 =