- Home /
Deriving and integer from a boolean
In the process of trying to short hand a script i've come to an intresting question. Is there a way to derive a 0, or 1 from a boolean? I need this to acess an array.
var state : boolean;
var audioState : AudioClip[];
function Update(){
audio.clip = audioState[state];
}
Answer by Wuzseen · Aug 13, 2013 at 09:59 PM
Unity/C#/Javscript does not have this feature built in. Unlike, say, C or C++ where a boolean is just a glorified zero/non-zero value.
However there is a shorthand by using the ternary/conditional operator:
value = value + (boolean ? 1 : 0);
This is probably the most concise way to do it. It is equivalent to using if statements with the boolean but it's very short and to the point.
Thanks! I've seen this syntax before. You don't have do answer this, but is there anywhere where I can learn more about using this kind of syntax?
There's really not much to learn about it, this wikipedia article shows it pretty well by converting if statements to their ternary equivalent: http://en.wikipedia.org/wiki/%3F:
But it's basically just:
question ? trueDoThis : falseDoThis;
Answer by IgorAherne · Aug 13, 2013 at 10:00 PM
function BoolToInt(boolean inputBool){
if( ! inputBool)
return 0;
else
return 1;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613112139im_/https://answers.unity.com/themes/thub/images/avi.jpg)