Hey guys, I am creating a piano type system that will use the keyboard to use notes while playing the game. I do not want to have 10+ if checks to see if a player has pressed a button so is there any way I can make a manager that can handle events like this?
Sorry for not providing complete example code, but this is how I would solve the problem:
- Create a prefab (Unity - Manual: Prefabs) as a template for the button.
- In GUI, create horizontal layout group (Unity - Manual: Horizontal Layout Group) as a parent for all these buttons.
- Implement the manager (I Shall Call It.. SomethingManager) which contains references (Unity - Scripting API: SerializeField) for the prefab of the button and parent for button instance (the manager component can be put on the parent itself).
- In Awake (https://unity3d.com/learn/tutorials/modules/beginner/scripting/awake-and-start) method I would instantiate the prefab for each button (Unity - Manual: Instantiating Prefabs at run time) and change their parents to the parent with layout (Unity - Scripting API: Transform.SetParent)
- For each instance, you can find the button script (
Button button = instance.GetComponent<Button>()
) and add listener to it’s onClick method (Unity - Scripting API: UI.Button.onClick).
Notes:
-
If you want to change content of the button, there are multiple ways:
-
Find the item (for example Text (http://docs.unity3d.com/ScriptReference/UI.Text.html) with GetComponentInChildren (Unity - Scripting API: Component.GetComponentInChildren)) and change it
-
Implement special component for the button which is put on root and have instances for components which needs to change (that’s how I would do it)
-
For adding listener for the button, you can use C#'s anonymous function (Anonymní funkce (Průvodce programováním v C#) | Microsoft Learn) for example:
public void CreateInstances() { for(int i = 0; i < 10; ++i) { GameObject prefabInstance = Object.Instantiate(buttonPrefab); Button button = prefabInstance.GetComponent<Button>(); button.onClick.AddListener(() => { OnButtonClicked(i); }); } } public void OnButtonClicked(int buttonIndex) { // ... }
for (int i = 0; i <= 20; i++)
{
GameObject button = Instantiate(buttonTemplate);
image = Resources.Load<Sprite>("iconsCPL/"+i.ToString());
texturelist.Add(Resources.Load<Texture>("iconsCPL/" + i.ToString()));
var prefabsimage = button.gameObject.transform.GetChild(0);
prefabsimage.GetComponent<Image>().sprite = image;
button.SetActive(true);
button.GetComponent<ButtonListButt>().SetIndex(i);
button.transform.SetParent(buttonTemplate.transform.parent,false);
button.gameObject.GetComponent<Button>().onClick.AddListener(delegate () { PrintText(button); });
}
}
public void PrintText(GameObject g)
{
float i = g.GetComponent<ButtonListButt>().GetIndex();
int index = g.GetComponent<ButtonListButt>().GetIndex();
i = i / 25;