Weapon Changing

Hi.
I’m making Android FPS but I don’t know how to change “if (Input.GetKeyDown(“number”))” to button.
Can someone help?

This is my code if needed:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WeaponSwitcher : MonoBehaviour
{
    public GameObject weapon01;
    public GameObject weapon02;
    public GameObject weapon03;
      // Use this for initialization
    void Start ()
    {
        weapon01.SetActive(false);
        weapon02.SetActive(false);
        weapon03.SetActive(true);
    }
   
    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown("1"))
        {
            weapon01.SetActive(true);
            weapon02.SetActive(false);
            weapon03.SetActive(false);
        }
        if (Input.GetKeyDown("2"))
        {
            weapon01.SetActive(false);
            weapon02.SetActive(true);
            weapon03.SetActive(false);
        }
        if (Input.GetKeyDown("3"))
        {
            weapon01.SetActive(false);
            weapon02.SetActive(false);
            weapon03.SetActive(true);
        }
    }
}

Do you have a “Button” component attached to the button you want to use to change the weapon?

(Btw it would be better to store the weapons in an array, especially if you want to add more)

Sorry but I don’t understand this question.
(I don’t speak English very well)

You have a game object in the canvas that is the button for switching weapons, right?
Does is have a “Button” component that looks like this: Screenshot by Lightshot

Btw: Which language do you speak then?

I have buttons to meant to change weapon but they wont work because android doesnt have 1,2 and 3. Script to change weapon is stored in controller and only way to change weapon is using keyboard and I want to use button I made to change weapon

I’m from Poland and I’m 14 years old so Im barelly good in english

First of all, it’s much better to have an array of GameObjects:

public GameObject[] weapons;

Then, you make a function called for example ActivateWeapon(int index):

public void ActivateWeapon(int index) {
    foreach (GameObject weapon in weapons) {
        weapon.SetActive(false);
    }
    weapons[index].SetActive(true);
}

When you have a button like in my screenshot (Screenshot by Lightshot):

  • At the bottom where it says “List is empty”, click on the plus
  • Drag the button game object in the Object field (Screenshot by Lightshot)
  • Select the function in the dropdown menu
  • Type the index of the weapon in the array that you want to select in the input field (Screenshot by Lightshot)
2 Likes

Thanks for help!

Short and helpful.