Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

UI Button Controls

Discussion in 'Scripting' started by IDontCare85060, Jul 18, 2015.

  1. IDontCare85060

    IDontCare85060

    Joined:
    Jan 23, 2015
    Posts:
    28
    Hi i was wondering how would i make it so that i could use the UI Button to switch weapons (Since I'm developing for android). Here's the script here :

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using UnityEngine.UI;
    5.  
    6. public class SwitchWeaponsScript : MonoBehaviour
    7. {
    8.  
    9.     public GameObject weapon1;
    10.     public GameObject weapon2;
    11.  
    12.  
    13.  
    14.  
    15.     void Update(GameObject SwitchWeaponButton)
    16.     {
    17.         if (SwitchWeaponButton.GetButtonDown)
    18.         {
    19.             switchWeapon();
    20.         }
    21.     }
    22.  
    23.     void switchWeapon()
    24.     {
    25.         if (weapon1.activeSelf)
    26.         {
    27.             weapon1.SetActive(false);
    28.             weapon2.SetActive(true);
    29.         }
    30.         else
    31.         {
    32.             weapon1.SetActive(true);
    33.             weapon2.SetActive(false);
    34.         }
    35.     }
    36. }
    37.  
    I don't understand if i should use GetButtonDown, GetButtonUp etc. Please Help

    Thanks in advance
     
  2. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Make the switchWeapon() function public and link it to your UI button so whenever you press the button, switchWeapon() will be called.
     
    IDontCare85060 and Kiwasi like this.
  3. phoda

    phoda

    Joined:
    Nov 11, 2014
    Posts:
    384
    You don't need that part in update and as gamer94 said create in editor button and i OnClick() function (right in inspector of button) drag game object to field and select SwtichWeaponsScript > switchWeapon (it has to be public)

    if need more help there are many video tutorials for this
     
    IDontCare85060 likes this.
  4. IDontCare85060

    IDontCare85060

    Joined:
    Jan 23, 2015
    Posts:
    28
    Lol I didn't think of that thanks