1. 程式人生 > >Unity3d監聽手機暫停與退出事件

Unity3d監聽手機暫停與退出事件

1,退出事件,Unity3d,InPut就包含了:

Input.GetKey(KeyCode.Escape) 、 Input.GetKey(KeyCode.Home) 、Input.GetKey(KeyCode.Menu);

2,暫停事件,Unity3d的

OnApplicationFocus、OnApplicationPause兩者結合起來

如:

[AddComponentMenu("WuKk/Public/Game Pause Quit")]

publicclass GamePauseQuit : MonoBehaviour {

public  delegate  void GameQuitDelegate();

public  static  event GameQuitDelegate gameQuitDelegate;

public  delegate  void GamePauseDelegate();

public  static  event GamePauseDelegate gamePauseDelegate;

bool isPause=false;

void OnEnable(){

isPause=false;

}

void  Update(){

    if (Input.GetKey(KeyCode.Escape) || Input.GetKey(KeyCode.Home) ||Input

.GetKey(KeyCode.Menu))

{

  if(gameQuitDelegate!=null)

gameQuitDelegate();

else 

  Application.Quit();

}

void OnApplicationFocus(){

#if UNITY_IPHONE || UNITY_ANDROID

  isPause=true;

#endif

}

void OnApplicationFocus(){

#if UNITY_IPHONE || UNITY_ANDROID

if(isPause)

{

isPause=false;

if(gamePauseDelegate!=null)

gamePauseDelegate();

}

#endif

}

}