I am learning about delegates, events, and actions right now and I have a question regarding game objects/scripts that subscribe to event(s)…
My understanding of delegates and events, etc. is that the primary benefit to using them is the flexibility/modularity they provide in that game objects do not need explicit references to perform logic when events take place in a game. Essentially, this means you can use these game objects in multiple projects without breaking them because you don’t have to worry about missing references, etc.
The theory here is really powerful and it excites me, haha, but I am wondering whether or not the code will fail to compile if you introduce a game object/script that is actively subscribed to event(s) into a new project where those static events no longer exist. I have not tested this personally, but I have to imagine that the compiler wouldn’t like it?
This is more or less a question of curiosity, because I understand that if you apply a convention to your subscriptions and centralize a location for subscribe tho events (i.e. the start method), if the code failed to compile you could easily open the script and comment out the entire list of subscriptions, but I am curious if anyone knows whether or not the code will fail to compile by default?
Event is very much like a regular field in this regard. If you are referencing a field, method, event, class etc that doesn’t exist, then your code will not compile.
I would argue that main function of events is not being able to reuse code in new project. Or at least not in a way you seem to understand this. I always viewed events as a means to increase encapsulation.
Let’s take a scene loader class as an example. You want to call some methods when you finish loading a scene. You could do this the “easy” way, just get the reference to all the objects and call required methods. But now your scene loader knows all about those other classes and the logic of them while it doesn’t need it for anything. So instead you use events. Now your scene loader will just invoke an event “SceneLoaded” and it doesn’t care who (or if anyone) will do something about it, it’s job here is done.
Of course events help with reusing code in different projects, but I would argue that you are supposed to reuse classes that THROW events, not the ones that are subscribed to them. Of course you can reuse both, but as a general case classes that throw events (like the earlier example, scene loader) will be more generic and reusable.
If the static event doesn’t exist then you’ll get a compilation error before being able to test anything. It would be the same as trying to access a variable or method from another class where the variable or method do not exist in that script.
So yeah, it would throw an error by default.