MissingMethodException: Transform.BroadcastMessage

I’m trying to do a BroadcastMessage on the root of the transform I’m getting from a RaycastHit, but I get the following error: “MissingMethodException: Method not found. UnityEngine.Transform.BroadcastMessage.”

What is going on? The same thing works elsewhere in my scripts with Collisions, but doesn’t work with RaycastHit.

For example this works:

OnCollisionEnter(col:Collision){
   col.transform.root.BroadcastMessage("DoSomething");
}

But this doesn’t:

var hit:RaycastHit 
Physics.Raycast(pos, dir, hit, dist);
hit.transform.root.BroadcastMessage("DoSomething");

If the raycast doesn’t hit anything, I’d expect you’d get errors with that code. Try this:

var hit:RaycastHit 
if( Physics.Raycast(pos, dir, hit, dist) )
{
  hit.transform.root.BroadcastMessage("DoSomething");
}

The example was just a simplification, I’m actually doing Physics.RaycastAll() and looping through the results. If nothing is hit the broadcasts isn’t attempted.

BroadcastMessage has an optional third parameter that specifies what to do when an object doesn’t have the function called by the broadcast. By default, it requires the receiving script to have the right function and throws an error if it doesn’t. However, if you change the parameter to SendMessageOptions.DontRequireReceiver, the message can be sent to an object that can’t respond without any error. This is especially important with BroadcastMessage, since it is easy to send messages to objects unintentionally.

I though having no receiver would give the BroadcastMessage methodName has no receiver! error message? Isn’t unity supposed to catch the MissingMethodException?

Erm… yes, you’re right about that - my mistake!

@Wertymk: can you post the code that doesn’t work exactly as you have it in the script?