instantiated gameobjcet as a conventional class

Good morning,
I’m implementing the state design pattern in my game, and wanted each state was responsible for the manufacture of gameObject itself.

However, as we needed to be monobehaviour class, can not instantiate with the new keyword, as if a normal class.

Do you have any sugestção?

I appreciate any help

Adriano

You have basically two options:

  • Use normal classes which aren’t derived from MonoBehaviour. Keep in mind that you don’t have methods available which belong to UnityEngine.Object or MonoBehaviour. So when you want to use Destroy you have to use UnityEngine.Object.Destroy. Also StartCoroutine is a instance method of MonoBehaviour. So to start a Coroutine from your class you have to pass in a reference to a MonoBehaviour which could run the coroutine.
  • If you want / need to use a MonoBehaviour you can provide a static “Create” method like this:

An example

// C#
public class MyState : MonoBehaviour, IMyStateInterface
{
    public static MyState Create()
    {
        return (new GameObject("MyState")).AddComponent<MyState>();
    }
    // Your state implementation
}