一般來說,我對統一和編程很陌生,我正在使用“DontDestroyOnLoad (gameObject);” 在管理游戲中播放的所有聲音的腳本中,我遇到了一個問題,即當我加載到另一個場景時,即使 DondtDestroyOnLoad 已打開,暫停和取消暫停之類的東西也會停止作業,它給了我一個 NullReferenceException 錯誤所以我認為當加載一個新場景,它清空了變數。現在有人有辦法防止這種情況發生嗎?
using UnityEngine.Audio;
using System;
using UnityEngine;
using Random=UnityEngine.Random;
public class AudioManager : MonoBehaviour
{
public Sound[] sounds;
public static AudioManager instance;
void Awake() {
if (instance == null) {
instance = this;
}
else {
Destroy(gameObject);
return;
}
DontDestroyOnLoad (gameObject);
foreach (Sound s in sounds) {
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
if (s.randompitch == false) {
s.source.pitch = s.pitch;
}
s.source.loop = s.loop;
if (s.playonstart == true) {
Play(s.name);
}
}
}
public void Play (string name) {
Sound s = Array.Find(sounds, sound => sound.name == name);
if (s == null){
Debug.LogWarning("there is no" name);
return;
}
if (s.randompitch == true ) {
s.source.pitch = Random.Range(s.randompitchmin, s.randompitchmax);
}
s.source.Play();
}
public void SoundPause (string name) {
Sound s = Array.Find(sounds, sound => sound.name == name);
if (s == null){
Debug.LogWarning("there is no" name);
return;
}
s.source.Pause();
}
public void SoundUnPause (string name) {
Sound s = Array.Find(sounds, sound => sound.name == name);
if (s == null){
Debug.LogWarning("there is no" name);
return;
}
s.source.UnPause();
}
}
uj5u.com熱心網友回復:
您可以將 DontDestroyOnLoad 添加到其陣列
像這樣
for(int i = 0; i < sounds.Length;)
{
DontDestroyOnLoad(sounds[i]);
i ;
}
或者您可以在 Scane 中搜索聲音
通過使用 :
游戲物件.查找
GameObject.FindGameObjectsWithTag
Object.FindObjectOfType
編輯
for(int i = 0; i < sounds.Length;)
{
DontDestroyOnLoad(sounds[i].GetComponent<GameObject>());
i ;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432324.html
標籤:unity3d
上一篇:檢測方法外的變數
下一篇:有沒有人可以幫忙顯示時間
