Home > Blockchain >  Colliders and sound
Colliders and sound

Time:12-17

When I enter a collider for a certain game object I would like to play a different sound according to whether its the first time entering the sphere collider or the 2nd or 3rd time. Can this all be written in the same script?

CodePudding user response:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    //attach in inspector or make private and get with code in the Start()
    public AudioSource audioSource1; 
    public AudioSource audioSource2; 

    void Start() {
        // get audioSources optional
    }
    int colCounter = 0;
    void OnCollisionEnter(Collision collision) {
        colCounter  ;
        if (colCounter == 1)
            audioSource1.Play();
        else
            audioSource2.Play();
    }
}
  • Related