SendMessage Slows down Unity Dramatically

So i have been working on a game for awhile and SendMessageUpwards has never been much of a problem for me. The script has a variable, containing the main camera of the scene, called playerCam.

playerCam.SendMessageUpwards("Message", gameObject);

this line incredibly decreases the speed at which unity runs. Anybody know a solution to this?

I hate to state the obvious, but not using SendMessage sounds like a start to a solution to me!

We did tests in work and it takes about 100x the time to call a SendMessage than calling the method directly.

There’s plenty of ways around this but it will involve recursively searching parents of parents; I’d probably use some kind of Interface coupled with (also slow, but not so awful as SendMessage) a GetComponent to call the method.

SendMessage takes so long because it uses reflection, which is slow, to check all MonoBehaviours on the target (iirc). SendMessageUpwards does this to all parents, so it’s even slower than SendMessage unless it’s in the root of your scene, and slower still as you get deeper and deeper in the hierarchy.

If you’re only using SendMessageUpwards because you want to tell one object a specific thing then you have two really easy options:

  • If you’re instantiating these objects in code then add a reference to the target in the MonoBehaviour that you’re calling SMU from, and when you instantiate the object(s) set the target as you need.
  • If you’ve got these objects in your hierarchy already then add serialized (inspector-assignable) properties to them and assign the target in edit mode.

You may be able to use a variation on this using an array if you have more than one target.

Food for thought anyway…

Probably you dont need to send the object every frame, you could do a variable like

var lastObjectSent: GameObject

if( lastObjectSent == thisObjectToSent ) return; this idea helped me a lot

Since this is on the front page again it’s worth noting that SendMessage has been replaced by the event system from 4.6 onwards. The event system uses interfaces to allow calling of methods on other GameObjects.