- Home /
Toggle Boolean Function
Hi there, I'm just trying to create a function where I can specify a variable I want to toggle on and off using a parameter and then toggle that variable. I'm using C#.
I keep getting an error saying I can't convert a 'string' to a 'bool'. Here's what I've got so far.
public bool variableA = true;
public bool variableB = true;
public bool variableWithADifferentNameC = true;
public void InvertBoolean (string booleanString)
{
if (booleanString)
{
booleanString = false;
} else {
booleanString = true;
}
}
void RandomFunction ()
{
InvertBoolean("variableA");
InvertBoolean("variableB");
InvertBoolean("variableWithADifferentNameC");
}
Any help is much appreciated.
P.S. It doesn't like lines 7, 9 and 11.
Answer by Sisso · May 21, 2013 at 03:24 PM
Line 7, if statement requires a boolean. You must explicity verify what you consider a valid string.
booleanString == null
booleanString == ""
booleanString.Length > 0
Line 9,11, strings are not boolean, you could not assign a boolean into a string.
booleanString = "true";
This is a basic programing concept. I really recommend to find a programing tutorial.
Answer by nventimiglia · May 21, 2013 at 03:28 PM
Yeah, you are no where near correct. Im hesitant to correct your error because its not that your code is wrong so much as your mindset and understanding of C# is wrong.
public class Test
{
public bool variableA = true;
public bool variableB = true;
public bool variableWithADifferentNameC = true;
public void InvertBoolean(bool arg)
{
// warning, value assigned is not used.
arg = !arg;
// Try reading the difference between structs and objects
}
void RandomFunction()
{
InvertBoolean(variableA);
InvertBoolean(variableB);
InvertBoolean(variableWithADifferentNameC);
}
}
I get that much. What I'm asking is if there's an alternative way of doing the same kind of thing? Perhaps using Casting or something. But I don't know how you would do it syntax-wise. This seems like such a basic thing, of using a string to identify a boolean variable name, but I can't find an alternative solution.
I would rethink your solution. That said, you can use reflection.
GetType().GetField("variableA").GetValue(this);
GetType().GetField("variableA").SetValue(this, arg);
Your answer
Follow this Question
Related Questions
Static Variable Problem 1 Answer
Sharing booleans between 2 scripts 1 Answer
How can I change a mecanim animation by pressing a key? 1 Answer
if several variables is true then do function 2 Answers
How to find variable status? 1 Answer