I'm working with the GMS UI and have a menu structure where a main menu may or may not have a specific submenu. My goal is to check for the existence of a submenu without triggering an error if it doesn't exist.
My current approach is:
Object MB = GetMenuBar()
Object Menu = MB.FindMenuItemByName("Menu")
Object SubMenu = Menu.FindMenuItemByName("SubMenu")
Result(SubMenu.GetName())
The issue is that if the submenu doesn't exist, the call to Menu.FindMenuItemByName("SubMenu")
results in an error, even when I try to wrap the code in a try-catch block.
Questions:
Any insights, workarounds, or example code would be greatly appreciated. Thank you!
Generally, when using functions/methods (such as FindMenuItemByName
) that return references to objects, it is a good idea to use the method ScriptObjectIsValid
to test whether the returned object is valid and to branch one's code accordingly. So in your example, you would probably want to do something like the following:
Object MB = GetMenuBar()
Object Menu = MB.FindMenuItemByName("Menu")
if (Menu.ScriptObjectIsValid())
{
Object SubMenu = Menu.FindMenuItemByName("SubMenu")
if (SubMenu.ScriptObjectIsValid())
Result(SubMenu.GetName() + "\n")
else
Result("No sub-menu\n")
}
One can also do this via try-catch, but it's not particularly clearer (or cleaner), as follows:
Object MB = GetMenuBar()
Object Menu = MB.FindMenuItemByName("Menu")
if (Menu.ScriptObjectIsValid())
{
try
{
Object SubMenu = Menu.FindMenuItemByName("SubMenu")
Result(SubMenu.GetName() + "\n")
}
catch
{
Result("No sub-menu\n")
break
}
}