如何同时缩放数组中的所有对象?

问题描述 投票:-1回答:1
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++)

但是它仅缩放数组中的第一个对象。

c# unity3d
1个回答
0
投票

在协程中完成所有操作..(未经检查的代码,但是可能会有奇怪的错误,但是..]

这将像您尝试过的那样遍历数组中的所有项目。如果您想并行使用,则需要进行一些调整。

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.