Home > Mobile >  How to keep variables with DontDestroyOnLoad unity
How to keep variables with DontDestroyOnLoad unity

Time:02-24

I'm quite new to unity and programming in general and I'm using "DontDestroyOnLoad (gameObject);" in a script that manages the all sounds played in the game, I run in to a problem that things like pause and unpause stop working when I load into another scene even though DondtDestroyOnLoad is on, it gives me a NullReferenceException error so i think that when loading a new scene it empty's the variables. does anyone now a way to prevent that from happening?

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();


    }

}

CodePudding user response:

You can add DontDestroyOnLoad to its array

like this

for(int i = 0; i < sounds.Length;)
{
   DontDestroyOnLoad(sounds[i]);
   i  ;
}

Or you can search for sounds in Scane

by using :

GameObject.Find

GameObject.FindGameObjectsWithTag

Object.FindObjectOfType

  • Related