- Home /
Cannot access AudioSource from within function
Alrighty, I'm a newbie newb to Unity following Brackey's tutorial for making a Pong clone.
For the life of me I can't get the audio to play. The method used in the video caused the sound effects to play when the game started, even though "Play On Awake" is disabled. Well, that won't work. So I thought I'd manually call the audio myself via the existing functions.
I have a script "gamesetup" that handles the assets:
#pragma strict
var mainCamera : Camera;
var topWall : BoxCollider2D;
var bottomWall : BoxCollider2D;
var leftWall : BoxCollider2D;
var rightWall : BoxCollider2D;
var player1 : Transform;
var player2 : Transform;
var scoreSound : AudioClip;
var hitSound : AudioClip;
...
And the script "gameManager" that handles the scores:
#pragma strict
static var player1Score : int = -1;
static var player2Score : int = -1;
var textSkin : GUISkin;
static function scoring (wallName : String) {
if (wallName == "rightWall") {
player1Score += 1;
//Debug.Log("hit right");
}
else if (wallName == "leftWall") {
player2Score += 1;
//Debug.Log("hit left");
}
else {
//Debug.Log("Je ne suis pas un mur");
}
//Debug.Log("P1: "+player1Score);
//Debug.Log("P2: "+player2Score);
gamesetup.scoreSound.Play();
}
However, any approach I try to call the sound variable from within scoring() results in error:
Assets/gameManager.js(23,19): BCE0020: An instance of type 'gamesetup' is required to access non static member 'scoreSound'.
Explicitly declaring the AudioSource variables public did not work, and also prevented me from assigning the sound clip from the Inspector.
Declaring the variables static had a similar effect.
It does not appear to matter where I call the line gamesetup.scoreSound.Play();
within that script; it just gives the same error.
Now, I've programmed before, mostly in PHP but nonetheless I'm not a complete noob. I'm pretty certain that if something is global/public/what have you by default, it means exactly that, and should not have this problem. Are individual scripts in Unity treated as their own scope? What am I missing?
Your answer
Follow this Question
Related Questions
Access a variable from another script in update function 1 Answer
Can I declare a variable inside a function which has instance scope? 1 Answer
Scope issues when initializing variables 2 Answers
Script not responding to public variable change 1 Answer
Accessing variable from a method in another script and gameObject 2 Answers