繁体   English   中英

如何修复“访问非静态成员需要对象引用”

[英]How to fix 'An object reference is required to acces non-static member'

我不断收到此错误:

Assets/PlayerScript.cs(220,35):错误 CS0120:访问非静态成员“Generate.seed”需要对象引用

使用此代码:

using (StreamWriter sw = new StreamWriter("file.txt"))
{
    sw.WriteLine(Generate.seed);
}

我在 Generate.cs 中声明:

 public int seed;

您要么使用对Generate实例的对象引用

在 Unity 中,您通常可以通过 Inspector 使用例如

// in the Inspector reference the according component via
// drag&drop the object to this field
public Generate GenerateReference;

或使用GetComponent (如果组件附加到同一个对象)

var GenerateReference = GetComponent<Generate>();

或者如果它在另一个对象上

var GenerateReference = anotherObjectReference.GetComponent<Generate>();

当然,现在您必须首先获得anotherObjectReference

比你会使用GenerateReference.seed

另请参阅使用组件控制游戏对象


或者让seed成为

public static int seed;

为了将其转换为非实例化成员,类型为Generate本身的成员并继续使用Generate.seed 简而言之,所有Generate组件都以这种方式share相同的seed值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM