Calling different voids on OnClick() based on bool values, string values etc.
I have a button that I want to call different public voids based on whether a bool is true or false, or a string = something, etc. When I passed the if statements into the assigned onClick () void in the inspector they seemed to never actually check the values, but return the else Debug.Log instead.
Answer by dacarrera · Nov 11, 2019 at 02:08 AM
Some clarifications might help you get to your solution. You don't call void
since void
is a return type. So you're calling functions (with void
as a return type, i.e. no return value) from OnClick()
. Next, you want to check if some conditions are true (string = something, etc.).
When you're using OnClick()
and assign a function that takes a parameter (in your case, the conditions you're checking), you're limiting yourself to whatever you assign in the editor. When you have a method with a parameter being called with OnClick()
you typically want to have it doing something specific with that one parameter. In your case, this may not be ideal.
So now with your question framed as "How do I call different functions from OnClick()
based on a condition?" you can try the following:
Have the function being called from OnClick()
be without parameters (no arguments). Inside this function, check your conditions and call the appropriate functions.
Example (untested):
// MyNewButtonCall() is what would be called from your OnClick()
// Notice how it doesn't take a bool as an argument and rather checks conditions within
public void MyNewButtonCall()
{
// You can setup your logic here however you want
if("test string" == "something")
{
ChainFunctionOne();
}
else if (boolValue == true)
{
ChainFunctionTwo();
}
}
// Functions you want chained
private void ChainFunctionOne()
{
// do something here
}
private void ChainFunctionTwo()
{
// do something else here...
}
Hope this helps!
This was what I needed and was using basically, but I had a reference issue. I followed the Tic-Tac-Toe tutorial but made a 6x6 board. When I set up the references for the OnClick () I selected all buttons and dragged them to the assign section of OnClick (), so all buttons only referenced a single button. I don't know if there is an easier way, but I one by one dragged each button onto it's own reference to itself in the OnClick (). Everything is working again. Thank you so much. This can either be taken down now or left up for someone who might actually be having a reference issue. Good info in your explanation too. I am new, been fiddling for 6 months now, should really just do more tutorials. Cheers!
Answer by Williamdecologero · Nov 11, 2019 at 04:23 AM
I might just be having a reference issue I guess. I can check public values in update but I can't check them from within anything inside of OnClick() and cannot assign new components. But I am getting my Debug.Logs. out of the same Onclick () assigned function.