Alternative to SendMessage

First, let me say that I wouldn't ask without doing some research myself. However, there's nothing specific (or at least enough so that I would understand) on the matter.

At first, I was trying to implement a SendMessage system so that "Spell" could kill the "Enemy".

Sendmessage("Function", #)

And then on the Enemy:

function Function(var : int)
...bunch of ifs

Basically, depending on the element of the Spell the Enemy will react a certain way.

While trying to implement SendMessage (I was having issues referencing the clone, and not the prefab) I've come across several people recommending avoiding SendMessage altogether for a better alternative.

In this scenario, what's the better alternative?

Thank you in advance for your wisdom.

Nobody should recommend avoiding SendMessage for a "better" alternative. Calling functions directly is faster than SendMessage, but that doesn't necessarily make it better. If SendMessage is appropriate for what you're doing and you don't need to call it a huge number of times then there's no reason to avoid it.

One alternative I have used to SendMessage is to have a class (or an abstract class) that extends MonoBehaviour that basically describes the behavior and properties that encapsulates those related facets of the entity and has the method you want. Then use the GetComponent<> method or GetComponentInChildren<>. If it's not found then you don't bother sending the "message".

For example, if I wanted a GameObject to be able to be hit and damaged in the game I would define a class (or abstract if there were going to be multiple strategies) maybe called 'Hittable' or something that had methods like 'public void TakeHit(WeaponType type, int force)' and properties like 'public float HitPointOffset' and other things like these.

The advantages of this approach are that it requires a much stronger (compile time) contract between the sender and receiver than SendMessage even if you specify that a recipient is required. Also, I suspect that SendMessage uses reflection to check for the method on each MonoBehaviour (and invokes it) so from that perspective being able to do a selective broadcast by GetComponentInChildren<>() and then calling your method on those found may buy you a little efficiency. I wouldn't read to much into the efficiency thing though as I think Unity uses the SendMessage approach a whole lot internally. I am not sure that this is 'better' but I like it because of the strong contract and easy refactoring.

Hope some of that helps.

Yeah as previously stated, dont use SendMessage. Use GetComponent<> with interfaces. You get type safety way more speed. Since you are calling typed methods through an interface you can also have listeners respond back with results. Take a look at my ComponentBase.cs which handles getting all the listeners and adds way more granular control to scoping for GetComponent. Unity base component for fast communication ยท GitHub