- Home /
Some Boolean "Action" Trouble
Okay, so in this script whenever the booleans IsOver5 and IsUnder5 are true, they do not do anything whenever the mouse clicks on the bakery. IsUnder5, when true, it is suppose to say in the console that the player does not have enough apples. Any help is appreciated!
Here is the code: void Update () {
//States the booleans
bool IsOver5 = Apples<= 5f;
bool IsUnder5 = Apples >= 5f;
//This changes the text
txt.text = "Ray Distance: " + distance;
//Basically declares where the ray is going
Vector3 forward = transform.TransformDirection (Vector3.forward) * distance;
Debug.DrawRay (transform.position, forward, Color.red);
//Basically declaring Apples
if (Physics.Raycast (transform.position, (forward), out hit, 5.0f)) {
rayDistance = hit.distance;
if (hit.collider.tag == ("Apple")) {
if (Input.GetKeyDown (KeyCode.Mouse0)) {
apples.text = "Apples: " + Apples;
Apples = Apples + 1;
}
}
//Declares what the Bakery will do.
//If tag is Bakery
if (hit.collider.tag == ("Bakery")) {
//When left mouse button is clicked
if (Input.GetKeyDown (KeyCode.Mouse0)) {
//Booleans, if true?
if (IsOver5 == true) {
Apples -= 5f;
}
if (IsUnder5 == true) {
print ("You Don't Have Enough Apples!");
}
}
}
}
}
Also, I'm thinking Apples is a score, so you might need to save to PlayerPrefs.Save();
Answer by jjcrawley · Mar 03, 2017 at 06:46 PM
Your logic is incorrect, and the isUnder5 variable is unnecessary, if you have more than 5 apples then you can't have less than five apples.
bool isOver5 = Apples >= 5f;
That will be sufficient, the extra isUnder5 will mess with the logic anyway. It will be true if you have 5 apples, the same as isUnder5. It will cause the code to remove five apples, before saying that you don't have enough. Debug it out and see for yourself.
Minor logic bug out the way. There are two things worth checking out. First the physics raycast, is it ever registering true. Place a debug inside and see. If that is working fine, double check your tags, make sure that your bakery object is tagged as Bakery. If that's okay, then check your Input check, place a debug in there.
Finally, if all of these are working, then check your apples. Are they being incremented correctly? You can check this by debugging out your isUnder5 flag. Do these checks in any order you like, may want to check the apples first before sorting out the raycast stuff.
Hopefully this'll lead you in the right direction.
Answer by UnityCoach · Mar 04, 2017 at 01:50 AM
Ok, I sort of understand what you want to do. I'm not going to discuss your logic here, as I believe it's always an iterative process.
You can use an accessor, outside of Update, like this :
bool isOver5 { get { return Apples >= 5f; } }
You may also want to simply use the condition in the statement itself, as it seems it's the only place you use it.
if (Apples >= 5f)
{
Apples -= 5f;
}
else
{
print ("You Don't Have Enough Apples!");
}