How do i play audio in a script

Ok i have a script for picking shit up that looks like this

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class pickupObject : MonoBehaviour
{

    public Transform pickupTransform;

    void OnMouseDown()
    {
        GetComponent<Rigidbody>().useGravity = false;
        GetComponent<Rigidbody>().freezeRotation = true;
        GetComponent<MeshCollider>().enabled = false;
        this.transform.position = pickupTransform.position;
        this.transform.parent = GameObject.Find("objectPickupTransform").transform;
    }

    void OnMouseUp()
    {
        this.transform.parent = null;
        GetComponent<MeshCollider>().enabled = true;
        GetComponent<Rigidbody>().useGravity = true;
        GetComponent<Rigidbody>().freezeRotation = false;
    }

}

and basically on the void OnMouseUp bit i need it to play a sound but i have no fuckin clue how to do that.

The object its set up on has an audio source with the clip i want to play already shoehorned into it. I just need to know what i have cram into that void to get it to play.

Bonus points to anyone who could get it to play another sound on the void OnMouseDown bit

Something like this, added using your script, should work…

You can probably use GetComponent directly as you have been doing, or set it in the inspector. I’ve only set it in Start as an example.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class pickupObject : MonoBehaviour
{
    public Transform pickupTransform;
    public AudioSource audioSource;
    public AudioClip mouseDownAudioClip;
    public AudioClip mouseUpAudioClip;

    void Start()
    {
        audioSource = gameObject.GetComponent<AudioSource>();
    }

    void OnMouseDown()
    {
        GetComponent<Rigidbody>().useGravity = false;
        GetComponent<Rigidbody>().freezeRotation = true;
        GetComponent<MeshCollider>().enabled = false;
        this.transform.position = pickupTransform.position;
        this.transform.parent = GameObject.Find("objectPickupTransform").transform;
        audioSource.PlayOneShot(mouseDownAudioClip, 1);
    }
    void OnMouseUp()
    {
        this.transform.parent = null;
        GetComponent<MeshCollider>().enabled = true;
        GetComponent<Rigidbody>().useGravity = true;
        GetComponent<Rigidbody>().freezeRotation = false;
        audioSource.PlayOneShot(mouseUpAudioClip, 1);
    }
}

For other options for playing audio I wrote a whole article on the different methods and when to use each, which you can find here: Blog - John Leonard French

Hope that helps.

3 Likes