- Home /
How do I catch the SendMessage Has No Reciever exception thrown when I try to run a function with SendMessage that does not exist?
I'm making a game with a command line where you can tell different objects to run different functions.
If they send a function call to an object that doesn't exist, I give them a custom error message through my command line.
But when they send a function that doesn't exist to an object that does, I can't catch the exception. In the following code, noun is the object and verb is the command. For example, open door is split into verb, noun respectively.
if (GameObject.Find(noun.ToUpper()))
{
try
{
GameObject.Find(noun.ToUpper()).SendMessage("COM_" + verb, password);
jukebox.PlayOneShot(jukebox.library["command_accepted2"]);
}
catch//THIS NEVER RUNS
{
Print("ERROR: " + noun + " does not have '"+verb+"' as a function.");
jukebox.PlayOneShot(jukebox.library["command_rejected2"]);
}
}
else
{
Print("ERROR: Object '" + noun.ToUpper() + "' was not found.");
jukebox.PlayOneShot(jukebox.library["command_rejected2"]);
}
How do I catch the "SendMessage has no receiver!" exception, OR how do I detect beforehand if an object has the verb function within?
inb4 don't use sendmessage, in my case it's the best option.
Send$$anonymous$$essage doesn't raise an exception as such when no receivers are found, it just prints an error message.
I guess you could use reflection to check if the verb function exists.
Despite your inb4 comment, I can't help thinking that interfaces might be a better approach.
Could you suggest how reflection could do that in the form of an answer please?
Reflection is a standard C# feature. You should be able to find lots of non-Unity "find all the functions" examples, which are much better than anyone is going to quickly write for you here.
I'd suggest keeping possible commands in a string array or a dictionary with reference to what to do. It's easier editable, you can just iterate the list to see if the command exist, populate it in the inspector for easy adjustment...
Answer by AlienNova · Oct 26, 2017 at 09:07 PM
Sorry to necro a thread but since I ended up here so might some other people.
You can't try SendMessage ()
and catch if it throws a no receiver error. The best thing I found was to try dynamically invoking a message and catching the error through it. https://www.codeproject.com/Articles/19911/Dynamically-Invoke-A-Method-Given-Strings-with-Me
How ever this is extremely circumventive so I really don't like doing it, but it's the best I could find.
Your answer
Follow this Question
Related Questions
IAP generates exception when calling m_StoreController.InitiatePurchase(product) 0 Answers
Calling a function in another script not working with yield 1 Answer
Try Catch not working with VideoPlayer 2 Answers
Error on my javascript code 1 Answer
Calling a function from a different script on the same object 1 Answer