- Home /
How to make classes in C# that are assignable to public variables in scripts trough the Editor
Hello I am trying to make a modular finite state machine/flocking system where each state is a class that should be able to be assigned to an array of states in the MonoBehaviour that is responsible for executing the states. I have read in the Scripting Reference that if a class inherits from Unity's Object it should be able to be assignable in the editor so I went ahead and did this. Basically I have two classes, one that states inherits from called BaseState and one that can contain states(right now this is called Sheep):
public class BaseState : Object {
}
public class Sheep : MonoBehaviour {
public BaseState[] states; //states should be allowed to be dragged to this place
}
To assign the Sheep class as a component to a GameObject works fine but I am not allowed to assign the BaseState class to any elements in the states array. What is weird is that Unity can see that BaseState is inherited from Object so the array is shown in the Inspector. Another thing is that it works if I change the type of the states array to Object. So my question is, How should a class be declared in order for Unity to let it be assigned to variables in the Inspector?
Any help would be much appreciated
Answer by yoyo · Feb 03, 2011 at 09:48 PM
Note that you don't assign the BaseState class to elements of the array, you would assign instances of the BaseState class. Normally you get instances of objects from the assets in the Project view or from objects or components in the Hierarchy view. In your case, you don't have any instances of BaseState or a way to create them.
Couple options ...
You could derive from MonoBehaviour, not from Object. Then you can create an object and assign the component to it, then drag the object onto an element in your states array. In this case, the states array is an array of references to (MonoBehaviour component) objects.
Or you could make BaseState a [System.Serializable] class (it doesn't need a base class), give it whatever fields you like, and create an array of BaseStates, as you've done. In this case your Sheep object will own the array and it's properties -- the array will contain the data itself, not references to objects containing the data.
Hope that helps.
Thank you, I feel quite stupid for not having spotted that myself :-) I will go with your first option since that would also allow me to have a set of steering behaviour prefabs for each type of entity. These could then use the same steering behaviour scripts as all the other sets of prefabs use.
Don't feel stupid, it takes a while to wrap your head around everything. This thread might be be helpful ... http://answers.unity3d.com/questions/36132/whats-the-difference-between-the-component-and-gameobject-classes-and-how-they-ar
Your answer
![](https://koobas.hobune.stream/wayback/20220613102708im_/https://answers.unity.com/themes/thub/images/avi.jpg)