- Home /
Instantiate without inheriting from MonoBehaviour
I'm using a state machine. There is a "ClassName : FSMSystem" that is attached to a GameObject. Then I have "StateName : FSMState", but I can't use anything from MonoBehaviour in this state, only in the main FSMSystem class.
using UnityEngine;
using System.Collections;
public class PlayerScript : FSMSystem {
// STATES
public PlayerIdle S_PlayerIdle;
void Awake()
{
AddState(S_PlayerIdle);
S_PlayerIdle.Parent = this;
GoToState(S_PlayerIdle);
}
}
FSMSystem inherits from MonoBehaviour, so it has access to Instantiate. FSMState does not. Here is an example state script:
using UnityEngine;
using System.Collections;
[System.Serializable]
public class PlayerIdle : FSMState {
[System.NonSerialized]
public PlayerScript Parent;
public override void OnEnter()
{
}
public override void OnUpdate()
{
}
public override void OnExit()
{
}
}
I can't make FSMState inherit from MonoBehaviour, so how do I get access to Instantiate/etc?
Why can't you make FS$$anonymous$$State inherits? If there is already another class it inherits from, can you make that one an interface? C# does not support multiple inheritance of class but does with Interfaces, as many as you want.
Actually, making FS$$anonymous$$State inherit from FS$$anonymous$$System, which itself inherits from $$anonymous$$onoBehaviour seems like it might work. I will go check...
Answer by Stardog · Dec 04, 2012 at 12:48 AM
The solution was to use GameObject.Instantiate instead.
GameObject instancedObj = GameObject.Instantiate(..., ..., ...) as GameObject;
Or just `Object.Instantiate`. GameObject works since it's a type of Object. Since your Q specifically mentioned $$anonymous$$onobehavior, you could even use that.
The trick is that Instantiate is a static, so you don't have to be an instance to use it.
I know I'm about 5 years late to this party, but thank you! I was able to inherit from $$anonymous$$onoBehaviour, but I wasn't able to create an instance of my class using "new". This totally solved it for me.
Answer by nventimiglia · Dec 03, 2012 at 08:38 PM
You can create new instances of non monobehaviours by using new.
public class NonMonoClass{}
void Awake(){ var myObject = new NonMonoClass(); }
Your answer
Follow this Question
Related Questions
Abstract Class - Monobehaviour Functions 0 Answers
Can I call a class's method which inherit monobehaviour by a normal class? 0 Answers
Strategy Pattern with Monobehaviours 2 Answers
Finite States Machine (Inheriting question) 0 Answers
Previously functional script now mysteriously does not invoke Start or Update methods 2 Answers