- Home /
looking for a way to set an integer to another number based on a condition.
Hello everyone! I am very new to C# and am having some trouble. I use mouse clicks to increase an integer from 1 to 3.
Goal: I want to set the integer counter to 1 when I click the mouse button and the current integer is set to three.
So the sequence starts on 1, i click and it becomes 2, I click again and it becomes 3 and I click once more to set it back to 1.
the problem: I try to do this with if(Input.GetMouseButtonDown(0) && Integer == 3) { Integer = 1 }
When doing this, it skips 3. So i press the mouse on two and it resets to 1 without going to three. Not sure what I am missing with this. Any help would be appreciated.
If you want it displayed as UI text put another comment and I can show you how.
Answer by thadstedman · Nov 23, 2020 at 04:17 AM
try public int myInt; void Update() { if (myInt == 3) { if (Input.GetKeyDown(KeyCode.Space)) { myInt = 1; } }else { if (Input.GetKeyDown(KeyCode.Space)) { myInt ++; } } Debug.Log(myInt); }
Here is the same code but with better format public int myInt;
void Update()
{
if (myInt == 3)
{
if (Input.GetKeyDown(KeyCode.Space))
{
myInt = 1;
}
}else
{
if (Input.GetKeyDown(KeyCode.Space))
{
myInt ++;
}
}
Debug.Log(myInt);
}
Oops I mean
public int myInt;
void Update()
{
if (myInt == 3)
{
if (Input.GetKeyDown(KeyCode.Space))
{
myInt = 1;
}
}else
{
if (Input.GetKeyDown(KeyCode.Space))
{
myInt ++;
}
}
Debug.Log(myInt);
}
Oh yeah and change the Debug.Log(myInt); to whatever form you want of showing your int
If you want it displayed as UI text put another comment and I can show you how.
Answer by unity_ek98vnTRplGj8Q · Nov 23, 2020 at 06:06 PM
I'm assuming that you have something similar to this
if(Input.GetMouseButtonDown(0) && Integer == 2) { Integer = 3 }
if(Input.GetMouseButtonDown(0) && Integer == 3) { Integer = 1 }
In which case your issue would be that when the number changes from 2 to 3, it then immediately checks the next line where GetMouseButtonDown is still true AND your number is now 3, so it immediately changes from 3 to 1. You can fix this by changing your second if to an else if so that it doesn't run on the same frame.
if(Input.GetMouseButtonDown(0) && Integer == 2) { Integer = 3 }
else if(Input.GetMouseButtonDown(0) && Integer == 3) { Integer = 1 }
Alternatively, you could always do something like this instead
maxNum = 3;
if(Input.GetMouseButtonDown(0)){
Integer++;
if(Integer > maxNum) Integer = 1;
}
Which lets you easily change you max number without having to write more code
Your answer
Follow this Question
Related Questions
How to implement tokenization of game characters? 1 Answer
Beginner Question: How to get normals from a physics raycast using visual scripting? 0 Answers
Question regarding Raycast hitting UI button object instead of gameobject 0 Answers
How do I make a photography function? 0 Answers
weighted inventory system 1 Answer