Hi all.
Im wondering, if i use the OnMouseOver Event, how can the GameObject detect / or receive info from the Clicking GameObject (in this case the Player).
In this special case, the Object which is clicked or hovered shall compare Varaiables from the Player with variables stored in the hovered Object.
How would the Object receive these Infos from Player?
Thanks to you all.
Greetings
Nin
You need to look into C# delegates, actions and events. Watch this tutorial Events - Unity Learn for basic understandig.
Also Unity has own UnityEvents Unity - Scripting API: UnityEvent .
There is small example with 2 scripts for your case:
ClickableObject
has event Click
which will be fired in some specific moment (in this case - Left Mouse Button Click). Player
can subscribe on this event and manipulate with received data (string with clicked object`s name).
public class ClickableObject : MonoBehaviour
{
public event Action<string> Click;
void OnMouseOver()
{
if (Input.GetMouseButton(0))
{
if (Click != null)
{
//fire event
Click(gameObject.name);
}
}
}
}
public class Player : MonoBehaviour
{
public ClickableObject obj1;
public void ClickableObjectHandler(string name)
{
Debug.Log("Player clicked on: " + name);
}
void Start()
{
//subscribe on event
obj1.Click += ClickableObjectHandler;
}
}