简体   繁体   中英

Coroutine doesn't execute setActive(false)

I have an object in my game that is like a power object: when my player enters the power it should activate a panel that indicates that the power was grabbed, and past 3 seconds that panel should disappear. At the moment my panel appears when I hit the power, but it doesn't disappear. I am using a Coroutine like this:

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: what is inside the update is independent from what i need to do, so i think it doesn't interfer with my needs.

maybe you should check if your gameobject(shrink's) is unactive or destroyed. coroutine does not work with unactive gameobject.

I think you might be destroying the GameObject before the WaitForSeconds(3f) has ended, which will prevent panel.SetActive(false) from executing.

In your Update-method's "else statement to if (temp.x > 0)" you're destroying the GameObject that tries to show/hide the panel.

If you absolutely need to Destroy this gameobject at that time you should break out your IEnumerator to another script and call it from this (shrink.cs) script.

Destroying the object before 3 seconds might be the issue. You can check by putting two logs:

1- After "Object.Destroy" line 2- After "WaitForSeconds"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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