Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Audio Help with c# gun shot sound on click

Discussion in 'Audio & Video' started by OHYYYYES, Oct 12, 2018.

  1. OHYYYYES

    OHYYYYES

    Joined:
    Oct 10, 2018
    Posts:
    2
    I need help because I searched this up many times and most of the answers were in java and obviously, now there is only c# can someone help me with this same exact code except in c# (side note this might be written in c# idk I am learning it is just ever time I enter it comes up with an error and the thread I got this code off of talking about java)

    1. var _sound : AudioClip;
    2. function Update(){
    3. if (Input.GetButton("Fire1"){
    4. audio.Play("put your sound name here");
    5. }
     
  2. OHYYYYES

    OHYYYYES

    Joined:
    Oct 10, 2018
    Posts:
    2
    And yes I put my sound name where it says "Sound name here" ^
     
  3. willemsenzo

    willemsenzo

    Joined:
    Nov 15, 2012
    Posts:
    585
    Please use code tags when you're posting code. Also it would be useful if you included what specific error you get. From what I understood you want to play a sound whenever you click the mouse, and you need the script in C#.

    Code (csharp):
    1. using UnityEngine;
    2.  
    3. public class AudioExample : MonoBehaviour
    4. {
    5.     public AudioClip _sound;    // this lets you drag in an audio file in the inspector
    6.     private AudioSource audio;
    7.  
    8.     void Start()
    9.     {
    10.         if(_sound == null)
    11.         {
    12.             Debug.Log("You haven't specified _sound through the inspector");
    13.             this.enabled = false; //disables this script cause there is no sound loaded to play
    14.         }
    15.    
    16.         audio = gameObject.AddComponent<AudioSource>(); //adds an AudioSource to the game object this script is attached to
    17.         audio.playOnAwake = false;
    18.         audio.clip = _sound;
    19.         audio.Stop();
    20.     }
    21.  
    22.     void Update()
    23.     {
    24.         if (Input.GetButton("Fire1")
    25.         {
    26.             audio.Play();        
    27.         }
    28.     }
    29. }
    30.  
     
    mattiamelodia likes this.