Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Gaming_Project · Feb 16, 2017 at 03:00 AM · scripting problemprefabsaudiosourcepoolingpersistence

Persisting Prefabs across scenes

I have created a SoundManager that persists across scenes so that the music is not interrupted. I have also created an object pool so that if a user were to click an in-game element multiple times the sound overlaps rather than cuts off the previous sounds.

I have implemented the object pooling manager as described in the Unity lesson (https://unity3d.com/learn/tutorials/topics/scripting/object-pooling) which works fine when staying and only used in a scene but the trouble I am having is persisting the prefabs collection from across scenes.

On startup I instantiate the SoundManager, load the sounds and then create the object pool. The object pool is created and populated with the prefab audiosource to create the channels I require. This is all working fine but when I transition to the game scene the soundmanager has persisted but collection list has null object in the new scene:

SoundManager

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class SoundManager : MonoBehaviour 
 {
     public AudioSource musicSource, uiSFXSource;
 
     private List<string> _clips;
 
     public static bool MusicLoaded { get; private set; }
 
     public static SoundManager Instance { get; private set; }
 
     private ObjectPoolingManager _gamePool;
 
     // Use this for initialization
     void Awake () 
     {
         // First we check if there are any other instances conflicting
         if(Instance != null && Instance != this)
         {
             // If that is the case, we destroy other instances
             Destroy(gameObject);
             return;
         }
         
         // Here we save our singleton instance
         Instance = this;
 
         MusicLoaded = false;
 
         InitClips();
 
         InitMusic();
 
         InitPool();
 
         // Furthermore we make sure that we don't destroy between scenes (this is optional)
         DontDestroyOnLoad(gameObject);
     }
 
     private void InitMusic()
     {
         MusicLoaded = false;
         AudioClip music = Resources.Load("Audio/MusicFile") as AudioClip;
         music.LoadAudioData();
 
         StartCoroutine(MusicLoadStatus(music));
     }
 
     public void InitPool()
     {
         GameObject audioSource = Instantiate(Resources.Load("Prefabs/GameSFXAudioSource")) as GameObject;
         _gamePool = new ObjectPoolingManager();
         _gamePool.Init(audioSource);
     }
 
     IEnumerator MusicLoadStatus(AudioClip music)
     {
         while (music.loadState != AudioDataLoadState.Loaded) 
         {
             yield return null;
         }
 
         MusicLoaded = true;
         musicSource.clip = music;
         StartMusic();
     }
 
     private void InitClips()
     {
         
         _clips = new List<string>();
 
         _clips.Add("Clips1");
         _clips.Add("Clips2");
         _clips.Add("Clips3");
         _clips.Add("Clips4");
         _clips.Add("Clips5");
         _clips.Add("Clips6");
         _clips.Add("Clips7");
         _clips.Add("Clips8");
     }
 
     public void PlayTapSFX()
     {
         if(PlayerPreference.Instance.SFXOnOff)
         {
             uiSFXSource.Play();
         }
     }
 
     public void PlayGameTapSFX()
     {
         if(PlayerPreference.Instance.SFXOnOff)
         {
             string clipToUse = _clips[Random.Range(0, _clips.Count-1)];
 
             AudioClip clip = Resources.Load("Audio/SFX/" + clipToUse) as AudioClip;
 
             GameObject obj = _gamePool.GetPooledObject();
             obj.SetActive(true);
             AudioManager sfx = obj.GetComponent<AudioManager>();
             sfx.InitClip(clip);
         }
     }
 
     public void StartMusic()
     {
         if(PlayerPreference.Instance.MusicOnOff)
         {
             musicSource.Play();
         }
     }
 
     public void StopMusic()
     {
         musicSource.Stop();
     }
 
 }
 

ObjectPoolingManager

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class ObjectPoolingManager : MonoBehaviour 
 {
     private GameObject pooledObject;
     public int poolSize = 5;
     public bool willGrow = true;
 
     public List<GameObject> poolObjects;
 
     void Start () 
     {
         poolObjects = new List<GameObject>();
     }
 
     public void Init(GameObject _pooledObj)
     {
         
         pooledObject = _pooledObj;
 
         for (int i = 0; i < poolSize; i++) 
         {
             GameObject tempObj = (GameObject)Instantiate(pooledObject);
             tempObj.SetActive(false);
             poolObjects.Add(tempObj);
         }
     }
 
     public GameObject GetPooledObject()
     {
         for (int i = 0; i < poolObjects.Count; i++) 
         {
             if(!poolObjects[i].activeInHierarchy)
             {
                 return poolObjects[i];
             }
         }
 
         if(willGrow)
         {
             GameObject obj = Instantiate(pooledObject);
             obj.SetActive(false);
             poolObjects.Add(obj);
             return obj;
         }
 
         return null;
     }
 }
 

Is there a reason why the initialised prefab pooling collection doesn't persist across the scenes even though the collection has the same collection size across the scenes but the objects in it are null?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Gaming_Project · Feb 17, 2017 at 09:45 AM

I managed to resolve it by ensuring the pooled objects weren't destroyed as well as the object pool itself. So by adding the DontDestroyOnLoad method to the pooling objects initialisation I was able to achieve my desired result.

 public void Init(GameObject _pooledObj)
     {
         poolObjects = new List<GameObject>();
         pooledObject = _pooledObj;
 
         for (int i = 0; i < poolSize; i++) 
         {
             GameObject tempObj = (GameObject)Instantiate(pooledObject);
             tempObj.SetActive(false);
             poolObjects.Add(tempObj);
 
             // Newly created object will now persist across 
             if(canPersistAcrossScenes)
                 DontDestroyOnLoad(tempObj);
         }
     }

Should obviously be used sparingly and have a flag as to whether it should persist across scenes or not

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Make a game object in a scene into a prefab with script 1 Answer

Script inside instantiated prefab run lag behind 1 Answer

How can I have two scripts in the animator panel ? 1 Answer

Audio Clip Playing every frame 2 Answers

NullReferenceException with collisions and audio management script 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges