2014年5月13日 星期二

[Unity3D] 遊戲暫停時 動畫與音樂的處理

節錄官方範例的script裡的method

private List<Animation> animationComponents;
private List<AudioSource> audioSourceComponents;

void HandleGamePauseRtGame(){ _GamePausePanel.SetActive(false); StartCoroutine(Pause (false)); } void HandleGamePauseOnPress(){ _GamePausePanel.SetActive(true); //_GamePausePanel.transform.position = new Vector3(0,0,0); StartCoroutine(Pause (true)); }

IEnumerator Pause (bool pause) {
// Pause/unpause time
Time.timeScale = (pause ? 0 : 1);
// Unlock/Lock cursor
Screen.lockCursor = !pause;

if (pause == true) {
Object[] objects = FindObjectsOfType(typeof(Animation));
animationComponents = new List<Animation>();
foreach (Object obj in objects) {
Animation anim = (Animation)obj;
if (anim != null && anim.enabled) {
animationComponents.Add(anim);
anim.enabled = false;
}
}
objects = FindObjectsOfType(typeof(AudioSource));
audioSourceComponents = new List<AudioSource>();
foreach (Object obj in objects) {
AudioSource source = (AudioSource)obj;
if (source != null && source.enabled /*&& source.isPlaying*/) {
audioSourceComponents.Add(source);
source.Pause();
}
}
}
else {
// If unpausing, wait one frame before we enable animation component.
// Procedural adjustments are one frame delayed because first frame
// after being paused has deltaTime of 0.
yield return 0;
foreach (Animation anim in animationComponents)
anim.enabled = true;
foreach (AudioSource source in audioSourceComponents)
source.Play();
animationComponents = null;
}
}


沒有留言:

張貼留言