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.
Asked
Active
Viewed 700 times
0
-
Are you using the unity UI or you want to use OnMouseDown Messages? – High Nov 13 '17 at 16:12
-
OnMouseDown Messages – Dev-kun Nov 13 '17 at 16:17
-
1If that is a UI then the best practice is to use uGUI instead. What you are doing is incorrect for a UI. See https://docs.unity3d.com/Manual/UISystem.html – Pino De Francesco Nov 13 '17 at 16:18
1 Answers
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. :)
- 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);
}
}
- create GameObject and add ButtonCountainer to that.
- now add sprites as child.
- end. we have lunch.

High
- 606
- 1
- 6
- 19