Lotan
Lotan

Reputation: 4283

How to call UnitySendMessage to an interface method

Working on Android Plugin for Unity.

To communicate from Android to Unity I use UnityPlayer.UnitySendMessage(string s1,string s2, string s3), this method takes as parameters three strings:

  1. s1: GameObject name that will receive the message.
  2. s2: Name of the Method that will handle the message.
  3. s3: The message.

So this setup works, on my android plugin I use the follow code to send the message to my UnityClass:

UnityPlayer.UnitySendMessage("GameObjectName", "OnResult", results);

In Unity, my GameObject with the name "GameObjectName" implements the method:

private void OnResult(string recognizedResult);

Now it comes the trouble

Now I want that this GameObject class implements an interface to make it mandatory the handling of the "OnResult".

BUT if I create the following interface:

//Interface for MonoBehaviour plugin holder
public interface IPlugin
{
    void OnResult(string recognizedResult);
}

And then on my MonoBehaviour class I implement the interface so it looks like:

void IPlugin.OnResult(string recognizedResult)

This approach seems to do not work. I've tried to call UnitySendMessage with both "OnResult" and "IPlugin.OnResult", neither works.

I'm doing something wrong? Or it's just a limitation? Thanks!

Upvotes: 0

Views: 460

Answers (1)

TJHeuvel
TJHeuvel

Reputation: 12608

In C# you can implement interfaces explicitely like you just did, or implicitly. It seems that Unity only recognises the method when its implemented Implicitly.

interface IPlugin
{
    void OnResult(string recognizedResult);

}

class Working : IPlugin
{
    public void OnResult(string recognizedResult)
    {
        throw new System.NotImplementedException();
    }
}

class NoWorking : IPlugin
{
    void IPlugin.OnResult(string recognizedResult)
    {
        throw new System.NotImplementedException();
    }
}

Upvotes: 1

Related Questions