简体   繁体   中英

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

I keep getting this error:

Assets/PlayerScript.cs(220,35): error CS0120: An object reference is required to access non-static member `Generate.seed'

With this code:

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

And i declared in Generate.cs:

 public int seed;

you either use an object reference to an instance of Generate

in Unity you usually either get it via the Inspector using eg

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

or using GetComponent (if the component is attached to the same object)

var GenerateReference = GetComponent<Generate>();

or if it is on anothet object

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

where ofcourse now you would have to get anotherObjectReference first.

than you would use GenerateReference.seed .

See also Controlling GameObjects using components


or alternatively make seed a

public static int seed;

in order to convert it to a non-instanced member, a member of the type Generate itself and go on using Generate.seed . In simple words this way all Generate components kind of share the same seed value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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