Home > database >  How to implemet Start()-like functionallity in a non-Monobehaviour class?
How to implemet Start()-like functionallity in a non-Monobehaviour class?

Time:06-24

Here we have two classes, A and B.

A class is Monobehaviour, and B class is non-Monobehaviour.

Both classes have a method called Initialize().

Class A can be called from Start(), but class B must be called after externally create an instance of B.

What I want here is 'How to implement a function like Start() inside B'.

Because sometimes I forget to call Initialize() from externally.


The Initialize() method does the following:

public class Popup : IObjectPooling
{
  private IObjectPooling popup;

  public void Initialize()
  {
    popup = new Popup();
  }
}

Solved

Foolish, I realized late that there is no magic.

We separated the new Popup() part, which is the problematic part in the Initialize() method.

public class Popup : IObjectPooling
{
  private IObjectPooling popup;

  public Popup() {}

  public Popup(Popup popup)
  {
    this.popup = popup;
    Initialize();
  }

  public void Initialize()
  {
    //...
  }
}
[SerializeField] private Popup popup = new(new Popup());

CodePudding user response:

Unity Messages

Unity's Start method (and all Message methods) makes use of Component.SendMessage internally to know when those specific message methods need to be called. It then uses Reflection to find the appropriate method (if declared) and invoke it. This creates a significant amount of overhead and work compared to a single call to Initialize. You can implement this type of system if you believe it is the appropriate direction, or simply for learning purposes.

Alternative Solutions

If you can change the signature of the Initialize method, you can add a boolean to indicate if the inner Popup object should be created.

public class Popup : IObjectPooling
{
    private IObjectPooling popup;

    public Popup()
    {
        Initialize();
    }
    public Popup(bool initialize)
    {
        if (initialize)
        {
            Initialize();
        }
    }

    public void Initialize(bool initialize = true)
    {
        if (initialize)
        {
            popup = new Popup(false);
        }
    }
}

If this is not possible due to the interface or external factors, you could create a method that creates the instance and initializes it.

public static Popup CreateInstance()
{
    var popup = new Popup();

    popup.Initialize();

    return popup;
}
  • Related