我正在研究 Unity5 上的 Stealth 教程。在我编写“Alarm Light”脚本时,出现了这个错误
Assets/AlarmLight.cs(28,31): error CS0120: An object reference is required to access non-static member `UnityEngine.Light.intensity'
这是整个脚本;
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;
}
}
}
}
最佳答案
基本上,编译器告诉您的是您正在尝试像静态成员一样使用实例成员,这显然是不正确的。
查看代码中的这一行
else {
Light.intensity = Mathf.Lerp (GetComponent<Light>().intensity, 0f, fadeSpeed * Time.deltaTime);
}
在右侧,您使用 GetComponent<Light>().intensity
,这是访问单个光强度的正确方法。
然而,在左侧,您使用的是 Light.intensity
. Light
类没有任何名为 intensity
的静态成员,因此出现错误。
将您的代码更改为
else {
GetComponent<Light>().intensity = Mathf.Lerp (GetComponent<Light>().intensity, 0f, fadeSpeed * Time.deltaTime);
}
你的错误应该会消失。
这样想。您可以分别更改每盏灯的强度,对吗?因此,它必须是类实例的成员,而不是类本身。
如果更改单个值会影响使用它的所有内容(例如 Physics.gravity),则这些是类的静态成员。请牢记这一点,您就不会弹出此问题。
关于c# - Unity5错误CS0120,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32535514/