C# MonoBehaviour In Inspector

Ok so in Javascript when you expose a class that extends Monobehaviour in a script the class’s variables are also exposed if they’re public so you can just edit them in the Inspector. But in C# if a class extending Monobehaviour is exposed in another Monobehaviour script then in the Inspector all you see is something like None (type) and you can’t edit them in the inspector like you can with a JS script. How can I make the Monobehaviours get initialized by default like in the JS versions?

Can you give a code example?

Do you mean something like this?

using UnityEngine;
using System.Collections;

public class MoveTest : MonoBehaviour {
	
	public int currentHp;
	
	// Use this for initialization
	void Update ()
	{
	}
}

Then an extended class

using UnityEngine;
using System.Collections;

public class MoveTestExtend : MoveTest {
	
	public int somthing = 0;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

This works for me. All the public variables are exposed to the inspector.

No, I mean something like this

using UnityEngine;

public class Storage : MonoBehaviour
{
    public int store1;
    public int store2;
}

public class Example : MonoBehaviour
{
    public Storage myStorage;
}

The equivalent code in JS would give me a Foldout for the myStorage variable where I could set the store1 and store2 fields in the Inspector, but this code in C# would just get me something like None (Storage).

Hey,

Do you need Storage to extend form MonoBehaviour I.E. are you putting the Storage script onto a gameobject?

If not you can use [System.Serializable] or you can do using System [Serializable].

using System;
[Serializable]
public class Storage
{
    public int store1;
    public int store2;
}
using UnityEngine;

public class Example : MonoBehaviour
{
    public Storage myStorage;
}
1 Like

It’s giving you the None (Storage) because the myStorage variable hasn’t been assigned. If you just want storage to hold data, you can create a custom class:

using UnityEngine;

public class Example : MonoBehaviour 
{
    public Storage myStorage;
}
[System.Serializable] // Serializes the class so it is shown in inspector.
public class Storage 
{
    public int store1;
    public int store2;
}

There’s no need for it to be a MonoBehaviour unless the storage class itself is attached to a GameObject.

2 Likes

Thanks a lot guys it seems to be working now once I used System.Serializable!