- Home /
How do you Play sound without having to load it In Inspector?
So i'm gonna have many characters of different types, and they may share sounds they emit.
So dragging sounds to the inspector 1 by 1, for every character type in my scene is tedious.
Can you just access any sound in your Assets and play it from code?
So far what i got is giving me errors saying: Cannot implicitly convert type UnityEngine.Object to UnityEngine.AudioCLip
using UnityEngine;
using System.Collections;
public class PlaySouuunn : MonoBehaviour {
AudioClip vv = Resources.Load("Blow");
void Start(){
audio.PlayOneShot(vv);
}
void Update(){
//do an if or whatever statement
}
}
This one also doesn't work AudioSource.PlayClipAtPoint(clip, transform.position);
So is this the line that has the problem? ---> AudioClip vv = Resources.Load("Blow"); I got this code from a example online, it was an answer here in UnityAnswers i think. but they had it in javascript as:
function PlayFile(file: String){ // file name without extension
var clip: AudioClip = Resources.Load(file);
// example 1: play with PlayOneShot
audio.PlayOneShot(clip);
// example 2: play without an AudioSource component
AudioSource.PlayClipAtPoint(clip, transform.position);
// example 3: play with Play
audio.clip = clip;
audio.Play();
}
So you see i'm basically doing the same
Auddioclip vv = Resources.Load
and then the play.
And yes i have a Resources folder in my assets folder
Answer by Sajidfarooq · Aug 19, 2013 at 04:41 PM
You need to cast the return value from Resource.Load into an AudioClip.
AudioClip vv = Resources.Load("Blow") as AudioClip;
Also remember to put the audio clip in a folder called "Resources", since that is where the Resources.Load expects it to be.
Still doesn't work.
It says There is no AudioSource attached to the BBB game object, but a script is trying to access it.
AudioSource is required for any sound and wont be affected by however you set up the sound clips. Just add it from Component > Audio > Audio Source
Remember to mark this question as "answered" if it has indeed answered your question.
Answer by kwokman · May 29, 2015 at 09:18 AM
You can try the simple:
AudioSource audio = gameObject.AddComponent < AudioSource > ();
audio.PlayOneShot ((AudioClip)Resources.Load ("blow"));
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How to emit a sound on specific collision. 1 Answer
Audio Play Once 2 Answers
Can anyone help me invert this simple script? 2 Answers
Fade In/Out Audio After Enter Trigger 3 Answers