Events vs GetComponent for inter-script functionality

I have seen many questions here having answers that give example on how to use GetComponent in order to modify a value in another script, or to call a function on another script. This is pretty much the same thing as passing a reference to another object during the contructor of your object, giving it full reign over that other object.

Now, I’m no programming expert but this bothers me because to me this seems like it’s breaking encapsulation. Your script now has to be aware that the other script exists. This means your script cannot work independently of the other script. This is probably not a big deal on small projects, but I can see this leading to a giant mess with all scripts being intra-dependent on each other to the point where the project won’t even compile should a single script be removed out of the equation.

I would have thought that a safer and more efficient way to make your classes work with each other would be to use events. This way, two classes that communicate with each other can exist without knowing of each other, and still compile and work (without the communication functionality) should one class be unaccessible.

So why is GetComponent seems to be the most popular answer for questions related to “how do I make my script affect this other script?” type questions?

I would think GetComponent is more efficient first because it only requires a reference when the event needs an object, a delegate, also events seems liike a complicated approach as you would also needs a method to he called, well all in all GetComponent seems way easier to me which may be the reason of its popularity.

Having all variables and methods public is also easy, but of course you understand what problems that leads to. I should have been more clear in my question - apart from why GetComponent seems to be so popular, I also want to re-affirm that events is a safer method, and more maintainable in the long-term.

There's no point in checking for null if you can guarantee it won't ever be.

1 Answer

1

Understanding how to directly manipulate other objects is easy to teach, and it will technically allow you to do whatever you want. Unfortunately, a human being doesn’t have the fluid intelligence to keep up with this practice on anything but a trivial amount of code. My opinion is that there are at least two main reasons you see so much of this:

  1. It’s succinct and does the job.
  2. Many people in the community are enthusiasts who have learned bad practices from the examples you’re talking about, and they don’t know that there’s a better way, so they teach the best they know how, which unfortunately isn’t as good as it could be.