Unity 错误 [错误 CS0120:非静态字段、方法或属性"Zoney.setMonney(int)"需要对象引用]



我一直得到这个错误,但我甚至不知道什么是或不是静态在这个上下文中?我已经尝试了解决方案,如设置实例和检查资本化,但我只是得到同样的错误。我希望商店脚本更改货币值,这将被写入调试,直到我设置正确的ui

Zoney脚本:

using UnityEngine;
using UnityEngine.UI;

public class Zoney : MonoBehaviour
{
public Text Money;
public int Monney;
private string Mony;

// Start is called before the first frame update
void Start()
{
Money = GetComponent<Text>();
}
public void setMonney(int Change) 
{
Monney = Change;
}   

// Update is called once per frame
void Update()
{          
Mony = Monney.ToString();
Money.text = Mony;
}
}

The Shop script:

using UnityEngine;

public class Shop : MonoBehaviour
{
public int Change;

// Start is called before the first frame update
void Start()
{
}

// Update is called once per frame
void Update()
{
Change += 1;
Zoney.setMonney(Change);
Debug.Log(Change);
}
}

因为你使用的是Unity,所以你需要遵循引擎的要求。

在这种情况下,你需要一个组件的实例(MonoBehaviour),你真的想引用一个Unity创建的实例,而不是用new关键字创建一个新的。使用new关键字创建组件实例将留给你一个与任何Unity GameObject都不相关的类实例。

获得你想要引用的组件的更可靠的方法是使用Inspector窗口,并将所需对象上的正确组件拖到对象字段中。在这种情况下,我将假设你想要拖动一个场景对象(在你的层次结构中)到对象字段槽。

首先要定义一个变量。这通常可以通过以下两种方式之一完成:

  1. public Zoney zoney;
  2. [SerializeField] private Zoney zoney;

在本例中,一旦分配了引用,请使用变量zoney,而不是类名Zoney。注意,你的变量名可以是任何你认为合适的名称,例如_zoneymyZoney

您的新Shop脚本可能看起来像这样:

public class Shop : MonoBehaviour
{
public int Change;
public Zoney zoney;

void Update()
{
Change += 1;
zoney.setMonney(Change);
Debug.Log(Change);
}
}

Zoney是一个类,在使用它之前需要先创建一个实例。

实例化从MonoBehaviour派生的类

同样重要的是,你需要更新你的shop对象,使它有Zoney实例作为成员对象,否则你对money的更新将不会被保留。例如

public class Shop : MonoBehaviour
{
private Zoney;

public int Change;
// Start is called before the first frame update
void Start()
{
_HiddenZoney = gameObject.Addcomponent<Zoney>();
}
// Update is called once per frame
void Update()
{
Change += 1;
_HiddenZoney.setMoney(Change);
Debug.Log(Change);
}
}

感谢@derHugo的提醒!

您需要从Zoney类创建一个对象来访问它的非静态成员。试试下面:

public class Shop : MonoBehaviour
{
public int Change;
public Zoney myZoney; // Need to create the object
// Start is called before the first frame update
void Start()
{

}
// Update is called once per frame
void Update()
{
Change += 1;
myZoney.setMonney(Change); // Access members using created object
Debug.Log(Change);
}
}

最新更新