TyDoesStuff
TyDoesStuff

Reputation: 23

Unity 5 C# - DontDestroyOnLoad(); Not Working

I have a very simple problem in Unity that I can't seem to solve. I want to have seamless music looping between scenes. Currently, I have an empty game object named "BGMusic" with a custom tag of "Music". It has an audio source and script attached. The following script, however, has not been working for me:

using UnityEngine;
using System.Collections;

public class Music : MonoBehaviour {
    void Awake()
    {
        GameObject[] objs = GameObject.FindGameObjectsWithTag("Music");
        if (objs.Length > 0)
        {
            Destroy(gameObject);
        }
        DontDestroyOnLoad(gameObject);
    }
}

I found this code sample from a YouTube video titled Playing Seamless Music Across Scenes in Unity 5 With Non-Destroyable Object. All of the comments said that it worked for them, but it seems to have no effect on my game object at all. I have even tried just doing the following:

void Awake()
{
    DontDestroyOnLoad(gameObject);
}

(Class name and imports are the same)

I am very confused, and any help on this subject would be greatly appreciated. All other similar posts were crowded with useless code or were done in JavaScript. Thank you for your time.

-Ty

Upvotes: 0

Views: 350

Answers (1)

nipercop
nipercop

Reputation: 387

Your code must be:

if (objs.Length > 1)  // not 0 
{
    Destroy(gameObject);
}

In video she wrote 1, but you wrote 0 and when code runnig this GameObject destroyed himself every time!

Be attentive !

Upvotes: 1

Related Questions