- Home /
Trigger doesn't work in Built version
I'm using Triggers to play different BGMs in different rooms, adding a behavior to the FPS controller, as well as an audiosource to it. The code is as following:
public class NewBehaviourScript : MonoBehaviour {
public AudioSource s;
public AudioClip music1;
public AudioClip music2;
void Start () {
}
void Update () {
}
void OnTriggerEnter(Collider e){
TestGUI.x=0;
if (e.transform.name == "play1") {
s.audio.Stop();
TestGUI.x=10;
s.audio.PlayOneShot(music1);
} else if (e.transform.name == "play2") {
s.audio.Stop();
TestGUI.x=20;
s.audio.PlayOneShot(music2);
}
}
}
where s is given the First Person Controller's audiosource component. On entering trigger "play1", music1 would play, and same for "play2". Also, to test whether the program runs correctly, I've added another variable x, and there's a seperate GUI code TestGUI that draws a texture at x-position. (If trigger is detected, x would become 0, and if the specific zones are acknowledged, such as "play1" or "play2", then not only would music change but also would x become 10 or 20)
This runs perfectly in editor mode, changing BGM and x as I enter different zones. Problem is, after I build and run it, the BGMs cannot be changed, although a trigger is still detected (x becomes 0). The program can't determine which trigger it is, and can't enter the "if" clauses.(Hence x stays 0, but not 10 or 20)
Can somebody help me? Since this is a multiscene project, I figure it might be some problem in namespaces in different scenes? Would it be possible that after build, the e.transform.name would have some prefixes to it, so that e.transform.name=="play1" no longer works?
Or, would there be some other way to play different BGM in different rooms?
Thank you very much!!
Answer by JackofTraes · Mar 13, 2015 at 07:21 AM
Have you tried separating tagging the object(s) in question (collider 'e')?
Once you do this, you will check for the collider:
// This is how you check for a tag.
if (e.tag == "myTag") {
// Do action here.
}
if (e.tag == "myOtherTag") {
// Do other action here.
}
Depending on what your plans for your project, this may or may not be the best solution. If not, I would suggest giving both trigger zones a check with a serialized int and switch statement (if you need more than two BGMs:
[Ranger (1, 10)] // Set the range to whatever you want.
[SerializeField]
private int triggerType = 1;
// Notice that I do not use a tag.
// If you want certain objects to trigger it, provide tag checks.
void OnTriggerEnter (Collider e) {
switch (triggerType) {
case 1:
// Stop Audio
// Set GUI position
// Play BGM
break;
case 2:
// Stop Audio
// Set GUI position
// Play BGM
break;
default:
// Do nothing.
break;
}
}
Hopefully this helps. At the very least, it should give you some ideas on possible solutions.