So I have two scripts, a JS and a CS.
My CS script has a function:
static void ChangeVar(bool var)
{
if(var)
testVar = true;
}
My JS script has a line that gets executed:
object.BroadcastMessage("ChangeVar", true);
I get an error saying there is no receiver, not sure why.
The setup of these two scripts is:
The JS is attached to an object that at the top has a line of code:
public var object : GameObject;
the object that has the CS attached to it is on the gameobject that is put into “object”.
I figured this was enough for BroadcastMessage to work.
What am I doing wrong?
SendMessage affects all scripts on the calling game object.
BroadcastMessage affects all scripts on the calling game object and its children.
SendMessageUpwards affects all scripts on the calling game object and its ancestry.
If you want game object X to BroadcastMessage to game object Y, you’ll need Y to be its child (or be its parent and use SendMessageUpwards).
Also, you don’t need to use object, you can just BroadcastMessage("ChangeVar", true)
and it will be caught by any scripts on the object or its children with that function.
By default, these messaging operations will throw an error if no one is listening to them. This error can be avoided with SendMessageOptions, like so:
BroadcastMessage("ChangeVar", true, SendMessageOptions.DontRequireReceiver);
EDIT: per alternative
If your game is such that you cannot alter the hierarchy of the objects in question, you can refer directly to the script on the other object by name, and call the function directly, using GetComponent
for example, instead of BroadcastMessage, you could use:
object.GetComponent("OtherScript").ChangeVar(true);
Where ‘OtherScript’ is the name of the actual changevar script, minus the extension. If you expect to use this component again later, it is advised that you store object.GetComponent("OtherScript")
in a variable for quick use.