Returning value from SendMessage (or something like that)

I just read the docs, and it did not specify whether SendMessage would return a value if the said called function returns one.

If it does not return a value, is there a way to call a function from an entered string without having to have a huge if-else block?

Something like

var enteredString : String = "MyAwesomeFunction";
var number : int = 5;

number = Call(enteredString,number);
enteredString = "MyOtherAwsomeFunction";

number = Call(enteredString,number);

function MyAwsomeFunction (x : int) : int
{
return sin(x);
}

function MyOtherAwsomeFunction (x : int) : int
{
return 1.5cos(x)-sin(x);
}

Thanks!

No, SendMessage cannot return anything. I think you’re pretty much stuck with the giant if/else if or a switch.

Just looked at the docs and it says
function SendMessage (methodName : string, value : object = null, options : SendMessageOptions = SendMessageOptions.RequireReceiver) : void

The “void” at the end means it doesn’t return anything. You could just do another SendMessage inside the function you wish to return something from.

Short of directly calling a method on the object (instead of using SendMessage, example here: Unity - Scripting API: GameObject.GetComponent), then the only way I can conceive of a return value is with the data object. Consider this:

public class SendMessageContext
{
	public var InputData : object;
	public var ReturnValue : object;
}

function MyAwesomeFunction (context : SendMessageContext)
{
	var x : int = int(context.InputData); //I think that's how you cast in JavaScript
	
	context.ReturnValue = sin(x);
}



//elsewhere in your application
var enteredString : String = "MyAwesomeFunction";
var number : int = 5;

var context : SendMessageContext = new SendMessageContext();
context.InputData = number;

targetGameObject.SendMessage(enteredString, context);

var returnedNumber : int = int(context.ReturnValue);

I think this would work (to be honest, I’m pretty sure SendMessage is synchronous/blocking, but I’m not 100% sure). But if you have more than one script with “MyAwesomeFunction” attached to your target GameObject, that same Context object would be passed to each one. This does have a few drawbacks, for one it’s not type-safe (see the integer casting), and secondly it’s a pretty messy/obtuse way of pulling it off.

I think if you can, you should try to use the method demonstrated in that GetComponent help page I linked. If you want to have some method of dynamically invoking various different methods, perhaps investigate using some method delegates (preferred), or possibly employ some polymorphism (though probably overkill in this case).