Help to play music whenever the character enters a GameObject...
I'm making a simple project where whenever my 3D character enters in a GameObject a music starts to play in eternal Loop and when the character leave out the GameObject the song stops playing, and when he enter into the GameObject again the music plays again from the beginning.
But I'm just getting to make it once (then when my character comes back into the GameObject no longer plays any music... this is like if the GameObject had been destroyed after he leaves the GameObject).
Please, I need your help to fix it.
using UnityEngine;
using System.Collections;
public class PlaySound : MonoBehaviour
{
AudioSource audio;
void Start()
{
audio = GetComponent<AudioSource>();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
GetComponent<AudioSource>().Play();
audio.loop = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
GetComponent<AudioSource>().Stop();
audio.loop = false;
}
}
}
I don't have any problem with your current script.
Are you sure:
the tag of the inco$$anonymous$$g object does not change?
the physics components (trigger / rigidbody) do no change?
the object with the
PlaySound
isn't disabled?
Answer by jihadkhawaja · Dec 22, 2019 at 09:28 PM
try this one, it’s the same but maybe getting the component again is causing any issue.
using UnityEngine;
using System.Collections;
public class PlaySound : MonoBehaviour
{
AudioSource audio;
void Start()
{
audio = GetComponent<AudioSource>();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
audio.Play();
audio.loop = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
audio.Stop();
audio.loop = false;
}
}
}
Your answer
Follow this Question
Related Questions
C# - How can i solve this door problem in script? Can someone help me? 1 Answer
math.Lerp not correct? 1 Answer
Im trying to turn off a sound when i leave a trigger collider 0 Answers
OnTriggerExit2D doesn't work when one of gameObject setActive false. 0 Answers
OnTriggerEnter and OnTriggerExit behaving unexpected 1 Answer