如何统一解决错误(cs0120)?

时间:2019-04-28 05:54:21

标签: c# unity3d

我试图统一按下按钮以提高播放器的速度。但是,每次我运行它时。它给了我

  

错误CS0120:非静态需要对象引用   字段,方法或属性“ PlayerController.speed”

我已经尝试过更改代码的顺序,那该怎么办?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Upgrader1 : MonoBehaviour
{

    void Start()
    {
        GameObject Player = GameObject.Find("Player");
        PlayerController PlayerController = Player.GetComponent<PlayerController>();
    }

    public void Upgrade1()
    {
        PlayerController.speed++;
    }
}

2 个答案:

答案 0 :(得分:0)

public class Upgrader1 : MonoBehaviour
{

PlayerController PlayerController; //It should be member variable

void Start()
{
    GameObject Player = GameObject.Find("Player");
    PlayerController = Player.GetComponent<PlayerController>();
}

public void Upgrade1()
{
    PlayerController.speed++;
}
}

答案 1 :(得分:0)

使用适当的命名约定始终是一件好事。

    PlayerController _PlayerController; 
void Start() {

     GameObject Player = GameObject.Find("Player"); 
     _PlayerController = Player.GetComponent<PlayerController>();

  } 

  public void UpgradeSpeed() // I changed the name according to its functionality 
  {
     _PlayerController.speed++; 
  }

有了这个,您不会再错误地输入PlayerController类引用。