Unity3D——游戏开始与暂停

论坛 期权论坛 脚本     
匿名网站用户   2020-12-20 11:22   11   0
暂停:
Time.timeScale=0;
开始:
Time.timeScale=1;

例如:
usingUnityEngine;
usingSystem.Collections;

publicclassScript_Menu:MonoBehaviour{

publicboolIsGamePaused;

voidStart()
{
PauseGame();
}

voidUpdate()
{
if(Input.GetKey(KeyCode.Escape))
{
PauseGame();
}
}
voidOnGUI()
{
if(!IsGamePaused)
return;
///自动布局,按照区域
GUILayout.BeginArea(newRect((Screen.width-100)/2,(Screen.height-200)/2,100,200));
///横向
GUILayout.BeginVertical();
if(IsGamePaused)
{
if(GUILayout.Button("开始游戏",GUILayout.Height(50)))
{
StartGame();
//enabled = false;
}
}
if(GUILayout.Button("退出游戏",GUILayout.Height(50)))
{
//在Android上可以,IOS上没试
//Debug.Log("Exit");
Application.Quit();
}
GUILayout.Button("关于游戏",GUILayout.Height(50));
GUILayout.EndVertical();
GUILayout.EndArea();
}

voidStartGame()
{
IsGamePaused=false;
Time.timeScale=1;
//Debug.Log("Start Game" + Time.fixedTime);
}

voidPauseGame()
{
IsGamePaused=true;
Time.timeScale=0;
//Debug.Log("Pause Game");
}
}

http://blog.sina.com.cn/s/blog_c3a4360501019wnl.html


一提到游戏暂停,很多人会想到 Time.timeScale = 0; 这种方法,但 Time.timeScale 只是能暂停部分东西。如果在 update 函数中持续改变一个物体的位置,这种位置改变貌似是不会受到暂停影响的。比如 transform.position = transform.position+transform.TransformDirection(Vector3(0,0,throwForce));
Time.timeScale = 0 的时候这个东西仍然在动。

CocoaChina 会员“123探花”的解决方法是:把使用Time.timeScale = 0; 功能的函数写在 FixedUpdate() , 当使用 Time.timeScale = 0 时项目中所有 FixedUpdate() 将不被调用,以及所有与时间有关的函数。在 update 通过一个布尔值去控制暂停和恢复。
如果您设置 Time.timeScale 为 0,但你仍然需要做一些处理(也就是说动画暂停菜单的飞入),可以使用 Time.realtimeSinceStartup 不受 Time.timeScale 影响。

另外您也可以参考一下Unity Answer上提到的方法

要暂停游戏时,为所有对象调用 OnPauseGame 函数:
Object[] objects = FindObjectsOfType (typeof(GameObject));
foreach (GameObject go in objects) {
go.SendMessage ("OnPauseGame", SendMessageOptions.DontRequireReceiver);
}

从暂停状态恢复时,
A basic script with movement in the Update() could have something like this:
protected bool paused;

void OnPauseGame ()
{
paused = true;
}

void OnResumeGame ()
{
paused = false;
}

void Update ()
{
if (!paused) {
// do movement
}
}


http://blog.csdn.net/tammy520/article/details/8959394
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP