Hey all. I’m using the UI Toolking to try to make a simple Game Over screen with 2 buttons, a ‘Retry’ button that will respawn the player and an ‘Exit’ button that will close the game. Placing everything in the unity editor has worked so far, but I’m having trouble with code in the script to control the buttons.
So far I’ve gotten the Exit button to work, but I can’t get the Retry button to work, as I’m getting a Null Reference on the variable retryButton. However, the exitButton variable works just like its supposed to. I’ve quadruple checked spelling and everything else I can think of and can’t figure it out. Code below:
var root = GetComponent<UIDocument>().rootVisualElement;
exitButton = root.Q<Button>("exit-button");
retryButton = root.Q<Button>("retry-button");
exitButton.clicked += ExitButtonPressed;
retryButton.clicked += RetryButtonPressed; // Doesn't work because retryButton variable is null.
This is all in the Start() method. ExitButtonPressed and RetryButtonPressed are both functions further down in the script. Though I’m unsure why they don’t need parentheses at the ends. All variables are declared further up and there are no compiling errors or red squiggles.
Most likely because your query isn’t finding it. Double check the spelling on your string for its query.
You could also define your own button classes and use them in the UI builder instead: https://docs.unity3d.com/Manual/UIB-structuring-ui-custom-elements.html
Then you can either query them in a strongly typed fashion, or just code all the functionality into the button itself and omit the query entirely.
I’ve checked it multiple times and haven’t found what’s wrong. I’ll keep checking, recreate the button if I need to, and see how that works. Thanks!
Copied and pasted the name of the button from the UI Toolkit window into the script and that seemed to fix it. I swear to the coding gods that the names were identical already, so I don’t know what to say.
Side note that the code that queries for controls in a UIDocument should be in OnEnable and not Start of your Monobehaviour class. But also seems like you had some character encoding issues from it now working all of a sudden, which is quite intriguing! In any case, moving your code will be safer
2 Likes
Oooh, I didn’t know that. Why is it preferable that OnEnable be used instead of Start?
Thanks, Julia!
Because the UI gets recreated during OnEnable, so it’s more guaranteed that you have the actual elements that are currently shown in the UI and not previous ones that got wiped and recreated.
1 Like