- Home /
if function broken?
So, here's the code:
public class EP_Instantiate : MonoBehaviour {
public Transform EP_fire;
public Transform EP_earth;
bool EP_fire_active;
bool EP_earth_active;
void Start()
{
bool EP_fire_active = false;
bool EP_earth_active = true;
}
void Update()
{
if(EP_earth_active == false && Input.GetButtonDown("Jump"))
{
Instantiate(EP_fire);
EP_fire_active = true;
}
}
}
I trimmed some unused booleans to make the code more readable. In this situation, I'd expect that the prefab "EP_fire" would not instantiate. However, the prefab does instantiate on input, regardless. Can some one make sense of this?
Answer by Jessespike · Feb 17, 2015 at 08:14 PM
Inside of Start(). Try removing the bool keywords.
void Start()
{
EP_fire_active = false;
EP_earth_active = true;
}
Answer by tanoshimi · Feb 17, 2015 at 08:14 PM
You mean that EP_fire is being instantiated every frame? Or only when you press the Jump key?
If the second, that's expected behaviour. If the first, your Jump key is stuck.
I'm assuming #2, so to explain: EP_earth_active
is false. You declare it on line 5 (actually line 6, but your code formatting is wrong) but don't give it a value, so it's initialised to false by default. bool EP_earth_active;
Then, in Start(), you declare some more variables with the same name and initialise these to true
, but these are locally-scoped only. Correct this by getting rid of your Start() function and instead assign a value to the bools on declaration:
public class EP_Instantiate : MonoBehaviour {
public Transform EP_fire;
public Transform EP_earth;
bool EP_fire_active = false;
bool EP_earth_active = true;
... etc. etc.
Answer by Owen-Reynolds · Feb 17, 2015 at 08:15 PM
If statements aren't broken. You made a regular C# programming mistake somewhere. Track it down the usual way.
Make an IF with each condition by itself, to test. A Unity trick is to make EP_xxx public, so you can see them change in the Inspector. Add print statements (printing out various values, if you need to.) I suspect you have some yellow triangle warnings. Those are often correct (they tell you why the programs runs the wrong way.)
Just going over each line (there aren't that many) you might even be able to spot the error.
Your answer
Follow this Question
Related Questions
Lightswitch help? 3 Answers
Input loss. One out of every five or six mouse clicks or button presses don't register. 1 Answer
Instantiating on Input 1 Answer
Questions of the Coroutines 1 Answer
Distribute terrain in zones 3 Answers