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\$
3
  • \$\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\$ Commented Dec 9, 2014 at 12:29
  • \$\begingroup\$ Of course no, sorry now I edit :) \$\endgroup\$ Commented Dec 9, 2014 at 13:08
  • \$\begingroup\$ Have you examined the TypeInitializationException.InnerException property? \$\endgroup\$ Commented Dec 9, 2014 at 15:03

1 Answer 1

0
\$\begingroup\$

You could use a static constuctor

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

This will run the first time you access the class

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .