Hi All -
Still in my first week of learning Unity, so I apologize for all of the questions. This forum has been incredible, though - so I hope this one won’t be too tough:
I have a folder of sound files, numbered 1 through 100. I’d like to attach each one, looping, to a sphere object that is instantiated in space. Is such a thing possible in Unity?
Thanks
I’m pretty sure the first piece of the puzzle is loading an array via Resources.LoadAll, but I’m having a difficult time. I was thinking something like the following might work, but I get a “Cannot convert type ‘UnityEngine.Object’ to ‘UnityEngine.AudioSource’ via a reference conversion…” message.
private AudioSource audioSource;
public AudioClip[] soundarray;
private AudioClip playedsound;
void Start()
{
audioSource = gameObject.GetComponent<AudioSource>();
soundarray = Resources.LoadAll("Relieve") as AudioSource;
int index = Random.Range(0, 200);
playedsound = soundarray[index];
audioSource.clip = playedsound;
audioSource.Play();
}
Hey there,
you have 2 options for this, depending on what you actually want to do with it.
So first up you can add one AudioSource to your sphere and use PlayOneShot() (instead of Play()) to dynamically let it play whatever you want it to play from an array of loaded audiofiles.
The second choice is to add a source for every sound that you have, which makes it easier (or even possible at all, there i’m not 100% sure) to play any sound you want and also to play sounds simultaniously with more control over the different sounds.
For your current script you introduce an array named “soundarray” of type AudioClip and you try to Load Your Objects as “AudioSource”. Which ofc will not work. Change it to as AudioClip
and try again.
I hope this helps so far, let me know if you can specify your goals with this project.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ResourcesTest : MonoBehaviour {
Object[] clips;
int i;
void Start () {
clips=Resources.LoadAll("Sounds",typeof(AudioClip));
InvokeRepeating("Play",1,1);
}
void Play() {
AudioSource.PlayClipAtPoint((AudioClip)clips*,transform.position);*
-
i++;*
-
if (i>=clips.Length)*
-
i=0;*
- }*
}