Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Scripting an image button

Discussion in 'Scripting' started by rainbow_design, Dec 20, 2015.

  1. rainbow_design

    rainbow_design

    Joined:
    Aug 8, 2015
    Posts:
    108
    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)

    Code (CSharp):
    1. for (int y = 0; y < resolutiony; y = y + 1)
    2. {
    3. for (int x = 0; x < resolutionx; x = x + 1)
    4. {
    5. if (modus == 2) { displaymap(i, x, y); }
    6. private void displaymap(int i, int x, int y) {
    7. Sprite mysprite = UnityEngine.Resources.Load<Sprite>("Tiles/" + str(tiname));
    8. GameObject o = Object.Instantiate(hexbasetile);
    9. o.GetComponent<Image>().sprite = mysprite;
    10. o.transform.localPosition = new Vector2(((x * xbase)+xdbase), (y * ybase));
    Now i want to attach something like this:

    On Click call beenclicked(o);


    Code (CSharp):
    1. private void beenclicked(GameObject o){
    The tutorials on this are extremely thin.
    How can i do this from code side?
     
  2. buckius82

    buckius82

    Joined:
    Nov 19, 2013
    Posts:
    40
    If I got this right you map of hex tiles each tile is an object you want to give a class the ability to tell if specific tiles were clicked on. you could attach a class to each tile give it a reverence to the class that will use been clicked. Attach a colider and then use the onmouse () monobehavior method to call the beenpressed function and send its own game object as a parameter.

    Or you can also use delegats and events aswell.
    Hope this helped
     
  3. rainbow_design

    rainbow_design

    Joined:
    Aug 8, 2015
    Posts:
    108
    Thankyou i guess thats an good approach but i dont know how you mean give a reverence, how to configute onmouse() of a collider in script.since i have not worked much with events and classes i dont know how it would look.in code.

    Same for delegats and events. Like i said i have trouble to find something useful in the tutorials.
     
  4. rainbow_design

    rainbow_design

    Joined:
    Aug 8, 2015
    Posts:
    108
    How would code with delegates and events look like?