c# - Unity5错误CS0120

标签 c# unity3d

我正在研究 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/

相关文章:

c# - Unity 检查器中不再显示具有动态参数的 UnityEvent

c# - 如何有效地删除空目录(和空子目录)

c# - Visual Studio 设置命令参数

c# - Scrollview 内的网格不通过鼠标滚轮滚动

c# - Unity 后处理 PostProcessEffectRenderer 显示在编辑器中但不在构建中

debugging - 连接到设备时,如何在 MonoDevelop Unity 中查看 Debug.Log 输出?

C# Web 应用程序调优 : PerformWaitCallback

c# - 如何缩放字体以适合指定的矩形

c# - 在 Unity3D 实例化的 UI 元素之间创建导航

c# - 如何使用脚本更改 Unity UI 中的占位符文本?