Hello
I am trying to learn the subject of Delegates and events in unity.
I have seen this example on:
The examples there are quite good and simple to understand so i followed it…
in the delegate/events it uses the following example:
public class Clicker : MonoBehaviour
{
// Event Handler
public delegate void OnClickEvent(GameObject g);
public event OnClickEvent OnClick;
// Handle our Ray and Hit
void Update ()
{
// Ray
Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition);
// Raycast Hit
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100))
{
// If we click it
if (Input.GetMouseButtonUp(0))
{
// Notify of the event!
OnClick(hit.transform.gameObject);
}
}
}
}
And now to reference the delegate from our other scripts that are listening to the call:
Other script:
public class GoldPile : MonoBehaviour
{
// Awake
void Awake ()
{
// Start the event listener
Clicker.Instance.OnClick += OnClick;
}
// The event that gets called
void OnClick(GameObject g)
{
// If g is THIS gameObject
if (g == gameObject)
{
Debug.Log("Hide and give us money!");
// Hide
gameObject.active = false;
}
}
}
Now, what i am asking?
It seems to be that if you have like 100 GoldPile Scripts attached to objects.
Everytime i “GetMouseButtonUP(0)” it will call 100 times the 100 scripts (since u have 100 objects of GolePile) to check if its a GoldPile gameobject. it seems to be inefficient and could cause slowdowns if you have like 1,000 GoldPiles.
I want to learn Delegates & Events, but i also want to learn how to use them the right way.
I would love to learn from your experience.