I'm implementing a fading effect for my game. I can change the duration to 0.1
(or 1
, 5
, or 10
). But if I change the duration to 0
and the fading stops, then when I change back the duration to any value above 0
the fading does not resume. I tried it on the automatic mode when isAutomatic
is true
. I can't figure out why after setting it to 0
and back to 1
, the fading is not continuing.
Here's my current implementation:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Fader : MonoBehaviour
{
public GameObject objectToScale;
public float duration = 1f;
public Vector3 minSize;
public Vector3 maxSize;
public bool scaleUp = false;
public Coroutine scaleCoroutine;
public bool isAutomatic = false;
private bool automatic = true;
private void Start()
{
objectToScale.transform.localScale = minSize;
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.G))
{
Fade();
}
if (isAutomatic && automatic)
{
Fade();
automatic = false;
}
}
private IEnumerator ScaleOverTime(GameObject targetObj,
Vector3 toScale, float duration)
{
float counter = 0;
Vector3 startScaleSize = targetObj.transform.localScale;
while (counter < duration)
{
counter += Time.deltaTime;
targetObj.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
yield return null;
}
automatic = true;
}
private void Fade()
{
scaleUp = !scaleUp;
if (scaleCoroutine != null)
StopCoroutine(scaleCoroutine);
if (scaleUp)
{
scaleCoroutine = StartCoroutine(ScaleOverTime(objectToScale, maxSize, duration));
}
else
{
scaleCoroutine = StartCoroutine(ScaleOverTime(objectToScale, minSize, duration));
}
}
}