[Solved] How to change the Clip in an AudioSource? C#

Im trying to pick a random sound picked from an array, then make the AudioSource become that sound. I cant figure out what Im doing wrong D;

Script: (C#)

using UnityEngine;
using System.Collections;

public class randomSound : MonoBehaviour {

    public AudioClip[] ricochet; // The array controlling the sounds
    public int rayMax; // The max amount of Sounds there are
    public int pickedSound; // The sound is choose to play
    // Use this for initialization
    void Start () {
        pickedSound = Random.Range(0, rayMax); // Grab a random sound out of the max
        gameObject.GetComponent<AudioSource>.clip = ricochet[pickedSound]; // Tell the AudioSource to become that sound
    }
   
    // Update is called once per frame
    void Update () {
   
    }
}

ERROR:

Assets/Game/FX/randomSound.cs(12,28): error CS0119: Expression denotes a method group', where a variable’, value' or type’ was expected

You forgot the () in the GetComponent call.

gameObject.GetComponent<AudioSource> ().clip = ricochet[pickedSound];

Glad to see your still on the Forums Daniel, can’t say how many times you have helped me :smile:

It works now but it no longer plays a sound?
It picks a random sound, but that sound never actually plays. Its set to play on awake too.

Any ideas?

Play on awake would play… on awake. Awake is called before Start, so you’ll need to manually call the Play method.

AudioSource source = gameObject.GetComponent<AudioSource> ();
source.clip = rocochet[pickedSound];
source.Play ();
1 Like

Thx