Use class nested Unity class as true script

typically in order to have a script execute relative to a GameObject, you attach an individual file to a GameObject, and it just works.

Imagine I have something like this:

namespace Something {

    class X1 {
        class X2 {
            class Human : MonoBehaviour {
                // Some functions
            }
        } 
    }

}

I would like to attach Human as if they were separate file. I would like to attach this class to a GameObject, it to be serialized and edit its unique variables in Inspector. Is there a way to do it?

Not sure, give it a try. It wouldn’t take more than 60 seconds of typing!

The classes have to be public, and if you want to attach it to a gameobject the only restrictions I know are:

  1. at least ONE of the files that contain the class must be named the same

  2. it must derive from Monobehavior.

Good luck, let us know what you find.

Well the issue is exactly that I didn’t manage to get it working. Hoped someone else already got it figured out.

All three of the above classes are NOT public. Did you try that?

I did make them public, but I think the main issue is the namespace. I did create a new script, opened up reference directly pointing to demo, then reloaded, the slot showed up on test object. I dragged GameObject containing the namespace but it won’t grab it. Neither asset nor scene browser detects this public MonoBehaviour, and even manual grab of new Test.X1.X2.X3() worked.

No errors.
And yes and I included the namespace.

There could be a solution, but it’s a different question. BRB.

This is not supported.

I think even multiple MonoBehaviours in the same file is not supported.
Because name of the class must be the same as name of the file.

Why do you need this class spaghetti?

1 Like