- Home /
Change Audio source on collision
if i have a 1st person controller and 4 cubes named cube1, cube2 , cube3, and cube4. each has attached a 3d audio file. I want the player to collide with cube1, stopping the the audio attached to cube1 and starting the audio attached to cube2 and then the same for the rest till cube4
how would i code this?!
Answer by SubatomicHero · Feb 27, 2013 at 09:10 AM
Hey there,
probably using the OnCollisionEnter() function. Here is what I would do in C#:
public void OnCollisionEnter(Collision other)
{
// Assuming the cube names are cube1, 2 etc
if (other.transform.name == "cube1")
{
other.transform.audio.Stop(); // Stop the sound
GameObject cube2 = GameObject.Find("cube2");
cube2.transform.audio.Play(); // Play the sound
}
}
Obviously you could make the cube1, cube2 public variables so that you can drag them into the script in the inspector, which may make things easier rather than finding the object everytime a collision occurs. All you need to do is add each other condition for the other cubes. You could also use a switch statement:
switch(other.transform.name)
{
case "cube1":
{
// do the same stuff here
break;
}
case "cube2":
{
// etc etc
break;
}
}
I hope this helps! :D
Thanks for the reply! although i tried pasting the top code but i get compiler errors :S
Assets/Change position sound.cs(1,13): error CS0116: A namespace can only contain types and namespace declarations
Assets/Change position sound.cs(2,1): error CS8025: Parsing error
Is the code I gave you on the script attached to the first person controller? Can you supply all the code so I can see it?
public void OnCollisionEnter(Collision other) { // Assu$$anonymous$$g the cube names are cube1, 2 etc if (other.transform.name == "cube1") { other.transform.audio.Stop(); // Stop the sound GameObject cube2 = GameObject.Find("cube2"); cube2.transform.audio.Play(); // Play the sound } }
i have it attached to cube 1. would i not just edit the code depending on the box it is attached to? it doesnt seem to like the 1st line? sorry im pretty new to unity and have used abit of Java, havent used C# before.
Your answer
Follow this Question
Related Questions
Collider + multiple sounds script 1 Answer
How do I make a scene change when my Player collides with a item? 1 Answer
Making a sound play once on collision, can you fix my script? 2 Answers
How can I make my players change colors when they collide? 2 Answers
Volume Slow down and High problem 1 Answer