unity實現物體延時出現

本文實例為大傢分享瞭unity實現物體延時出現的具體代碼,供大傢參考,具體內容如下

新建一個cube和plane,隱藏cube,腳本掛在plane上。

1. update計時器實現

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
//一個隱藏的物體等待t秒後顯示,updata計時器實現
public class activeShow : MonoBehaviour {
 
 public GameObject cube;
 public int t;
 private float m_timer=0;
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 m_timer+=Time.deltaTime;
 if(m_timer>5){
  cube.SetActive(true);
  m_timer=0;
 }
 }
}

2. invoke實現

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
一個隱藏的物體等待t秒後顯示,Invoke實現
public class ShowT : MonoBehaviour {
 
 public GameObject cube;
 public int t;//等待時間
 
 // Use this for initialization
 void Start () {
 Invoke("ActiveShow", t);
 }
 
 // Update is called once per frame
 void Update () {
 
 }
 
 public void ActiveShow(){
 cube.SetActive(true);
 }
}

3. invokeRepeating實現(這個是用來湊數的)

void Start () {
 InvokeRepeating("ActiveShow", t,1000);
 }

4. 協程實現

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
//一個隱藏的物體等待t秒後顯示,協程實現
public class HideInSeconds : MonoBehaviour {
 
 public GameObject cube;
 IEnumerator ie;
 
 // Use this for initialization
 void Start () {
 ie=waitFourSeconds();
 StartCoroutine(ie);
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }
 
 IEnumerator waitFourSeconds(){
 yield return new WaitForSeconds(4.0f);
 cube.SetActive(true);
 }
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。