Array of buttons , and get their IDs
Okey, i'm making calculator and i want when you click on button 1 or whatever other number to put button text to my text that is named input. So i made this public :
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Glavnaskripta : MonoBehaviour {
public Text unos3;
public Button[] button;
private string stringunosa;
public Text rezultat;
public void InputNumber()
{
int i;
for(i = 0; i < 10; i++)
{
if(button[i].isActiveAndEnabled)
{
string b = button[i].GetComponentInChildren<Text>().text;
unos3.text = b.ToString ();
}
}
}
So basically i want to know which button is pressed and add his text to Input.
Any help?
You have picture down there how it looks.
Answer by andrei2699 · Jul 25, 2016 at 11:05 AM
There are several ways to achieve what you want, but all involve the same method :
public void OnButtonClick(int id)
{
// The id is the text of the button.
unos3.text = (id+1).ToString();
}
The first method is to do it by scripting:
void Start()
{
for(int i=0;i<button.Length;i++)
{
button[i].onClick.AddListener(() => OnButtonClick(i+1));
}
}
The second way is to add the function in the inspector :
You choose a button, you look in the inspector at the Button component and there you will see OnClick. Finally, you will add the object that contains the script with the OnButtonClick method and choose the method.
Note: the buttons from the array should be ordered. The button with the number 1 should be first and the one with number 9 should be last.
For more information about the first way, visit this link.
For more information about the second way, visit this link.