【Unity】遊戲開發過程中的前後臺切換技術

在有些場景中游戲是需要從前臺切換到後臺運行的,那麼在開發過程中需要如何去實現這個功能呢,爲了幫助大家,下面就給大家介紹下退後臺的方法,不會的就一起來看看吧。
  
  
//simulateSwitchToBackground.cs

usingUnityEngine;
usingSystem.Collections;
usingSystem.Collections.Generic;
publicclass simulateSwitchToBackground : MonoBehaviour {
voidsendApplicationPauseMessage(boolisPause){
Transform[] transList= GameObject.FindObjectsOfType(); 
for(inti = 0; i < transList.Length; i++) {
Transform trans = transList [i];
//Note that messages will not be sent to inactive objects
trans.SendMessage ("OnApplicationPause",isPause,SendMessageOptions.DontRequireReceiver);
}
}
voidsendApplicationFocusMessage(boolisFocus){
Transform[] transList= GameObject.FindObjectsOfType(); 
for(inti = 0; i < transList.Length; i++) {
Transform trans = transList [i];
//Note that messages will not be sent to inactive objects
trans.SendMessage ("OnApplicationFocus",isFocus,SendMessageOptions.DontRequireReceiver);
}
}
 
publicvoid sendEnterBackgroundMessage(){
sendApplicationPauseMessage (true);
sendApplicationFocusMessage (false);
 
}
publicvoid sendEnterFoegroundMessage(){
sendApplicationFocusMessage (true);
sendApplicationPauseMessage (false);
 
}
 
}
  
  //simulateSwitchToBackgroundEditor.cs

usingUnityEngine;
usingSystem.Collections;
usingUnityEditor;
[CustomEditor(typeof(simulateSwitchToBackground))]
publicclass simulateSwitchToBackgroundEditor : Editor
{
 
voidOnEnable(){
}
 
publicoverride void OnInspectorGUI()
{
 
 
DrawDefaultInspector();
serializedObject.Update ();
 
serializedObject.ApplyModifiedProperties ();//now varibles in script have been updated
 
 
if(GUILayout.Button ("send enter background message")) {
if(Application.isPlaying) {
((simulateSwitchToBackground)target).sendEnterBackgroundMessage ();
}
}
if(GUILayout.Button ("send enter foeground message")) {
if(Application.isPlaying) {
((simulateSwitchToBackground)target).sendEnterFoegroundMessage ();
}
}
}
 
 
}

  
  把simulateSwitchToBackground.cs掛到場景中的一個gameObject上,其inspector面板如下:

  
  在遊戲運行過程中點“send endter background message”按鈕,即模擬遊戲退到後臺。再點"send enter foeground message"按鈕,模擬遊戲從後臺切回到前臺。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章