Constructor called multiple times on Class

I have 2 classes. Class Alpha and Class Beta. Alpha is supposed to instantiate an instance of Beta, lets call that betaPieces. However, after a few frames, betaPieces is deleted out of nowhere and Alpha.betaPieces is equal to NULL What i discovered while debugging:

  • Constructor is called about 3 times.
  • Deconstructor is also called about 2 times. Some times in an unexpected order like Costructor, Constructor, Deconstructor, Constructor, Deconstructor
  • Triple checked if there are times when betaPieces is assigned, however it’s never assigned anywhere else.

Below is a pretty stripped down version of the classes.

public class Beta<IT,ID> where ID : IEquatable<ID>
{

  private int windowSize;

  public Beta (int windowSize = 3)
  {
    this.windowSize = windowSize;
    //Called 3 times? Why?
    Debug.Log("Constructor Called");
  }

}

public class Alpha : MonoBehaviour
{

  public Beta<GameObject, int> betaPieces;

  void Start(){
    betaPieces = new Beta<GameObject, int> ();
  }

  void Update(){
    //Null Exception After being called a few times
    Debug.Log(betaPieces.windowSize);
  }
}

How do i stop Alpha.betaPieces from disappearing?

It’s hard to see exactly what you’re doing here with the class pared down. Normally for this to happen, you would have had to do something in the Alpha constructor, or write [Serializable] above the Alpha Class, or be in a situation where a class who owns the Alpha class is being serialized. The behavior you’re describing is a perfect match for a situation where Alpha is being serialized by Unity, and thus, as a result, it’s refusing to let it’s Beta variable be null. You mentioned you had destructors, and the destructors themselves could be getting called all will-nilly thanks to the deserialization. They very well might be your culprit.

Do not use constructors and destructors on or around Monobehaviors or [Serializable] classes unless you are prepared for them to get called over and over again. Monobehaviors/gameObjects are serialized by Unity, and Unity recreates and destroys objects all over the place every time it needs to serialize or deserialize something. Which is: Every time you save scripts for your project, every time you load your project, twice every time you play your project, every time you stop playing your project, and so on and so forth.

http://ilkinulas.github.io/development/unity/2016/05/30/monobehaviour-constructor.html

Hope tha thelps.