c# - 如何同时缩放数组中的所有对象?
问题描述
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawLinesAnimated : MonoBehaviour
{
public Transform[] objectsToScale;
private void Start()
{
for (int i = 0; i < objectsToScale.Length; i++)
{
StartCoroutine(scaleOverTime(objectsToScale[i], new Vector3(2, objectsToScale[i].transform.localScale.y, objectsToScale[i].transform.localScale.z), 2));
}
}
bool isScaling = false;
IEnumerator scaleOverTime(Transform objectToScale, Vector3 toScale, float duration)
{
//Make sure there is only one instance of this function running
if (isScaling)
{
yield break; ///exit if this is still running
}
isScaling = true;
float counter = 0;
//Get the current scale of the object to be moved
Vector3 startScaleSize = objectToScale.localScale;
while (counter < duration)
{
counter += Time.deltaTime;
objectToScale.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
yield return null;
}
isScaling = false;
}
}
我尝试使用循环:
for (int i = 0; i < objectsToScale.Length; i++)
但它只缩放数组中的第一个对象。
解决方案
在协程中完成所有操作..(未经检查的代码,可能有奇怪的错误但是..)
这将像您尝试过的那样遍历数组中的所有项目。如果您想要并行,您需要稍微改进一下。
Enumerator scaleOverTime(float ScaleSize, float duration)
{
if (isScaling) yield return break;
isScaling = true;
for (int i = 0; i < objectsToScale.Length; i++)
{
float counter = 0;
//Get the current scale of the object to be moved
Vector3 startScaleSize = objectToScale[i].localScale;
Vector3 toScale = startScale*ScaleSize;
while (counter < duration)
{
counter += Time.deltaTime;
objectToScale[i].localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
yield return null;
}
}
isScaling = false;
}