Daniel Lip
Daniel Lip

Reputation: 11325

How can I scale all the objects in the array at the same time?

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;
    }
}

I tried using a loop :

for (int i = 0; i < objectsToScale.Length; i++)

But it's scaling only the first object in the array.

Upvotes: 0

Views: 119

Answers (1)

BugFinder
BugFinder

Reputation: 17868

Do it all in the coroutine.. (unchecked code, may have odd errors but..)

This will run through all items in the array a bit like you tried.. If you want in parallell you'd need to funk it up a little.

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;
}

Upvotes: 1

Related Questions