0

I made and empty game object that I use for a container for my sprites, which are my buttons. I want to know which sprite I just clicked with one script on my container so I can add more buttons later and not have to alter the code.

derHugo
  • 83,094
  • 9
  • 75
  • 115
Dev-kun
  • 59
  • 5

1 Answers1

0

Many way can doing that. my solution:

i Create Button Script to handling the OnMouseDown but i don't add it to child because i add it with the Container code.

then in ButtonContainer script get all child and add BoxCollider2D and Button to theme and important part is Adding your listener(DoSomthing method).

Done. :)

  1. create a script Button:
using UnityEngine;
using UnityEngine.Events;

public class Button : MonoBehaviour
{
    private SpriteRenderer sr;
    public MouseDownEvent mouseDown = new MouseDownEvent();

    void Awake(){
        sr = GetComponent<SpriteRenderer>();
    }

    void OnMouseDown(){
        mouseDown.Invoke(sr);
    }
}

[System.Serializable]
public class MouseDownEvent : UnityEvent<SpriteRenderer> { }

2.create a script for ButtonCountainer

using UnityEngine;

public class ButtonContainer : MonoBehaviour
{
    private void Awake()
    {
        // get all child
        var childs = GetComponentsInChildren<Transform>();

        // add button class to them
        for (int i = 0; i < childs.Length; i++) {
            // child element
            var go = childs[i].gameObject;
            // add boxcolliser2d. (child must have collider to invoke the OnMouseDown Message)
            go.AddComponent<BoxCollider2D>();
            // add button script to them
            var b = go.AddComponent<Button>();
            // do everything you want with this event
            b.mouseDown.AddListener(DoSomthing);
        }
    }
    // every time this gameObject invoke sr = sprite renderer of the that gameObject
    private void DoSomthing(SpriteRenderer sr)
    {
        Debug.Log(sr.name);
    }
}
  1. create GameObject and add ButtonCountainer to that.
  2. now add sprites as child.
  3. end. we have lunch.
High
  • 606
  • 1
  • 6
  • 19