In doing some research I found that send message is really not a good thing to use. Unity lets us access C#'s event model, and I’m a big fan of using event-driven programming in general.
Here is an alternate way to wire up the player death sequence using events instead of SendMessage.
The publisher is the new PlayerShipController which handles collision. All we do here is create a delegate that I called DeathAction and then created a public static event of type DeathAction that is called OnDeath.
The static keyword means that I can access it by typing “Class Name”.“Static Object” without needing to instantiate the object that it is defined in.
So PlayerShipController.OnDeath is valid.
When we collide and the trigger fires, we call the StartDeathSequence method. This simply says “if OnDeath has any subscribers attached to it, invoke it”.
In the subscriber (my player ship) when we start the script I subscribe to the event by saying “PlayerShipController.OnDeath += PlayerShipController_OnDeath;”
This says "hey playershipcontroller class, I want to know when you invoke OnDeath. And when you do, you will tell me because I’m now subscribed to you and I will automatically invoke my private void PlayerShipController_OnDeath function.
The really powerful thing about this is that we can have multiple objects subscribed to this one event, and that one event can fire off and update ALL of those objects that are subscribed to it (in this example we are just using the one object subscribed to it)
In PlayerShipController_OnDeath we simply set a boolean _controlsEnabled = false and scream DIEEEE at the console.
In the update method if this bool is true we will handle movement, but the moment it turns false the player loses controls.
Research topics: Event Driven Programming, C# Event, C# Delegates, static keyword (be careful with these, particularly if you venture into the dank and dark forest known as “multithreading”)
I realize that events and delegates are some of the more intermediate to advance topics in modern development but they are one of the central pillars of ALL modern software development and would encourage the adventurous to start peeking at those now because they will be everywhere you look.
Cheers!