Reputation: 21
I'm working on Stealth tutorial on Unity5. While I was writing the "Alarm Light" script, this error showed up
Assets/AlarmLight.cs(28,31): error CS0120: An object reference is required to access non-static member `UnityEngine.Light.intensity'
Here is the entire script;
using UnityEngine;
using System.Collections;
public class AlarmLight : MonoBehaviour {
public float fadeSpeed = 2f;
public float highIntensity = 2f;
public float lowIntensity = 0.5f;
public float changeMargin = 0.2f;
public bool alarmOn;
private float targetIntensity;
void Awake(){
GetComponent<Light>().intensity = 0f;
targetIntensity = highIntensity;
}
void Update()
{
if (alarmOn) {
GetComponent<Light>().intensity = Mathf.Lerp (GetComponent<Light>().intensity, targetIntensity, fadeSpeed * Time.deltaTime);
CheckTargetIntensity ();
}
else
{
Light.intensity = Mathf.Lerp (GetComponent<Light>().intensity, 0f, fadeSpeed * Time.deltaTime);
}
}
void CheckTargetIntensity (){
if (Mathf.Abs (targetIntensity - GetComponent<Light>().intensity) < changeMargin) {
if (targetIntensity == highIntensity) {
targetIntensity = lowIntensity;
}
else {
targetIntensity = highIntensity;
}
}
}
}
Upvotes: 2
Views: 132
Reputation: 2516
Basically, what the compiler is telling you is that you're trying to use an instance member like a static member, which obviously, is incorrect.
Look at this line in your code
else {
Light.intensity = Mathf.Lerp (GetComponent<Light>().intensity, 0f, fadeSpeed * Time.deltaTime);
}
On the right hand side, you use GetComponent<Light>().intensity
, which is the correct way of accessing a single Light's intensity.
On the LEFT hand side, however, you're using Light.intensity
. The Light
class does not have any static member named intensity
, and hence the error.
Change your code to
else {
GetComponent<Light>().intensity = Mathf.Lerp (GetComponent<Light>().intensity, 0f, fadeSpeed * Time.deltaTime);
}
and your error should go away.
Think about it this way. You can change the intensity of each of your lights seperately, correct? Therefore, it MUST be a member of an instance of the class, rather than the class itself.
If changing a single value effects everything that uses it, (such as Physics.gravity), then those are static members of the class. Keep that in mind, and you won't have this issue pop up.
Upvotes: 1