Hello, I have a silly question.
On these two ways of writing the code for a button, is there a big difference?
For me, apart from a micro character optimization, there is none.
public void ButtonClick()
{
myVariable=!myVariable;
if (myVariable)
{...}
else
{...}
}
public void ButtonClick()
{
if (myVariable)
{myVariable=false;}
else
{myVariable=true;}
}
In the second example you are checking the variable and then changing it, whereas in the first you are changing it and then checking it. Order of operation is the only real difference I can see.
1 Like
#JeffDUnity3D
In the example of using a button with two click states, we need an else
.
If you want to invert a boolean you can just someBoolean = !someBoolean
.
Yes as I put it in example 1 ^^
How would you do without “ELSE” in this case (mute button) :
public void ButtonClicked ()
{
isMute =!isMute;
if (isMute)
{
audioSource.mute = true;
}
else
{
audioSource.mute = false;
}
}
Okay yeah, was hard to see with the lack of proper formatting.
In any case, just use the boolean to assign the value.
isMute = !isMute;
audioSource.mute = isMute;
1 Like
Sorry, but I try to be careful with the formatting.
Wow you’re too strong , I hadn’t thought of that ^^
but who says button says image and suddenly comes back to the same place.
public void ButtonClicked ()
{
isMute =!isMute;
if (isMute)
{
audioSource.mute = true;
button.image.sprite = img1;
}
else
{
audioSource.mute = false;
button.image.sprite = img2;
}
}
You can use a ternary operator if you want.
isMute = !isMute;
audioSource.mute = isMute;
button.image.sprite = isMute == true ? img1 : img2;
However I wouldn’t worry about stuff like this. You’ll learn it the more time you spend coding.
1 Like
So… my brain is exploding xD thank you very much for this info, even if it’s going to take me a good while to integrate them 8/
1 Like
dlorre
June 23, 2022, 10:28am
10
Don’t forget about setters, setters can make your code so much simpler:
public bool IsMute {
get {
return isMute;
}
set {
isMute = value;
audioSource.mute = value;
}
}
then:
IsMute = !IsMute;
this is enough.
1 Like
Thank you dlorre , I told you I was going to study get and setter, but I haven’t had time yet ^^