can someone explain me this code....
i was trying to add background music by creating a empty gameobject and attaching script. Initially i tried to use GameObject.DontDestroyOnLoad(gameObject) ; but it was creating some error as the bg sound was being loaded the amount of time the scene was loaded. Then I searched internet and i found the folllowing code.. This code is working fine and error free , but i have a problem understanding it..
I have a ques:-
using UnityEngine;
using System.Collections;
public class musicPlayer : MonoBehaviour {
static musicPlayer instance = null;
void Start () {
if (instance != null){
Destroy(gameObject);
print ("Destructed");
} else {
instance = this;
GameObject.DontDestroyOnLoad(gameObject);
}
}
}
I want to know that how the code is being executed i.e for the first time if i run code the ELSE command is being executed but the second time, instance become equal to musicPlayer instance and therefore IF command executes, and destroys the instance created by the previous running of ELSE command , then how is the musicPlayer keeps on running , since it should have been destroyed by the IF command and also the ELSE command was not executed
I have read it that Static variable is not able to make instance , then how come here the instance of music player was created..
Answer by Baste · Sep 11, 2015 at 06:30 PM
What you're looking at there is the singleton pattern, and a somewhat clumsy way of implementing it.
The idea is essentially "there should only be one of this kind of object ever existing, and if I by mistake add another one, destroy it".
The important thing to note here is that Start is only called once: when the object first becomes active. The if (instance != null) part is to allow you to place one of these in every scene. That means that you can start testing your game from every scene, but if you move to another scene, the current music player will continue playing it's music, while the music player in that level will be destroyed.
A static variable is just a variable that's global to the class, instead of a variable that lives on a per-object basis. This means that every musicPlayer's instance variable is the same thing - if you change it for one, you change it for all.
This thing:
else {
instance = this;
GameObject.DontDestroyOnLoad(gameObject);
}
is basically your music player saying "Okay, there's no other music players that exist. That means that I am the music player, and all other music players will be destroyed"
Your answer
Follow this Question
Related Questions
Audio Cutting Out Unexplainably 1 Answer
Play sound on collision doesnt actually play it 0 Answers
Distance delay for sound 3 Answers
How can I make my script play on it's own without using an input button? 1 Answer
Sonido sobre superficies 0 Answers