How to check which button was clicked from script.
Hi, I'm making a crafting system with the new UI system. It consists of a list of buttons representing the items to be crafted, and i created a script that contains the logic for changing the database(for all the craftables).
public class CraftManager : MonoBehaviour {
public GameObject mainPanel;
public Button[] buttons = new Button[17];
public Text infoText;
public Text remarkText;
public void CraftStuff()
{
Debug.Log("OnClick reference worked!");
if (gameObject == buttons[0])
{
Debug.Log("Button found, crafting stuff");
if (PlayerStats.Scrap >= 2)
{
PlayerStats.Scrap -= 2;
PlayerStats.Metal += 1;
}
else
{
remarkText.text = ("Not enough resources.");
}
}
if (gameObject.CompareTag("TimberButton"))
{
if (PlayerStats.Wood >= 2)
{
PlayerStats.Scrap -= 2;
PlayerStats.Metal += 1;
}
else
{
remarkText.text = ("Not enough resources.");
}
}
}
(This is the script I have so far)
The problem is this: I can not find a way to reference the correct part of the script when a certain button is pressed. (ie. When the button for ITEM 1 is pressed, the script should change the values of items like in the first IF statement of the script, for ITEM 2, it should do as in the second IF statement, and so on). I assigned the CraftStuff() method to execute when I click the button, (OnClick()), and it executes it(The first Debug string is displayed), but does not do anything else. The values of the items do not change, the second Debug string is not displayed(although the button is tagged properly). My problem is, that I cannot make out a way to differentiate between the buttons from script. I tried referring to them by tag, or making an array of buttons, but neither works.
If there is still not enough information, I will try to add more. I don't get any errors, it just simply does not do anything.
This question is very vague. Please be more specific about what the problem is and include any relevant code samples or errors you're getting.
@Dinosaurs : I added the necessary info. Hope it helps. Cheers.
Answer by Dinosaurs · Nov 19, 2015 at 10:09 PM
You can either create 2 different methods (CraftWood() and CraftMetal() for example) and call them from the different buttons, or pass a parameter from the button when it's clicked.
The Unity UI tutorial explains how to do this https://unity3d.com/learn/tutorials/modules/beginner/ui/ui-button
Your answer
Follow this Question
Related Questions
UI Button OnClick() Will not Trigger Function Call 0 Answers
C# On Click sound to play before loading scene 0 Answers
Help with buttons 0 Answers
unity 2018.3.12f1 Button OnClick call function on another instance? of script 0 Answers
How can I make mobile UI buttons fire when first touched rather than released? 0 Answers