I have 3 objects in my Unity scene:
-
Planet
, with scriptPlanet
, propertyactionableModel
and methodstopBuilding()
public class Planet : MonoBehaviour { private GameObject _actionableModel; // ... public void stopBuilding() { // For debugging only Planet planet = GameObject.Find("Planet").GetComponent<Planet>(); Debug.Log(planet.actionableModel); Debug.Log(this.actionableModel); } }
-
Actionable
with scriptActionable
which hasUnityEvent
propertyonClick
, which callsstopBuilding()
on a click eventpublic class Actionable : MonoBehaviour { public class OnClick : UnityEvent<GameObject> { } public OnClick onClick = new OnClick(); // ... void OnMouseDown() { onClick.Invoke(gameObject); } }
-
A Button, which calls
stopBuilding()
on click event.
When stopBuilding()
is invoked by the button click, everything works as expected, both Debug.Log()
calls print the correct actionableModel
. However, when the method is invoked via the Actionable
script, the second log Debug.Log(this.actionableModel)
prints null
(even though this
object is still Planet
for some reason). Since the first log Debug.Log(planet.actionableModel)
still prints the correct value, I assume this is not a problem with the actual value of the property. (I have only a single “Planet” object)
From my experience outside C# and Unity, in which I have only humble experience, I would assume that the context here is improper and that I would need to pass it when I am invoking the method. There seems to be no way to do that though in UnityEvent
object.
How can I invoke the UnityEvent
callback in the same way as Button
does, such that I have access to actionableModel
in stopBuilding
?