class AB {
var a: float = 1.0;
var b: float = 2.0;
}
var ab: AB = AB();
And when I attach that script to some game object, I can modify a and b in the editor.
I’m trying to do the same thing using C#. But if I create a script AB.cs with:
using UnityEngine;
public class AB: ScriptableObject {
public float a = 1.0f;
public float b = 2.0f;
}
Then in another script I can declare an instance variable like this:
public AB ab = ScriptableObject.CreateInstance("AB") as AB;
But when I attach that script to a game object I can’t even see the a and b variables in the Editor.
By the way, I had to put the AB class into a separate source to even get this far, because if I try to declare the AB class in the same source file where I create the instance variable, then Unity can’t even find AB!
How should I write my C# code to get the same result I get with Javascript?
You have to mark the AB class as Serializable (it need not extend ScriptableObject). See the documentation for Serializable. To have the class in the same file, you need to either declare it outside the class declaration for the class whose name appears in the file or declare the class internal.
For an example of the former:
using UnityEngine;
[System.Serializable]
internal class AB
{
public float a = 1;
public float b = 2;
}
public class InternalClassTest : MonoBehaviour
{
public AB ab;
}
For an example of the latter:
using UnityEngine;
public class InternalClassTest : MonoBehaviour
{
[System.Serializable]
internal class AB
{
public float a = 1;
public float b = 2;
}
[SerializeField] //Must be done to show in the inspector, see the docs for "SerializeField" for more info.
internal AB ab;
}
Keep in mind that with the latter approach, other classes won’t be able to access AB objects (because it’s only visible to the class that contains it.