简体   繁体   English

Unity3d:将对象设置为几秒钟不可见

[英]Unity3d : object set to invisible for seconds

I am using a coroutine to alternate my object visibility using Renderer.enabled every 2 seconds, but the object doesn't wait 2 seconds to change its state, it just alternate between visible and non visible fast and randomly, it's just looking unstable. 我使用协程每隔2秒使用Renderer.enabled更改对象可见性,但是对象不等待2秒钟更改其状态,它只是在可见和不可见之间快速随机地交替显示,只是看起来不稳定。

Here is my code : 这是我的代码:

using UnityEngine;
using System.Collections;

public class ArrowController : MonoBehaviour {



GameObject arrow = null;

void Start () {
    arrow = GameObject.Find ("Arrow");
    arrow.GetComponent<Renderer> ().enabled = false;
}

void Update () {

    StartCoroutine(showDirection());


}



    IEnumerator showDirection(){
            while (true) {
        GetComponent<MeshRenderer> ().enabled = true;
        GetComponent<Renderer> ().enabled = true;

        yield return new WaitForSeconds (1);
        GetComponent<MeshRenderer> ().enabled = false;
        GetComponent<Renderer> ().enabled = false;

        yield return new WaitForSeconds (1);
    }

    }


}

That's because you have StartCoroutine in Update method, which is fired every frame. 那是因为在Update方法中有StartCoroutine ,它每帧都会触发一次。 So, you start a new coroutine every frame, and you have hundreds of coroutines running at the same time. 因此,您每帧启动一个新的协程,并且同时运行数百个协程。

Place that coroutine is start as placing it in update will make the coroutine run many times. 将协程启动,因为将其放置在更新中将使协程运行多次。 Just make sure while using coroutines that they are called only when necessary in you case the keeping it in update loop is the problem. 只要确保在使用协程时,仅在必要时才调用它们,以确保将其保持在更新循环中就成为问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM