Call a function When a bool changes value?
I'm trying to call an animation/sound when a bool becomes true. How can I do that when it changes from false to true and not simply every frame that it is true?
$$anonymous$$ake unity event and when your bools turn to true then invoke your event or what you want.
Answer by Hellium · May 18, 2017 at 07:29 AM
Use properties : https://msdn.microsoft.com/en-us/library/aa288470(v=vs.71).aspx
private bool myBool ;
public bool MyBool
{
get { return myBool ; }
set
{
if( value == myBool )
return ;
myBool = value ;
if( myBool )
{
// Play sound
}
}
}
Ok. I kind of get it... which bool do I use in the rest of the code? I see we make a bool function and a regular bool, which one should I use to set true/false?
You have to use the property (getter and setter) i.e : $$anonymous$$yBool
Hello,
How could I reuse this code for a high number of booleans, like 100, or maybe an array of booleans?
Thanks in advance!
private bool arrayOfBool = new bool[100];
public void SetBoolValue( bool value, int index )
{
if( index < 0 || index >= arrayOfBool )
throw new System.ArgumentOutOfRangeException("Index value must be between 0 and " + arrayOfBool.Length );
if( arrayOfBool[index] == value )
return ;
arrayOfBool[index] = value ;
if( arrayOfBool[index] )
Foo() ;
else
Bar() ;
}
Thanks for the quick answer.
Would I have to call the method periodically with a timer in order to check the value of the booleans?
Note, though, that these properties CAN NOT LONGER be shown in the properties editor.
The Unity inspector never shown properties unless you create the appropriate custom inspector because of the potential side effects (like the one in my answer).
However, you can make the "inner variable" visible in the inspector by adding a tag above it in your code:
[SerializeFiled]
private bool myBool ;
Obviously, changing the value in the inspector won't call the setter.
Okay I know this reply is 3 years ago already. but I think this code just checks when you change the $$anonymous$$yBool variable and not the myBool variable. It's kinda redundant compared to this, isn't it?
private bool myBool;
public void $$anonymous$$yBool()
{
if (myBool)
{
myBool = false;
}
else
{
myBool = true;
// Play Sound
}
}
would do the same? If not what would be the difference, optimization wise?
$$anonymous$$y main question is ,how can I check the myBool variable and not call $$anonymous$$yBool? because both of our codes is based on calling $$anonymous$$ybool as an event.
Answer by toddisarockstar · May 19, 2017 at 01:54 AM
here is a simple answer with an "if" statement if you don't want to get into custom classes.
bool mybool;
bool checkit;
void Update(){
if(mybool!=checkit){
checkit=mybool;
print("my bool has changed to: "+ mybool);
if(mybool==true){
//do stuff here
}
}
}
Excellent! I was looking for exactly this myself. Thanks!