[SOLVED] Need Help With Weapon Changing Script

Hi Everyone,i need some help with my weapon changing script…Here’s the script:

using UnityEngine;
using System.Collections;

public class wepSwitcher : MonoBehaviour {

    public GameObject[] weps;

    void Awake(){
        changeWep (0);
    }

    void Update(){

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

        if(Input.GetKeyDown (KeyCode.Alpha2)){
            changeWep (1);
        }

        if(Input.GetKeyDown (KeyCode.Alpha3)){
            changeWep (2);
        }


    }

    public void changeWep(int seq){
        disableAll ();
        weps [seq].SetActive (true);
    }

    public void disableAll(){
        foreach (GameObject wep in weps) {
            wep.SetActive (false);
        }
    }

}

it works fine and changes weapons on pressing Keyboard buttons but i wanna change weapon with touch buttons.i wanna have a single onGUI or any touch button which can change my weapon…and when it reaches at the last weapon it should reset back to 1st weapon is there any way how i can do it…Any Help would be appreciated!..

One way could be,
add int currentIndex=0; variable there,

then if you press 1: set currentIndex=0; and call changeWep();
then if you press 2: set currentIndex=1; and call changeWep();
then if you press 3: set currentIndex=2; and call changeWep();

and from UI button, you would call this to activate next weapon:

public void NextWeapon()
{
    // wrap around between 0 to max items
    currentIndex=++currentIndex % weps.length;
    changeWep();
}
1 Like

Worked Perfectly Like a Charm…! Thank You So Much mgear Here’s the working script :

using UnityEngine;
using System.Collections;

public class wepSwitcher : MonoBehaviour {

    public GameObject[] weps;


    int currentIndex = 0;

    void Awake(){
    //    changeWep (0);
    }

    void OnGUI(){

        if (GUI.Button (new Rect (200, 200, 150, 200),"Next Weapon")){
            NextWeapon ();
        }

    }

    public void NextWeapon()
    {
        // wrap around between 0 to max items
        currentIndex=++currentIndex % weps.Length;
        changeWep(currentIndex);
    }

    void Update(){


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

        if(Input.GetKeyDown (KeyCode.Alpha2)){
            changeWep (1);
        }

        if(Input.GetKeyDown (KeyCode.Alpha3)){
            changeWep (2);
        }


    }

    public void changeWep(int seq){
        disableAll ();
        weps [seq].SetActive (true);
    }

    public void disableAll(){
        foreach (GameObject wep in weps) {
            wep.SetActive (false);
        }
    }

}

Thanks Once Again Bro!..