Reputation: 189
I wanted to make a game where you click a button and it affects another button. I made a grid. If I click a button in this grid I want to have it affect another button's image. However I need some sort identifier which tells me which button is which.
I'm used prefabs for a button, then made a 5x10 grid prefab of those prefabs. Any guidance towards the right direction would be helpful even if it does not answer the question thank you.
Upvotes: 0
Views: 47
Reputation: 447
This can be done easily
First lets make a script
GridController.cs
Add a reference to the UI namespace at the top using UnityEngine.UI;
Now place all of your grid items in a parent container(can be an empty gameobject)
Now lets start coding
//Reference parent gameobject
[SerializeField]
private GameObject gridContainer;
//List of all child elements
private List<Button> gridObjects = new List<Button>();
private void Start(){
//Loop through all children
for(int i = 0; i < gridContainer.transform.childCount; i++){
//Add button to list
gridObjects.Add(gridContainer.transform.getChild(i).gameObject.GetComponent<Button>());
}
//Set listeners for buttons
for(int i = 0; i < gridObjects.Count;i++){
gridObjects[i].onClick.AddListener(delegate{
DoSomething();
});
}
}
private void DoSomething(){
//Do Something
}
Upvotes: 1