- Home /
initiate Imagebuttons in loop
Hello, i have a prefab which is an image and creates a map in a loop and i want to attach a click receiver. Right now it looks like this (this is not the complete code just a part to give you an idea)
 for (int y = 0; y < resolutiony; y = y + 1)
 {
 for (int x = 0; x < resolutionx; x = x + 1)
 {
 if (modus == 2) { displaymap(i, x, y); }
 private void displaymap(int i, int x, int y) {
 Sprite mysprite = UnityEngine.Resources.Load("Tiles/" + str(tiname));
 GameObject o = Object.Instantiate(hexbasetile);
 o.GetComponent().sprite = mysprite;
 o.transform.localPosition = new Vector2(((x * xbase)+xdbase), (y * ybase));
Now i want to attach something like this: On Click call beenclicked(o);
 private void beenclicked(GameObject o){
The tutorials on this are extremely thin. How can i do this from code side?
Please provide me some example code or a link! : with instructions only i will not be able to do much. The Essential question is how can i execute a function from a button
Answer by corn · Dec 21, 2015 at 04:36 PM
Well, the easiest way would be to have a UI Button attached to your prefab. Then you can retrieve it in your script with a simple GetComponent() call, and listen to its OnClick UnityEvent.
 // Get your prefab's button
 Button b = o.GetComponent<Button>();
 // Assign your sprite to the button as its graphic component
 b.image = mysprite;
 
 // Add a listener to your button's OnClick UnityEvent
 b.OnClick.AddListener(myCallback);
 
 void myCallback() 
 {
   //Called whenever b is clicked
 }
Alternatively, you could also attach a script to your prefab that raises an event whenever it detects a click, with
 UnityEvent onClick = new UnityEvent();
 
 if ( Input.GetMouseButtonDown(0) )
 {
   onClick.Invoke();
 }
And add a listener to yourscript.onClick in the same manner.
If you're not familiar with UnityEvents, check the manual.
Oh thankyou. However i think i missed one little detail. I would like to pass o to myCallback on click
You can call an UnityEvent with arguments, so one way to do it would be to invoke the script's GameObject.
 class GameObjectEvent : UnityEvent<GameObject> { }
 GameObjectEvent onClick = new GameObjectEvent();
 onClick.Invoke(this.gameObject);
And modify your callback accordingly :
 void myCallback(GameObject go) 
 {
   // do stuff
 }
Your answer
 
 
             Follow this Question
Related Questions
How to Change transparency of button image in Unity 5.0? 3 Answers
Is their any way to save a particle system when it's not instantiated yet? 2 Answers
Button's sprite swap works fine but it doesn't change the related image's source image! why? 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                