I'm a beginner coder in Unity and, although I don't have much experience coding, I know that my code is a mess.
So, here's the thing: I inserted a certain functionality that allows the player to Lerp from its position, to a "Object1" when I click the mouse(0). At the click, a Time Counter starts and, in the period of 2 seconds, if I click de mouse(0) again, it will Lerp the player to a second time, now to an "Object2". I applied this logic in a way that allows the user to Lerp the Player 4 times to 4 different positions, if each Input was under the five seconds.
With much effort I find a way to make it work, it's functional, but at the cost of many booleans and ifs statements, a complete and terrible Spaguetti. So my question to you folks, is how could I make this whole mess more clean and efficient ? What code structures could I use in this type of situation to make the whole thing more readable, and cut off this huge amount of booleans and conditionals? Thank you all in advance!
Here's the code:
[SerializeField] private Transform cube1;
[SerializeField] private Transform cube2;
[SerializeField] private Transform cube3;
[SerializeField] private Transform cube4;
private float timer;
private bool canCount;
private bool click1;
private bool click2;
private bool click3;
private bool click4;
private bool lerp1;
private bool lerp2;
private bool lerp3;
private bool lerp4;
private void CountDown()
{
if (canCount)
{
timer += Time.deltaTime;
if (timer >= 2)
{
canCount = false;
Debug.Log("Timer End");
}
}
}
private void Lerp()
{
if (lerp1)
{
transform.position = Vector3.Lerp(transform.position, cube1.position, Time.deltaTime * 10);
}
if (lerp2)
{
transform.position = Vector3.Lerp(transform.position, cube2.position, Time.deltaTime * 10);
}
if (lerp3)
{
transform.position = Vector3.Lerp(transform.position, cube3.position, Time.deltaTime * 10);
}
if (lerp4)
{
transform.position = Vector3.Lerp(transform.position, cube4.position, Time.deltaTime * 10);
}
}
private void Update()
{
CountDown();
Lerp();
if (Input.GetMouseButtonDown(0))
{
if (!canCount)
{
click1 = true;
click2 = false;
click3 = false;
click4 = false;
lerp2 = false;
lerp3 = false;
lerp4 = false;
if (click1)
{
click1 = false;
click2 = true;
lerp4 = false;
lerp1 = true;
timer = 0;
canCount = true;
}
else if (click2 && canCount)
{
click2 = false;
click3 = true;
lerp1 = false;
lerp2 = true;
timer = 0;
}
else if (click3 && canCount)
{
click3 = false;
click4 = true;
lerp2 = false;
lerp3 = true;
timer = 0;
}
else if (click4 && canCount)
{
click4 = false;
click1 = true;
lerp3 = false;
lerp4 = true;
timer = 0;
}
}
else
{
if (click1)
{
click1 = false;
click2 = true;
lerp4 = false;
lerp1 = true;
timer = 0;
canCount = true;
}
else if (click2)
{
click2 = false;
click3 = true;
lerp1 = false;
lerp2 = true;
timer = 0;
}
else if (click3)
{
click3 = false;
click4 = true;
lerp2 = false;
lerp3 = true;
timer = 0;
}
else if (click4)
{
click4 = false;
click1 = true;
lerp3 = false;
lerp4 = true;
timer = 0;
}
}
}