Static fields in a class don't seem to be destroyed after play mode?

Hi, so I’m playing around with Unity’s FPS Sample console utility and when I play the game twice after a script reload, the console outputs “Cannot add command … twice” a couple of times.

After logging the count of the “s_Commands” dictionary, the first time after a script compilation its 0, then when I play the game a second time its’s 3, so I’m guessing for some reason it doesn’t get reset after play mode.

My amateur guess is because the Console class never actually get’s instantiated with the “new” keyword and it’s only used to access its static methods so the garbage collector doesn’t clean it up after play mode?
I also tried to make it a static class but it seemed not to do anything.

I could easily fix this by just reinitializing the dictionary at the start but I want to understand why this behavior occurs.

Thanks.

static fields would absolutely never be changed unless you change them.

If you want a static field changed, you must change it.

Personally I like the pattern of:

  • initializing my statics at the start of a game or session or whatever they lifetime-mimic
  • setting all my statics to null at exit time.

Setting them null keeps you out of trouble because you’ll get errors if you access them when they could be invalid.

1 Like

Right. Static fields are never destroyed until / unless the whole CLR is shut down. Though this only happens at certain events. For example when Unity recompiles code. Though when this happens Unity serializes a lot of things which normally are not serialized and restore them after the domain reload. This is for hot-reloading.

1 Like

You are likely supposed to make use of that Shutdown method, but I’m having a hard time understanding how is this supposed to be used without installing the whole thing for myself.

For example, line 503 in Game.cs is calling Console.Shutdown() in OnDestroy.

That said, this is probably a working example, perhaps not fully implemented, and not something that should absolutely work, bug free.

2 Likes

Thanks for the replies I understand now.

Yes, I am already doing that but the Shutdown method doesn’t reset the static fields so that’s what I should probably add now.

2 Likes