BroadcastMessage string reference workaround

Hi, I wanted to share my way of avoiding string references with BroadcastMessage, since it’s so easy to make mistakes with strings. For other non-BroadcaseMessage situations I’d normally use a static class of string constants, but I thought I needed a better way for BroadcastMessage where the compiler can check method names and whatnot. So, hopefully this might be useful to someone :grin:

I created an interface that includes a method with the OnDamageTaken() signature:

public interface IDamageResponder {
	void OnDamageTaken();
}

Then instead of calling BroadcastMessage with the string reference, I call this line which takes advantage of the compiler, so we can be sure there are no mistakes from string references:

BroadcastMessage(nameof(IDamageResponder.OnDamageTaken));

Finally, any class that wants to listen to the broadcast (such as the EnemyAI) can then implement the IDamageResponder interface, and the compiler will force us to implement the OnDamageTaken method.

image

It’s not perfect but I find it useful for preventing any issues arising if we need to change any method names in the future. I’d love to hear any other ways to achieve this kind of result too! :grin:

4 Likes

while this works it think there are better option , like implementing an event system that broadcast when an entity takes damage, something like :

class DamageEventSystem
{
    public static Action<GameObject> OnDamageTaken;
}

Then on the enemy health script can rise the event

public class EnemyHealth: MonoBehaviour
{
void TakeDamage()
{
DamageEventSystem.OnDamageTaken(this).Invoke();
}

}

and everywhere else that needs this information can subscribe to the event and do whatever they need to do when this happens

public class EnemyAI: MonoBehaviour
{
void Start()
{
DamageEventSystem.OnDamageTaken+=HandleDamageTaken;

}
void HandleDamageTaken(GameObject go)
{
// make sure the object that took damage is this one
if(go != this.gameObject)
return;

//Do whatever you need to do when damage is taken here
}
}

I’m not sure if there may be flaws with this tho, but i feel like it’s less hacky that searching script name at compile time

Events are a good way to do this, but the course uses the built-in BroadcastMessage which is what the original post is about.

Privacy & Terms