I am building a 3D game, and I have some water in the scene. I have attached to it a trigger collider. When the player character's collider enters the water's trigger collider, a splash sound will play. The same happens when the character exits the water.
Now I have added another collider child of the player gameObject. As I did expect, now when the player enters the water, two different colliders hit the trigger so it produces two sounds. What I would like to do is to check to see if the collider that activated the trigger is actually the player or no, so it can play the sound only once, as it did before and as it should do.
This is what i tried to do.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Splashwater : MonoBehaviour
{
public AudioSource audioSource;
public AudioClip splashInWater;
private bool isInTheWater = false;
public GameObject player;
private void OnTriggerEnter(Collision collision)
{
if (collision.gameObject == player)
{
audioSource.PlayOneShot(splashInWater);
}
}
private void OnTriggerExit(Collision collision)
{
if (collision.gameObject == player)
{
audioSource.Stop();
audioSource.PlayOneShot(splashInWater);
}
}
}
Note: I assigned to player
the gameobject of the player character in the inspector.
I'm sure there is a simple way to do this. I did not yet find any solutions that could fix my problem.
Any help is highly appreciated!