- Home /
object reference problem
I am getting this really annoying error and I have no idea how to fix it. Hope you can help error CS0120: An object reference is required to access non static member 'Unity.AudioSource.volume' This is my script
using UnityEngine; using System.Collections;
public class volumechange : MonoBehaviour { public static int volume; public AudioSource;
// Update is called once per frame
void Update () {
if (volume == 1)
AudioSource.volume = 10;
if (volume == 0)
AudioSource.volume = 0;
}
}
Answer by robertbu · Dec 20, 2013 at 07:37 PM
AudioSource is the class. What you want is a reference to the actual AudioSource attached to the specific game object (I'm guessing). You can use 'audio'. Note that 'volume' goes from 0.0 to 1.0.
audio.volume = 1.0;
What I am trying to do is to change a specific audiosource (music track) to 0 and 1 chaning using the variables. The audiosource gameobject is called Game $$anonymous$$usic and the script assigned to it is called Volumechange.
I don't fully understand your comment. Is the 'Volumechange' script on the same game object as 'Game$$anonymous$$usic'? If so, the code I outlined will work. If not, then:
AudioSource as;
void Start() {
as = GameObject.Find("Game$$anonymous$$usic").audio;
}
// Update is called once per frame
void Update () {
if (volume == 1)
as.volume = 1.0f;
if (volume == 0)
as.volume = 0.0f;
}
The "Volumechange" script is on the gameobject called Game $$anonymous$$usic. There are two scripts total in the Game $$anonymous$$usic gameobject called "Volumechange" which is c# and "$$anonymous$$usicplay" which is javascript. This is the "$$anonymous$$usicplay" script.
#pragma strict
private static var instance:musicplay;
public static function GetInstance() : musicplay {
return instance;
}
function Awake() {
if (instance != null && instance != this) {
Destroy(this.gameObject);
return;
} else {
instance = this;
}
DontDestroyOnLoad(this.gameObject);
}
It's a bit more complicated than when you first look at it. This is because I want the AudioSource to keep playing a specific music track all the time even when changing scenes. In the same scene where the Game $$anonymous$$usic object is there is also a gameobject called "Game $$anonymous$$anager". This is the script for that.
#pragma strict
var New$$anonymous$$usic: AudioClip; //Pick an audio track to play.
function Awake () {
var go = GameObject.Find("Game $$anonymous$$usic"); //Finds the game object called Game $$anonymous$$usic.
if (go.audio.clip != New$$anonymous$$usic) {
go.audio.clip = New$$anonymous$$usic; //Replaces the old audio with the new one set in the inspector.
go.audio.Play(); //Plays the audio.
}
}