简体   繁体   中英

Unity, C#: Delay on function not working? Waitforseconds?

I am creating a VR app using Google Cardboard in Unity and I have succeeded in switching from VR to a normal view with this function:

public GameObject[] cardboardObjects;
    public GameObject[] monoObjects;
    public bool switched = false;

    // Turn on or off VR mode
    void ActivateVRMode(bool goToVR) {
        foreach (GameObject cardboardThing in cardboardObjects) {
            cardboardThing.SetActive(goToVR);
        }
        foreach (GameObject monoThing in monoObjects) {
            monoThing.SetActive(!goToVR);
        }
        Cardboard.SDK.VRModeEnabled = goToVR;

        // Tell the game over screen to redisplay itself if necessary
        //gameObject.GetComponent<GameController>().RefreshGameOver();
    }

I then call this function on a button to switch to mono view:

public void Switch() {
        ActivateVRMode(false);
        switched = true;
        Debug.Log (switched+"No VR!");
    }

I then want to have the mono view on a timer, as in once the user switches to non-VR mode it remains in that for only a set amount of time (3 seconds or so) before switching back to VR.

I tried to do this by flipping a boolean and using WaitForSeconds , however the view remains in mono view and nothing happens:

IEnumerator Switchback() 
    {
        yield return new WaitForSeconds(3); 
            ActivateVRMode(true);
            switched = false;
            Debug.Log (switched+"VR!");
    }

    void Update () {

        if (switched == true) {
            Switchback ();
        }

        //Debug.Log ("updating");

    }

What am I doing wrong here?

You have forgotten to call the Switchback function as a Coroutine

Instead of calling Switchback() you need to call StartCoroutine(Switchback()) in your Update() function.

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