协程不执行 setActive(false)

Coroutine doesn't execute setActive(false)

我的游戏中有一个类似于能量对象的对象:当我的玩家输入能量时,它应该激活一个指示能量被获取的面板,并且在 3 秒后该面板应该消失。目前,当我按下电源时,我的面板出现了,但它并没有消失。我正在使用这样的协程:

using UnityEngine;
using System.Collections;

public class shrink : MonoBehaviour {

    public float value = 0.1f; //1 by default in inspector
    private bool colided = false;
    private float speed;
    Manager gameManager;
    public GameObject panel;
    // Update is called once per frame
    void Start(){
        speed = 3.4f;
        gameManager = GameObject.Find ("GameController").GetComponent<Manager> ();
    }

    void OnTriggerEnter(Collider c)
    {
        if (c.gameObject.tag == "Player") {
            colided = true;
            gameManager.powerUp1 = true;
            StartCoroutine(menuOp());
        }
    }

    //This method is executed every frame
    void Update(){
        if (colided) {
            Vector3 temp = transform.localScale; 
            //We change the values for this saved variable (not actual transform scale)
            temp.x -= value * Time.time;
            temp.y -= value * Time.time;

            if (temp.x > 0) {
                speed += 0.02f;
                transform.Rotate (0f, 0f, Time.deltaTime * 90 * speed);
                transform.localScale = temp;
            } else {
                Object.Destroy (this.gameObject);
            }
        }
    }


    IEnumerator menuOp(){
        panel.SetActive (true);
        yield return new WaitForSeconds (3f);
        panel.SetActive (false);
    }
}

Ps:更新中的内容与我需要做的无关,所以我认为它不会干扰我的需求。

也许你应该检查你的游戏对象(收缩的)是否未激活或被破坏。 协程不适用于未激活的游戏对象。

我认为您可能会在 WaitForSeconds(3f) 结束之前销毁 GameObject,这将阻止 panel.SetActive(false) 执行。

在您的 Update-method 的 "else statement to if (temp.x > 0)" 中,您正在破坏试图 show/hide 面板的游戏对象。

如果你当时绝对需要销毁这个游戏对象,你应该将你的 IEnumerator 分解到另一个脚本并从这个 (shrink.cs) 脚本中调用它。

在 3 秒之前销毁对象可能是问题所在。您可以通过放置两个日志来检查:

1- "Object.Destroy" 行之后 2- "WaitForSeconds"

之后