I want to know is it possible to access functions of object like Start, Update,OncollisionEnter of other objects class in another class. if the answer is yes please tell me how can i do that.
Thank you fr helping
Your question is bit unclear, if you are asking to get access in a way that you can execute it by yourself like other common methods, then I would ask why you want so, if you can implement your own methods?
But if you are asking to get notified if Start
,OnCollisionEnter
of other script is called, then you are actually want to listen those specific events. For that purpose I'd recommend to implement delegate
.
Here is the short example for delegate
implementation.
// Class AA
public delegate void OnAAMessagesDelegate(string methodName);
public static event OnAAMessagesDelegate OnAAMessagesListener;
void Start()
{
if (OnAAMessagesListener != null)
OnAAMessagesListener("Start");
}
void OnCollisionEnter(Collision collision)
{
if (OnAAMessagesListener != null)
OnAAMessagesListener("OnCollisionEnter");
}
Now you can listen that delegates in other class
// Class BB
void OnEnable()
{
AA.OnAAMessagesListener += OnAAMessages;
}
void OnDisable()
{
AA.OnAAMessagesListener -= OnAAMessages;
}
// Signature should be same as delegate's signature
void OnAAMessages(string methodName)
{
switch (methodName){
case "Start":
Debug.Log("AA's Start called");
break;
case "OnCollisionEnter":
Debug.Log("AA's OnCollisionEntercalled");
break;
}
}
delegate
's would be the perfect solution. Let me know if you are still confuse in implementing delegate
\$\endgroup\$
You might have noticed that the Unity event methods are usually declared as private, so they can not be called directly from the outside. Then how does the Unity Engine itself call those methods?
By using the SendMessage function. This method uses introspection to call the named method in all components which derive from MonoBehaviour
, no matter how its visibility is declared. You can use that method, too. There is a caveat, though: It will call the method on all components, but maybe you only want to call it on one.
Another thing you can do when the method is implemented in a script you control is declare the event handler method as public
. It can then be called directly. The visibility on the event handler does not interfere with Unity's own event management.