在Scale方法内部,我正在检查它是否处于随机持续时间模式:
if (randomDuration)
{
scaleCoroutine = StartCoroutine(ScaleOverTime(eyesparts[i], maxSize, Random.Range(0.1f, 1)));
}
else
{
scaleCoroutine = StartCoroutine(ScaleOverTime(eyesparts[i], maxSize, duration));
}
问题在于,它没有在完成新的随机持续时间之前完成眨眼,这会导致眼睛眨眼太快,或者有时minSize不能在maxSize之前完成,因为眼睛是由两部分组成的,随机时间构成了部分不相等/不相等。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EyeBlinking : MonoBehaviour
{
public GameObject eyePrefab;
[Range(0.1f, 50f)]
public float duration = 1f;
public Vector3 minSize;
public Vector3 maxSize;
public Coroutine scaleCoroutine;
public bool oppositeDirection = false;
public bool automatic = false;
public bool randomDuration = false;
[Range(1, 20)]
public int numberOfEyes = 1;
private List<GameObject> eyesparts = new List<GameObject>();
private bool coroutineIsRunning = false;
private bool scaleUp = false;
private float oldDuration;
private void Start()
{
oldDuration = duration;
if (oppositeDirection)
{
Vector3 tempMin = minSize;
Vector3 tempMax = maxSize;
minSize = tempMax;
maxSize = tempMin;
}
for (int i = 0; i < numberOfEyes; i++)
{
GameObject eye = Instantiate(eyePrefab);
foreach (Transform child in eye.transform)
{
child.localScale = minSize;
eyesparts.Add(child.gameObject);
}
}
}
private void Update()
{
if (automatic)
{
if (oldDuration != duration && duration >= 0)
{
StopAllCoroutines();
oldDuration = duration;
Scale();
}
if (!coroutineIsRunning)
{
Scale();
}
}
else
{
if (Input.GetKeyDown(KeyCode.G))
{
if (duration > 0)
{
StopAllCoroutines();
Scale();
}
}
}
}
private void Scale()
{
scaleUp = !scaleUp;
if (scaleCoroutine != null)
StopCoroutine(scaleCoroutine);
for (int i = 0; i < eyesparts.Count; i++)
{
if (scaleUp)
{
if (randomDuration)
{
scaleCoroutine = StartCoroutine(ScaleOverTime(eyesparts[i], maxSize, Random.Range(0.1f, 1)));
}
else
{
scaleCoroutine = StartCoroutine(ScaleOverTime(eyesparts[i], maxSize, duration));
}
}
else
{
scaleCoroutine = StartCoroutine(ScaleOverTime(eyesparts[i], minSize, duration));
}
}
}
private IEnumerator ScaleOverTime(GameObject targetObj, Vector3 toScale, float duration)
{
float counter = 0;
Vector3 startScaleSize = targetObj.transform.localScale;
coroutineIsRunning = true;
while (counter < duration)
{
counter += Time.deltaTime;
targetObj.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
if (counter > duration)
coroutineIsRunning = false;
yield return null;
}
}
}
答案 0 :(得分:0)
更改:
private bool coroutineIsRunning = false;
到
private List<bool> coroutineIsRunning;
使其长度与private List<GameObject> eyesparts
通过这种方式,您可以知道协程是否针对每个具有不同持续时间的特定眼睛部分运行
尽管在这一点上,这将使您的代码更难阅读和维护。...也许您应该考虑将代码分成更小的部分