hamel123 hamel123 - 2 days ago 4
C# Question

Sound is playing multiple times when look at an object

I'm learning about

raycasting
in
unity3d
and facing a audio problem. What I'm doing is there is a
Main Camera
which attached with a script called
NewCast
. That
Main Camera
cast a ray to the cube which has a component called
box collider
. Ray casting is working fine, when looking at that cube. I'm playing a sound. It means when camera looking at that object ray is cast to the cube. But why audio is playing multiple times. I want to play that audio only one time, when i look at that object and repeat this procedure again and again. Package link.
Picture

Code:

public class NewCast : MonoBehaviour
{


private RaycastHit hit;

bool playAudio1;

[SerializeField]
private AudioSource source;


[SerializeField]
private AudioClip clip1;



private void Start()
{
source.clip = clip1;
playAudio1 = true;

}

private void Update()
{

if (Physics.Raycast(transform.position, transform.forward, out hit,9f))
{

if (hit.collider.gameObject.name == "Cube")
{
playAudio1 = false;

if (!playAudio1)
{
source.Play();

if (!source.isPlaying)
{
playAudio1 = true;

}
}
}

}

}

}

FLX FLX
Answer

Everytime the collider is hitting, you're setting playAudio1 to false so the next condition is always true and so the sound will always play...

 if (Physics.Raycast(transform.position, transform.forward, out hit,9f))
    {
        if (hit.collider.gameObject.name == "Cube"){
            if (!source.isPlaying){
                source.Play();
            }
        }
    }

If you want to play only ONCE per look to object :

public class NewCast : MonoBehaviour
{


private RaycastHit hit;

bool soundPlayed = false;

[SerializeField]
private AudioSource source;


[SerializeField]
private AudioClip clip1;


private void Start()
{
    source.clip = clip1;
}

private void Update(){
    if(Physics.Raycast(transform.position, transform.forward, out hit,9f)){
        if (!soundPlayed && hit.collider.gameObject.name == "Cube"){
            if (!source.isPlaying){
                source.Play();
                soundPlayed = true;
            }
        }
    }else{
       if(soundPlayed) soundPlayed = false;
    } 
}

}
Comments