I want sound only on a clicked area

Hi there,

I have a script that when you click a game object an animation will play with a sound. The thing is that it works, but if I click anywhere on screen the animation and sound also play. I just want the sound to play when the gameobject is clicked.

Does anyone have an idea what goed wrong? Is it in the code or maybe the size of the gameobject? This is my code.

using UnityEngine;
using System.Collections;

public class ScriptLoop : MonoBehaviour {
    public Animator anim; //anim kan ook een andere naam zijn, is willekurig

    private bool deurOpened = false;

    public AudioClip soundFile;
    AudioSource mySound;

    void Awake()
    {
        mySound = GetComponent<AudioSource>();
    }

    // Use this for initialization
    void Start()
    {

    }

     
     void Update()
    {
        MyInput();
    }

    void MyInput()
    {
        if (Input.GetMouseButtonDown(0))
        {
            anim.SetTrigger("deuropen");
            mySound.PlayOneShot(soundFile, 0.8f);

        }
    }

    }

Hopefully someone can help me out. Thanks in advance.

Cheers,

Jonah

This should work as long as the game object has a collider and you only want to use the left mouse button to click on the object. You could use OnMouseUp() or OnMouseUpAsButton() as an alternative to OnMouseDown().

using UnityEngine;
using System.Collections;
 
public class ScriptLoop : MonoBehaviour 
{
     public Animator anim;
     private bool deurOpened = false;
 
     public AudioClip soundFile;
     AudioSource mySound;
 
     void Awake()
     {
         mySound = GetComponent<AudioSource>();
     }
 
     void OnMouseDown()
     {        
         anim.SetTrigger("deuropen");
         mySound.PlayOneShot(soundFile, 0.8f);
     } 
}

@Ahndrakhul Thank you very much. That’s it. It worked!

I have one more question. Is it possible to stop another sound when this code is executed. Something like StopOneShot within the same code?

Thanks again!

Cheers!!! Jonah.