unity3d 延迟执行脚本语句

2015年03月21日 14:05 0 点赞 0 评论 更新于 2025-11-21 17:57

在 Unity3D 中,yield 语句可用于实现延迟操作。例如,yield return new WaitForSeconds(3.0f); 这行代码的作用是让程序等待 3 秒。

若要深入了解其用法,可查阅 Unity3D 脚本手册,使用时需遵循相应的格式规范。

下面通过一段示例代码,详细说明如何实现加载图片显示,等待 6 秒后进入名为 level1 的场景。

using UnityEngine;
using System.Collections;

public class init : MonoBehaviour
{
// 用于存储要显示的图片纹理
public Texture img;
// 用于标记是否可以加载场景的布尔变量
private bool bl = false;
// 等待时间变量
public float waitTime;

// 初始化方法,在脚本实例被启用时调用
void Start()
{
// 启动一个协程,并传入等待时间 6.0f
StartCoroutine(wait(6.0f));
}

// 每帧调用一次的更新方法
void Update()
{
// 当 bl 为 true 时,加载索引为 1 的场景
if (bl)
{
Application.LoadLevel(1);
}
}

// 用于绘制 GUI 的方法
void OnGUI()
{
// 在屏幕上绘制图片纹理
GUI.DrawTexture(new Rect(0, 0, 1024, 768), img);
}

// 协程方法,用于实现延迟操作
IEnumerator wait(float time)
{
// 等待指定的时间
yield return new WaitForSeconds(waitTime);
// 等待时间结束后,将 bl 设置为 true
bl = true;
}
}

在上述代码中,Start 方法启动了一个协程 wait,并传入等待时间 6 秒。wait 协程使用 yield return new WaitForSeconds(waitTime) 来暂停执行指定的时间,时间结束后将 bl 变量设置为 true。在 Update 方法中,会不断检查 bl 变量的值,当 bltrue 时,就会调用 Application.LoadLevel(1) 加载索引为 1 的场景。同时,OnGUI 方法负责在屏幕上绘制图片纹理。

需要注意的是,Application.LoadLevel 在较新的 Unity 版本中已被弃用,建议使用 SceneManager.LoadScene 方法来加载场景。例如:

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class init : MonoBehaviour
{
public Texture img;
private bool bl = false;
public float waitTime;

void Start()
{
StartCoroutine(wait(6.0f));
}

void Update()
{
if (bl)
{
SceneManager.LoadScene(1);
}
}

void OnGUI()
{
GUI.DrawTexture(new Rect(0, 0, 1024, 768), img);
}

IEnumerator wait(float time)
{
yield return new WaitForSeconds(waitTime);
bl = true;
}
}

这样可以确保代码在新的 Unity 版本中也能正常工作。

作者信息

menghao

menghao

共发布了 3994 篇文章