CS0120发生(功能)Unity

时间:2019-01-11 16:34:39

标签: unity3d

public int[,] position = new int[8, 8];

Figure pawn1 = new Figure();
void Start()
{
    pawn1.Create("pawn", 1, new Vector2Int(1, 2));
}

void Update()
{

}

[System.Serializable]
public class Figure
{
    public int id;
    public void Create(string nameEntered, int IdEntered, Vector2Int positionEntered)
    {
        position[positionEntered.x, positionEntered.y] = IdEntered;
        //CS0120 occurs here
    }
}

获取此错误,不知道如何解决 有谁能帮忙吗? 感谢您的任何帮助

1 个答案:

答案 0 :(得分:1)

CS0120的意思是

  

非静态字段,方法或属性“ member”需要对象引用


的引用
public int[,] position = new int[8, 8];

non-staticinstanced,因为它不使用关键字static。这意味着访问它的唯一方法是通过外部类实例的引用。


解决方案取决于您要使用的解决方案:

如果您想要non-static,以使其在外部类的所有实例之间不“共享”,则可以将外部类的实例引用传递给

private void Start()
{
    pawn1.Create("pawn", 1, new Vector2Int(1, 2), this);
}   

图中中,期望值(用外部类的实际名称替换<OuterType>

[System.Serializable]
public class Figure
{
    public int id;
    public void Create(string nameEntered, int IdEntered, Vector2Int positionEntered, <OuterType> reference)
    {
        reference.position[positionEntered.x, positionEntered.y] = IdEntered;
    }
}

否则,您可以将其设置为static,以便它在外部类的所有实例之间“共享”:

public static int[,] position;

提示1
如果仅是您的Create方法,为什么不在外部类本身中设置值?

private void Start()
{
    position[1,2] = 1;
    // Rather pass on the value in this direction if Figure needs it
    pawn1 = new Figure("pawn", position[1,2], /*...*/);
}

非常有必要将position等传递给Figure实例,而不必回写值(除非发生了更多未显示的事件)。

提示2
而不是在

中创建新的Figure
Figure pawn1 = new Figure();

,然后在以后使用其方法Create来设置值,您可能应该使用构造函数,例如:

[System.Serializable]
public class Figure
{
    public int id;
    public Figure(string nameEntered, int IdEntered, Vector2Int positionEntered, <OuterType> reference)
    {
        reference.position[positionEntered.x, positionEntered.y] = IdEntered;
    }
}

并像使用它一样

Figure pawn1;

private void Start()
{
    pawn1 = new Figure("pawn", 1, new Vector2Int(1, 2), this);
}

提示3
StartUpdate的用法让我们得出结论,您很有可能正在使用MonoBehaviour

为避免与transform.position混淆,我建议为您的字段命名更好Positions

提示4
到目前为止,您尚未使用Vector2Int的任何功能,而仅使用它来获取两个int的值。

如果您对positionEntered不做任何其他事情,则无需传递new Vector2Int即可获得两个int值,而只需传递{{1 }}本身就是价值

int

pawn1.Create("pawn", 1, 1, 2, this);

提示5
通常,如果您使用的是public void Create(string nameEntered, int IdEntered, int x, int y, <OuterType> reference) { reference.position[x, y] = IdEntered; } 组件,但没有使用MonoBehaviourStart之一,则应将它们从类中完全删除,因为Unity会在存在时立即调用它们,这会导致不必要的开销