How can I detect/catch the SendMessageOptions.RequireReceiver error message?

SendMessage is kind of antiquated. The way to do things today is to make an interface.

That way you say “is there this interface?” and check if it’s not null, then call the method you want if it is.

Don’t be afraid, it’s pretty simple, and it’s way more powerful. Here, soooper-quickly:

// stick this in its own file, usually IMyInterface.cs
public interface IMyInterface
{
  void MyMethod( int arg1, string arg2);
}

Now, in whatever Monobehaviors you have, you implement that interface, which basically involves:

  1. put that interface after a comma right after MonoBehavior in the class header:
public class FooClass : Monobehavior, IMyInterface
{
}
  1. make a public version of the above function in the FooClass, with body:
public void MyMethod( int arg1, string arg2)
{
// do your stuff!
}

Now, to find this interface you say:

var imyInterface = GetComponent<IMyInterface>();

and to potentially call it you do:

if (imyInterface != null)
{
  imyInterface.MyMethod( 1, "yabo!");
}

That’s it! Read more if you like but that is the tl;dr of using C# interfaces in Unity3D.

4 Likes