Home > database >  Does UnityEvent creates a dependency on the scripts called
Does UnityEvent creates a dependency on the scripts called

Time:03-25

I know that we should avoid scripts to be dependent of each other. That's why I'm wondering if putting a script in a UnityEvent in the Inspector makes the script which owns this UnityEvent, dependent on the one called.

For instance, I have a script ScriptWithEvent.cs which has a UnityEvent. In the inspector I add an event to this UnityEvent which calls the method Open() inside an other script OtherScript.cs. Inside this script I have another method which changes a component active state linked to a GameObject containing ScriptWithEvent.cs or a public variable inside ScriptWithEvent.cs.

Does this make ScriptWithEvent.cs and OtherScript.cs dependent on each other ? Does UnityEvent creates a dependency on the scripts we make it call ?

CodePudding user response:

No it does not, UnityEvent takes a UnityAction which is a pointer to a method. The script holding the UnityEvent does not know about the type of the method holder nor does it know about the content of the method. In the same way, a C# event would not know about the registered method, only that they need to match the delegate signature.

Your UnityEvent is a list of addresses where to find the methods to be run when invoke is called. But it is totally oblivious to what type it is stored in. The only dependency for UnityEvent is that the method has to be stored in a MonoBehaviour and the method signature has some limitations.

UnityEvent has this advantage over normal C# event, in the latter the subscriber would need to find out how to register to the type or interface UnityEvent via inspector removes that dependency as you can drag anything.

  • Related