【问题标题】:Why am I getting error CS0120 if I have no "static" in my code?如果我的代码中没有“静态”,为什么会出现错误 CS0120?
【发布时间】:2021-01-02 04:45:16
【问题描述】:

我正在制作 FPS 游戏,我正在尝试一些枪支脚本,但 Unity 一直显示错误 CS0120,但问题是我没有使用任何“静态”或需要它的东西,至少我认为我没用。

主要代码:

{
    public float damage = 10f;
    public float range = 100f;

    public Camera fpsCam;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Shoot();
        }
    }

    void Shoot()
    {
        RaycastHit hit;
        if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
        {
            Debug.Log(hit.transform.name);

            healthPoints hp = hit.transform.GetComponent<healthPoints>();
            if(hp != null)
            {
                //Here is where I get the error
                healthPoints.TakeDamage(damage);
            }

        }
    }

}

HP 代码:

public class healthPoints : MonoBehaviour
{
    public float health = 100f;

    public void TakeDamage(float amount)
    {
        health -= amount;

        if (health <= 0f)
        {
            Die();
        }
    }

    void Die()
    {
        Destroy(gameObject);
    }
}

“错误 CS0120 非静态字段、方法或属性‘healthPoints.TakeDamage(float)’需要对象引用”

【问题讨论】:

  • 你有一个名为hp的实例,但你在类而不是实例上调用healthPoints.TakeDamage()
  • 错误告诉你需要做什么;由于TakeDamage 方法不是static,您需要使用对healthPoints 类的引用才能调用它(您在hp 中拥有)。

标签: c# unity3d raycasting


【解决方案1】:

这段代码sn-p的问题是,你必须使用实例化对象hp,而不是类healthPoints来调用非静态方法TakeDamage()

if(hp != null)
{
   // Here is where I get the error
   hp.TakeDamage(damage);
}

只有类的静态方法才能被访问,而无需先实例化类的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多