"BCE0020: An instance of type 'UnityEngine.Component' is required to access non static member" while trying to play an AudioClip
Here is my script:
#pragma strict
var maxFallDistance = -10;
var a = false;
var audio : AudioSource = gameObject.GetComponent(AudioSource);
function Update () {
if (transform.position.y <=maxFallDistance && a == false){
RestartLevel();
};
};
function RestartLevel () {
UnityEngine.Component.audio.Play();
yield WaitForSeconds (4);
Application.LoadLevel("Level01");
GameMaster.currentScore = 0;
a = true;
};
Whenever I try to start the game I get the error from the title telling my that an instance of type 'UnityEngine.Component' is required to access non static member 'audio' and redirecting me to UnityEngine.Component.audio.Play();
. Please help I've been stuck on this the whole day I'm about to cry. bump i guess
Answer by Landern · Nov 03, 2016 at 03:03 PM
You "SHOULD" set the variable in the Awake or Start function. Couple other comments about semi-colon use below and calls to the audio source reference.
#pragma strict
var maxFallDistance = -10;
var a = false;
var audio : AudioSource;
function Start () {
audio = gameObject.GetComponent.< AudioSource >(); // Get the actual type, if you do it as you did in the example in your post, it will return a Component type which is not a AudioSouce.
}
function Update () {
if (transform.position.y <=maxFallDistance && a == false){
RestartLevel();
} // don't put a semi-colon here
} // don't put a semi-colon here
function RestartLevel () {
audio.Play(); // Just use the AudioSource reference you set in Start
yield WaitForSeconds (4);
Application.LoadLevel("Level01");
GameMaster.currentScore = 0;
a = true;
} // don't put a semi-colon here
What do I need to get the actual type like you say in line 7? If i just copy and paste your code I still get the BCE0004: Ambiguous reference 'audio': BallHealthGameOver.audio, UnityEngine.Component.audio.
error. And also, how do I use the AudioSource reference I set in start ins$$anonymous$$d of audio.Play()
Your answer
![](https://koobas.hobune.stream/wayback/20220612095850im_/https://answers.unity.com/themes/thub/images/avi.jpg)