0
\$\begingroup\$

im instantiating an object which is gonna play the background music for my game. On the Awake() function I check if there is a gameobject with the tag "MusicPlayer" on it, and if there isn't any I instantiate a prefab (the music player prefab with the tag "MusicPlayer" on it).

Now my issue is this :

It keeps instantiating the prefabs even if there is one or more music players(objects with the "MusicPlayer" tag on them). Why is this happening ?

Here is my code :

var musicPrefab : Transform;

function Awake()
{
    if(GameObject.FindWithTag("MusicPlayer") == null)
    {
        Instantiate(musicPrefab,transform.position,transform.rotation);
    }
}

I also have a script that makes the music player not be destroyed upon the level reload. This is the script :

function Start()
{
    DontDestroyOnLoad (gameObject);
}

Thank you for your time, I hope I was clear enough.

\$\endgroup\$
  • \$\begingroup\$ Are you placing these script on a general purpose GameManager or directly on the MusicPlayer? You make get some value from reading this. \$\endgroup\$ – Kelly Thomas Dec 9 '14 at 9:53
1
\$\begingroup\$

The FindWithTag will throw an error if the Tag is not defined (or perhaps spelled wrong). I think that might have been why it did not work at first, but works now :)

\$\endgroup\$
0
\$\begingroup\$

Ehm...

I don't know whats going on but this is what I did to fix this :

var musicPrefab : GameObject;
var muter : GameObject;

function Awake()
{
    if(GameObject.FindWithTag("MusicPlayer") == null)
    {
        Instantiate(musicPrefab,transform.position,transform.rotation);
        DontDestroyOnLoad (musicPrefab);
        muter = GameObject.FindWithTag("MusicPlayer");
    }

    muter = musicPrefab;
}

You can compare the first script with this one. I don't know how I did it but it works.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.