- Home /
On trigger , sound play
hi I Made a cube underwater as triger... then I wrote this script :
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
MotionBlur MB;
void Start ()
{
MB = (MotionBlur) gameObject.GetComponentInChildren<MotionBlur>();
}
void OnTriggerEnter()
{
MB.enabled = true;
}
void OnTriggerExit ()
{
MB.enabled = false;
} }
so when I go under water (trigger cube) motion blur will enabled... but I also wanted to Play a sound when I get to that triger... like under water effect... I know I should use play.sound , but how can I direct it to my specific sound?
Answer by crazyKnight · Aug 04, 2011 at 10:24 AM
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
AudioClip MyClip;
void Start () {
}
void Update () {
}
void OnTriggerEnter(Collider info)
{
if(info.gameObject.tag == "Tag Name of our object")
{
audio.Play();
}
}
void OnTriggerExit(Collider info)
{
if(info.gameObject.tag == "Tag Name of our object")
{
audio.Stop();
}
}
}
Answer by roamcel · Aug 04, 2011 at 11:07 AM
First of all, you must add an audio source to your cube-collider object.
Secondly, I'd rather suggest you create a simple script called "SoundEffect" that you attach to the water (pay attention to the capital letters when defining variables and class names. with this single instruction inside
var audioClip : AudioClip;
Then you go and drop the "splash.wav" file you've chosen for the audio splash effect into the inspector.
In your code, OnTriggerEnter MUST be redeclared with the collider info like crazyknight suggests, and then you simply add there
var soundeffect: SoundEffect = info.GetComponent(SoundEffect); //SoundEffect is the name of the class you created and that you attached to the water
audio.clip = soundeffect.audioClip;
audio.Play();
Assigning the "SoundEffect" component to other objects will let you play audio when the cube-collider object interacts with them, too.
Your answer
Follow this Question
Related Questions
Sound Trigger 2 Answers
How to have audio only be heard in a certain radius? 4 Answers
How to get sound to play on barrel Explosion 1 Answer
Trigger sound when walking through cube trigger 3 Answers
Object Sound Trigger 1 Answer