play sound from an array
Ive spent 24 hours going around in circles with this, and it seems like nothing is compatible, or items are depreciated and obsolete. I know there must be a way. I have an array, I can print random items from the array. I can also play an individual audio.clip. But as soon as I try to put it all together I get incompatibility errors.
Ive commented out lines that I have tried and failed on. Any help would be greatly appreciated.
#pragma strict
//var MetalHits: AudioClip;
public var MetalHits:AudioClip[];
//public var MetalHits:AudioClip;
function Start()
{
//MetalHits = GetComponent.<AudioSource>();
}
function OnCollisionEnter(collision: Collision)
{
for (var contact: ContactPoint in collision.contacts) {
Debug.DrawRay(contact.point, contact.normal, Color.white);
}
if (collision.relativeVelocity.magnitude > 2)
//AudioSource.Play(MetalHits, transform.position);
// audio.PlayOneShot(MetalHits[1]);
//audio.Play();
//audio.PlayOneShot(MetalHits[Random.Range(0,MetalHits.Length)]);
// MetalHits.Play();
Debug.Log("mag hit "+collision.relativeVelocity.magnitude);
}
Answer by Statement · Nov 23, 2015 at 03:17 PM
//var MetalHits: AudioClip;
...
//MetalHits = GetComponent.<AudioSource>();
Looks like you've been trying to store the audio source component in an audio clip reference. That won't work. Store the audio source component in an audio source reference. I haven't tested the following, but perhaps it's closer to where you want to be?
var MetalHits : AudioClip[];
private var audioSource : AudioSource;
audioSource = GetComponent.<AudioSource>();
function OnCollisionEnter(collision : Collision)
{
DrawCollisionNormals(collision);
PlayCollisionSound(collision);
}
function DrawCollisionNormals(collision : Collision)
{
for (var contact : ContactPoint in collision.contacts)
Debug.DrawRay(contact.point, contact.normal, Color.white);
}
function PlayCollisionSound(collision : Collision)
{
if (collision.relativeVelocity.magnitude > 2)
PlayRandomClip(MetalHits);
}
function PlayRandomClip(clips : AudioClip[])
{
var clip = clips[Random.Range(0, clips.Length)];
audioSource.PlayOneShot(clip);
}
Answer by D-Coy · Nov 23, 2015 at 03:54 PM
Thank you! Works perfectly! I had read that you could temporarily instantiate the audioSource and then play from it, but nothing worked... at least the way I tried. Thanks again, Ill play around with this so to get a better understanding.