I have some objects with this script on them, that make them scale up when the mouse is over them
public void ZoomIn()
{
savedPosition = this.transform.position;
this.transform.position = new Vector3(savedPosition.x, savedPosition.y + 120f, savedPosition.z);
this.transform.localScale = new Vector3(2f, 2f, 1f);
}
public void ZoomOut()
{
this.transform.position = savedPosition;
this.transform.localScale = Vector3.one;
}
ZoomIn and ZoomOut are called by events.
This works just fine. But I wanted to wait a bit, before the scale triggers, so I modified the game like this:
[SerializeField]
private float zoomDelay;
private float timer;
private bool isTimeCounting = false;
void Update()
{
if (isTimeCounting)
{
timer += Time.deltaTime;
if (timer >= zoomDelay)
{
Zoom();
}
}
}
public void ZoomIn()
{
timer = 0f;
isTimeCounting = true;
}
private void Zoom()
{
savedPosition = this.transform.position;
this.transform.position = new Vector3(savedPosition.x, savedPosition.y + 120f, savedPosition.z);
this.transform.localScale = new Vector3(2f, 2f, 1f);
isTimeCounting = false;
}
public void ZoomOut()
{
this.transform.position = savedPosition;
this.transform.localScale = Vector3.one;
isTimeCounting = false;
}
Now, when the ZoomIn is called, a timer starts. If the zoomOut is called before the Zoom, the timer is stopped.
This system works. Well, not really. Most of the time it works as intended. Sometimes there is an object that Zooms in regularly (saving the savedPosition variable), but when it’s time to ZoomOut, the savedPosition becomes the Vector3.zero, moving the gameObject far away.
I don’t use those variables elsewhere.
What am I doing wrong?
Thanks for the answers.