2
\$\begingroup\$

I have a custom editor wich has a static field.

Suppose you have a static field of type MyObject:

public class myEditor : Editor {

...

private static MyObject myObj;

...
}

I'd like to initialize the field myObj directly on the same line of the declaration, but in this way I get a TypeInitializationException.

I could initialize the field myObj in the method OnEnable, but in this way I have to use an if statement like the following:

if ( myObj == null )
    myObj = new MyObject();

Is there a way to initialize myObj once for all without using if statement?

\$\endgroup\$
  • \$\begingroup\$ Is this the code that you are using? I ask because it looks like field shouldn't be there and would cause a compilation error. \$\endgroup\$ – Kelly Thomas Dec 9 '14 at 12:29
  • \$\begingroup\$ Of course no, sorry now I edit :) \$\endgroup\$ – optimusfrenk Dec 9 '14 at 13:08
  • \$\begingroup\$ Have you examined the TypeInitializationException.InnerException property? \$\endgroup\$ – Kelly Thomas Dec 9 '14 at 15:03
0
\$\begingroup\$

You could use a static constuctor

Static myEditor(){
    myObj = new MyObject();
}

This will run the first time you access the class

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.