【问题标题】:How to fix 'An object reference is required to acces non-static member'如何修复“访问非静态成员需要对象引用”
【发布时间】:2019-04-05 18:43:38
【问题描述】:

我不断收到此错误:

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

使用此代码:

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

我在 Generate.cs 中声明:

 public int seed;

【问题讨论】:

  • someGenerateObject.seed;或使seed static iff 这样是合适的。请search for errors messages next time
  • 好吧,您要么使用对象引用 ... 到 Generate 的实例,要么将 seed 设为 public static int seed
  • “seed”不是“Generate”类的静态成员。您尝试像使用静态成员一样使用它。要么使其成为静态成员,要么停止使用它。您需要了解实例和静态事物之间的区别。

标签: c# unity3d


【解决方案1】:

您要么使用对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

另见Controlling GameObjects using components


或者将seed设为一个

public static int seed;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多