- Home /
How to convert a string to a boolean?
I want to convert "true" to true.
I have seen the mono help at http://msdn.microsoft.com/en-us/library/system.convert.toboolean.aspx but when I try this I get an error ("Unkown Identifier")
I get the same error with Boolean.Parse.
Can anyone help?
Thanks!
Have you tried outputting the variable? I think Debug.Log(BooleanVariable) would output either true or false.
"$$anonymous$$ Identifier" doesn't sound like a conversion problem. Can you share your script, there may be something else wrong.
Answer by Bunny83 · Apr 15, 2014 at 11:48 PM
All you have to do is comparing the string to "true":
//C#
bool mybool = someString == "true";
A lot people forget that the compare operators return a boolean value which you can use in an if-statement or assign it to a variable of type bool.
Some prefer to put some brackets like this:
//C#
bool mybool = (someString == "true");
You can use "System.Convert.ToBoolean(someString)" as well, but keep in mind that it only works with the string "True" or "False" and will throw an exception if it contains anything else. My approach will return always false unless it's "true". Keep in mind that you can also check for multiple strings. In this case it's best to wrap them in a method:
//C#
public static bool ToBool(string aText)
{
return aText == "true" || aText == "on" || aText == "yes";
}
Answer by poncho · Mar 14, 2011 at 02:30 PM
if the value you get, always is "true", you can make an if like this
string valueYouGet="";
//by this line your variable, valueYouGet should be "true", by your own means
bool mybool = false;
if(valueYouGet == "true")
mybool = true;
is not exactly a parser, but do the trick
hope this is the answer you are looking for
Answer by Shkarface-Noori · Apr 15, 2014 at 03:00 PM
you simply should import the type System and call Convert.ToBoolean as:
import System;
function Start() {
print(Convert.ToBoolean("True"));
}
and is exactly a parser
well never import system if you really don't need it, not just for converting string to boolean, however if you need it for something heavier, then you can surely use this too
Your answer
Follow this Question
Related Questions
what the hell is a int? (or a float, or boolean, or string!) 3 Answers
Converting a String to Another Object's Boolean 1 Answer
String comparison, can't use false result as string. 4 Answers
How do I change the logged text based on a momentary collision? 1 Answer
Hierarchy search "NOT" modifier? 1 Answer