我怎样才能使用StartCoroutine缓慢地缩放对象?

这两个脚本都附加到Hierarchy中的相同对象。 我使用F键显示或不显示对象的第一个脚本:

using System.Collections; using System.Collections.Generic; using UnityEngine; public class DroidMove : MonoBehaviour { public GameObject droid; private float distance; private Camera cam; private void Start() { cam = GetComponent<Camera>(); distance = Vector3.Distance(cam.transform.position, droid.transform.position); droid.SetActive(false); } private void Update() { if (Input.GetKeyDown(KeyCode.F)) { droid.SetActive(!droid.activeInHierarchy); } } } 

一旦按下F来显示对象我想从0,0,0到1,1,1慢慢缩放对象,所以我做了另一个脚本:

 using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeScale : MonoBehaviour { public GameObject objectToScale; public float maxSize = 1f; public float growFactor = 1f; public float waitTime = 5f; // Use this for initialization void Start () { objectToScale.transform.localScale = new Vector3(0, 0, 0); } IEnumerator Scale() { float timer = 0; while (true) // this could also be a condition indicating "alive or dead" { // we scale all axis, so they will have the same value, // so we can work with a float instead of comparing vectors while (maxSize > objectToScale.transform.localScale.x) { timer += Time.deltaTime; objectToScale.transform.localScale += new Vector3(1, 1, 1) * Time.deltaTime * growFactor; yield return null; } // reset the timer yield return new WaitForSeconds(waitTime); timer = 0; while (1 < objectToScale.transform.localScale.x) { timer += Time.deltaTime; objectToScale.transform.localScale -= new Vector3(1, 1, 1) * Time.deltaTime * growFactor; yield return null; } timer = 0; yield return new WaitForSeconds(waitTime); } } // Update is called once per frame void Update () { if (objectToScale.activeInHierarchy == true) { StartCoroutine(Scale()); } } } 

但是我在线上的第一个脚本得到两个例外:

 droid.SetActive(!droid.activeInHierarchy); 

第一个例外:

坡度限制必须小于90度。 UnityEngine.GameObject:SetActive(布尔)DroidMove:更新()(在资产/ NAVI /脚本/ DroidMove.cs:23)

第二个例外:

UnityEngine.GameObject:SetActive(布尔)DroidMove:更新()(在资产/ NAVI /脚本/ DroidMove.cs:23)

首先,在更新循环中启动协程是一个非常糟糕的主意。 切勿在更新中调用它。 相反,你应该使用OnEnable作为你的规模的协同程序不应该调用每一帧。