Rabadash8820 Rabadash8820 - 27 days ago 18
C# Question

Using Nested Class as Unity3D Component

I am using Unity 5.4.2f2 Personal, and I have written a C# script similar to the following:

using UnityEngine;
using System;

public class Outer : MonoBehaviour {

// Some public outer fields

public class Inner : MonoBehaviour {
// Some public inner fields
}

}


I would like to be able to attach both
Outer
and
Inner
to GameObjects in my scene. Unfortunately,
Inner
does not show up as an available script in the Unity Inspector, even if I add
[Serializable]
to it. I know a lot of people will probably say there's something wrong with my setup if I'm trying to make a nested class visible to the outside world, but for the sake of this question, I just want to know if this can be done. I.e., is there any way to make nested classes usable as Unity components?

Answer

No there's no way to use a nested class as a unity component. To use your MonoBehaviour class as a unity component the class name must be equal to the file name of your script, so use nested class would't be possible.

If you rename your outer class to whatever other name you want without renaming the script file you will see that it will not be possible to use the new outer class too.

[EDIT]

I found the documentation. And as I said: "The class name and file name must be the same to enable the script component to be attached to a GameObject."