Play random sound clip on collision (Unity)
I have 4 sound files which are landing noises that I want the player to do when hitting the ground, no sound is currently playing. New to C # and programming needs a little help.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class Bhop : MonoBehaviour{
public AudioClip[] list;
AudioSource audio;
CharacterController characterController;
int number;
void Start ()
{
audio = GetComponent<AudioSource>();
characterController = GetComponent<CharacterController>();
//Loading the items into the array
list = new AudioClip[]
{
(AudioClip)Resources.Load("Sound/jumplanding1.wav"),
(AudioClip)Resources.Load("Sound/jumplanding2.wav"),
(AudioClip)Resources.Load("Sound/jumplanding3.wav"),
(AudioClip)Resources.Load("Sound/jumplanding4.wav")
};
}
void OnCollisionEnter (Collision col)
{
int number;
number = Random.Range(0, list.Length);
if (col.gameObject.name == "Sound")
{
audio.PlayOneShot(list[number], 0.5f);
}
}
}
source to share
If you've added a script to the GameObject before adding the line [RequireComponent(typeof(AudioSource))]
, you most likely don't have an Audio Source for your GameObject (check your inspector). If so, you can:
- manually add the Audio Source component to the Inspector, or
- remove and then re-attach the script to the GameObject, which will automatically add the Audio Source component to it . If you are using a public variable
AudioClip
for your audio file (OP is not), remember to drag and drop the audio asset into the public variable again (this is cleared by script re-attachment).
source to share
Here Mate
Instructions: 1 - attach this to any game object 2 - put a game object with an AudioSource component in mySource 3 - Let's say you have 3 audio clips that you want to use, set Scan Range and My Audio Items to 3 4 - add 3 clips as 5 items - Turn on Debug to get a list of clips on the console, but they also show up in the editor when playing the game
Tips: This is included, so every time this object allows it to trigger a new range and assign a clip, hope this helped me about 5 minutes if it helps you think about following my facebook dev group HERE
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class randomSound : MonoBehaviour {
public AudioSource mySource;
public int rangeScan;
public AudioClip[] myAudio;
public int toPlay;
public bool debugging;
void OnEnable () {
toPlay = Random.Range(0,rangeScan);
if (debugging) {
foreach (AudioClip value in myAudio) {
print (value);
}
}
mySource.PlayOneShot(myAudio[toPlay], 0.9F);
mySource.Play ();
}
}
source to share