Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'Editor & General Support' started by BlakeGillman, Jul 2, 2014.

  1. BlakeGillman

    BlakeGillman

    Joined:
    Dec 7, 2013
    Posts:
    412
    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#)

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class randomSound : MonoBehaviour {
    6.  
    7.     public AudioClip[] ricochet; // The array controlling the sounds
    8.     public int rayMax; // The max amount of Sounds there are
    9.     public int pickedSound; // The sound is choose to play
    10.     // Use this for initialization
    11.     void Start () {
    12.         pickedSound = Random.Range(0, rayMax); // Grab a random sound out of the max
    13.         gameObject.GetComponent<AudioSource>.clip = ricochet[pickedSound]; // Tell the AudioSource to become that sound
    14.     }
    15.    
    16.     // Update is called once per frame
    17.     void Update () {
    18.    
    19.     }
    20. }
    21.  
    22.  
    ERROR:

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

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    You forgot the () in the GetComponent call.

    Code (csharp):
    1. gameObject.GetComponent<AudioSource> ().clip = ricochet[pickedSound];
     
  3. BlakeGillman

    BlakeGillman

    Joined:
    Dec 7, 2013
    Posts:
    412
    Glad to see your still on the Forums Daniel, can't say how many times you have helped me :D

    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.
     
  4. BlakeGillman

    BlakeGillman

    Joined:
    Dec 7, 2013
    Posts:
    412
    Any ideas?
     
  5. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Play on awake would play... on awake. Awake is called before Start, so you'll need to manually call the Play method.
    Code (csharp):
    1. AudioSource source = gameObject.GetComponent<AudioSource> ();
    2. source.clip = rocochet[pickedSound];
    3. source.Play ();
     
    lekkii likes this.
  6. BlakeGillman

    BlakeGillman

    Joined:
    Dec 7, 2013
    Posts:
    412