- Home /
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
Answer by Bunny83 · Feb 10, 2014 at 11:46 AM
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
}
thank, Bunny
I implemented the code, however, appears an empty GameObject in the Unity editor. I've tried associating a prefab, but it did not work. Can you help me in this question.
Your answer
![](https://koobas.hobune.stream/wayback/20220613133057im_/https://answers.unity.com/themes/thub/images/avi.jpg)