I’ve been wondering if a code (javascript or C#) could be set up that ‘tricks’ a ui button into acting as thought it were clicked. E.g When a the player (a rigid body, tagged player) enters a trigger collider, or a variable such as life becomes lower than 1, etc.
I’m not necessarily asking for a full on code, just if it can be done, and what function i’d have to use (and which code javascript/C#).
Cheers!
If the desired result is to call the function for the onClick event it is as simple as getting the reference of the button and onClick.Invoke();
As people have posted, it can be done via the Button.onClick.Invoke() … but as a personal rule of thumb (which stems from my experience in using MVC, or “Model-View-Controller” patterns), I’d advise that you shouldn’t.
Doing so can potentially trap you into making confusing/conflicting logic, will increase the scope of a User-interface past what it should be responsible for, can make the UI rather inflexible, and your code won’t be as loosely coupled as it could be (if you worry about that sort of thing)
GUI Elements and their attached viewscripts (as I tend to call them as they represent the “View” in MVC) shouldn’t directly alter the state of the game. Your viewscripts should be allowed to:
- Read any data they need from the gamedata/playerdata (which represents the “Model” in MVC) and game controllers (representing the “Controller” in MVC).
- “Request” to change the state of the game (by calling methods on the controllers, which can choose to ignore the request if its invalid).
The major benefit to this rule is that now the dependency is one-way, your game state and Controller are not required to be aware of the existence of your viewscripts, which makes your controllers more robust, and your UI more modular, allowing you to swap out the UI for different UI on special occasions (for example perhaps you have a Hard Mode that disables or changes the in-game HUD).
Back to the question at hand.
This means that when a button is clicked, it will call a viewscripts OnClick() method (which you will write). and then this OnClick() will “ask” the controller to do the action (as well as update any UI if needed/successful). This means the actual game-changing logic is stored on the controller, so if you want to be able to “trick” a button to being clicked, you simply call the function on the controller that your OnClick() method would call. And the added benefit is that this button doesn’t even need to exist in the first place to get the same functionality.
Why do you need to invoke the onClick?
When you set up your GUI button, you’re probably also giving it a function in a script to call when it’s clicked. Just call that same function from other parts of your code, you don’t need to call the ‘click’ function of the button, just to make the code in there execute.