Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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.

share|improve this question
    
Are you placing these script on a general purpose GameManager or directly on the MusicPlayer? You make get some value from reading this. –  Kelly Thomas Dec 9 '14 at 9:53

2 Answers 2

up vote 0 down vote accepted

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.

share|improve this answer

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 :)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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