- Home /
Unity SendMessage with Parameter not working
Dear Unity Answers Community,
Though the title is somewhat unclear, I think I can explain it easily below: My mouse input simply checks if it hit an object, if it does. It sends a message to the object and stores the object in a variable. When the mouse input hits another object, I wanted to send a message with the already defined object as parameter. So the receiving script can target that object. Here are the two functions that matter:
void MouseClick(){
beginMousePosition = Input.mousePosition;
panVector = GetMousePos ();
Ray ray = Camera.main.ScreenPointToRay(beginMousePosition);
RaycastHit hit ;
if (Physics.Raycast (ray, out hit)) {
if(hit.collider.transform.tag == "SelectionCollider"){
GameObject objectToSend = selectedObject;
hit.transform.SendMessage("OnSelected", objectToSend);
selectedObject = hit.transform.gameObject;
}
else {
if(selectedObject != null){
hit.transform.SendMessage("OnSelected");
selectedObject = null;
}
}
}
}
Receiving function:
void OnSelected(){
if(!selected){
Select ();
} else {
UnSelect();
}
}
void OnSelected(GameObject selectedObject){
Debug.Log ("Not receiving in this function");
if (!selected) {
Select();
} else {
if(selectedObject == null){
UnSelect();
}
else {
HandleSecondSelect(selectedObject);
}
}
}
The first time I select an object with my mouse, it enters the empty receiving function as it needs to. However the second time (when the objectToSend has a reference) it's also received in the empty receiving function.
Does anybody know why the 1 parameter receiving function doesn't get triggered?
Thanks in advance,
Greatings Matti.
I'm not sure if Send$$anonymous$$essage plays nice with overloaded functions. You might need two distinct names to call, or you could pass null, or find some other workaround.
I've added the overloaded functions later, because when I didn't have the empty parameter function, unity gave an error saying that the receiver asks for 1 parameter. Which I most certainly passed with Send$$anonymous$$essage. I know there are some workarounds, but this approach would really be nice in my case. Edit: There was a case when I passed down null, im going to check if that was the problem. 2nd Edit: Didn't seem to be the problem.
Just pass null when you don't want to pass an object (line 14 in your first code snippet). You already have a null check in the receiver, so that Should Just Work.
Whenever I see a usage of Send$$anonymous$$essage
, I ask, "Why not delegates?"
Call 2 functions with two distinct names, how rutter has already write.
Your answer

Follow this Question
Related Questions
A node in a childnode? 1 Answer
SendMessage has no receiver (SmartFox) 1 Answer
SendMessage to another specific GameObject? 1 Answer
iPad touch scripting... 0 Answers