Fast Alternative to Unity's SendMessage For Mobile

It seems everywhere on the forums everyone says SendMessage is much to slow for real use within a game, especially in a mobile game on iOS/Android, thus I was wondering what were the alternatives for a messaging system?

Has anyone made a faster messaging system that I could use or are there any examples, suggestions on how to do this? Thanks.

.NET/Mono, and thus Unity, have support for events built into it. msdn c# event - Google Search

I hope nobody actually said that, because it’s not true (unless you’re using it thousands of times per frame or something).

–Eric

Like Eric says, unless you’re going nuts, it likely won’t be a problem. Otherwise, look into events or delegates. delegates are more flexible.

Events are not really an alternative to SendMessage, in an event its the consumer who determines that they get the message, in SendMessage its the provider that determines that the consumer gets the message.

As Eric said SendMessage is generally okay. In many situations a method call is a viable alternative. If you need to message the same component many times then you can store a reference to it.

Just to make sure it’s clear, the provider still determines when and what to send in an event. The consumer would need to subscribe to the event to be able to receive it, but the provider is in control. If you think about it, that’s probably better then sendmessage in that you have more control over who consumes the event.

You would typically use SendMessage to do something like (psuedo code):

OnCollision { other.SendMessage("YouGotHit"); }

You are telling a specific object that something has happened to it. It’s pretty hard to implement that elegantly with events.

In that case, you’re better off calling a function on the object directly. :slight_smile:

If you call a function then you need to know what kind of component you will be calling it on.

Lets say you have a bomb that can hit a player or a building. If you used GetComponent you would then need to have both players and walls inheriting from the same base class.

How about if you want to drag a particle effect on to some objects but not others. You could adjust your Wall class to reference a particle system and then play it from there, but its much easier to have a component that responds to the YouGotHit message by playing the particle effect.

This is exactly what Unity’s Component system and SendMessage are for. I still find myself fighting with it, as I come from the land of business services and strict interfaces, but if you work with it it works to your advantage!

You can use interface to address this also but GetComponentsInChildren doesn’t play nice with interfaces. Personally I still do it this way a lot of the time, but I’m trying to move away from it :slight_smile:

No, because you probably don’t know what the script/scripts is/are called. All you have to do is say SendMessage(“Foo”), and any/all functions called Foo on whatever scripts are on the object are automatically called. You can muck around with reflection to accomplish this, but it will be far more complicated and not really any faster. SendMessage is relatively slow because what it does is fairly complex, but it’s not so slow that you should avoid it if it’s the most appropriate method to use. I don’t actually use it a whole lot, but there are times when it’s a simple and effective thing to do. My only real complaint is that I think the SendMessageOptions default should have been DontRequireReceiver, because I pretty much always have to add that.

–Eric

Nope. That’s what interfaces are for. You use inheritances for " is a " relation and interfaces for "can do/be " relations.

i.e.

public class Animal {
   // base Animal functionality
}
// Dog IS AN animal
public class Dog : Animal {
}

public interface IDamagable {
    void Damage(float damage);
}

// Player CAN BE damaged
public class BasePlayer : IDamagable {
}

// The wall CAN BE damaged
public class Wall : IDamagable {
}

When using interfaces, you only dictate which methods or fields have to be implemented but not how they have to be implemented.

That being said, your bomb would do

void OnCollisionEnter(Collider other) {
    IDamagable damagableObject = GetComponent(typeof(IDamagable)) as IDamagable;
    if(damagableObject!=null) {
        // The colided object does implement IDamangable, it's save to call the method. 
        otherDamagable.Damage(10f);
    }
}

It’s just that Unity’s component model makes interfaces (which are a great thing) somewhat complicated, since the generic GetComponent doesn’t seem to work according to this thread.

Also using SendMessages is pretty messy, it’s somewhat like duck-typing. When you do a SendMessage, the message will be sent to all components attached to the object in question and both methods will be called, even if you only want to call that one that manages the health (to stay at the example above).

To be honest, I think that there are only three reasons for SendMessage
a) Shortcut for badly designed code
b) To overcome the UnityScript ↔ C# compile order issue
c) Patchwork for bad API (see GetComponent(s)[InChildren] method issues and workarounds with Interfaces)

Too bad there is no way to override certain methods of Component/MonoBehaviour, it would solve many of the issues above by overriding some of the Component Methods (i.e. handling the list of components yourself)

@Tseng… I’m well aware of what interfaces are, lets at least look at all my comments:

“You can use interface to address this … Personally I still do it this way a lot of the time …”

Even when using SendMessage I still use interfaces as a way to enforce that a certain object will have some capability.

That said its got nothing to do with being a shortcut for badly designed code; its an alternative paradigm, one that Unity happens to be based on (supported by the fact they use it in all their samples), and which works well in many scenarios (supported by the fact that many of the most popular asset store products use it). Unless you are hitting some point where the (typically negligible) impact of SendMessage is causing a performance issues then you don’t need to avoid it.

PS You can use the generic GetComponent with interfaces, its only GetComponents/GetComponentsInChildren that will start throwing warnings (they still work as long as the class implementing the interface also extends component).

PPS It’s strange arguing against this approach, as I use it all the time. My point is that my pre-conceptions about OO programming have made me avoid SendMessage when in reality the only significant downside is a potential performance hit that is rarely realised.

Just use startcoroutine overload that takes a function name as a string:

StartCoroutine(“DoSomething”, 2.0F);

You don’t need to know the object’s type, and you can pass parameters as well.

@Ben(OP) - This is a classic case of over optimizing. Like Eric pointed out - unless you are doing an enormous amount of calls per frame, the performance of SendMessage is nothing to be concerned with; even on mobile.

As for SendMessage vs Interfaces - don’t get caught up in the performance based arguments either way. Last time I checked, GetComponent on an Interface along with a direct function call was faster than SendMessage, but the difference is negligable unless you’re making a ton of calls like that in a single frame (in which case both are shoddy and you likely want to find a third alternative anyway).

Personally, I use interfaces along with GetComponent 99% of the time. I don’t have any illusion that I do this for performance reasons, I just find that it makes things significantly easier for me, as an individual, to debug and work with. If you find SendMessage easier to work with, or just faster / more convenient to implement for simple things - absolutely go for it.

I know I’m ressurecting an old theard here but:

I need to call methods in Unity (C#) from an Java Android Library with a high frequency. It’s about 60 - 80 calls per second. And I need to pass more than one parameter to the C# method.
Now UnityPlayer.UnitySendMessage() is not a very good solution for this, because first UnitySendMessage() slows down the process and after that I need to split a String in C# to get the different parameters. Both together do slow down my Android game to an unuseable FramesPerSecond.

Now is there any posibility to fix that? How can I use Interfaces in C# from Java or how can I trigger Events for C#. Or is there a way to store a direct access to the C# method in Java?
Any Idea how to solve this problem?

And no - I can’t lower the number of method-calls per second, because it’s about user inputs and it needs to be close to realtime!

EDIT:
Cloud this answer apply to Unity too?
www.codeproject.com/Articles/378826/How-to-wrap-a-Csharp-library-for-use-in-Java