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?!

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! :smiley: