Can I create a subclass of the GameObject class?

The reason I ask is mainly to educate myself. I currently have a set of 10 prefabs that are instantiated at runtime. I want each of these to have a set of attributes associated with them.

I know that I could attach a script to each prefab that has the attributes on it, but a subclass of GameObject might enable me to create objects in code for each prefab that would inherit the attributes from the subclass of GameObject. I’m very new to c# and Unity, so I’m sorry if this sounds totally absurd. if there is a more “elegant” solution, I’m all ears. Thanks.

1 Answer

1

GameObject is a sealed class so it cannot be derived. However, you are probably looking to derive from MonoBehaviour which is the default inheritance when you make a new c# script in Unity.

You can create your class

using UnityEngine;

public class MyDerivedMonoBehaviour : MonoBehaviour
{
    //Customize it as you want here.
}

After you create that class you can instantiate just like a you would a gameObject prefab with the following modification:

var myDerivedInstance = Instantiate<MyDerivedMonoBehaviour>(prefab);

Good luck!

If my prefabs are not instances of the GameObject class, do they lose some of the attributes of GameObject?

I'm not sure if I'm approaching this problem the right way, but I'll give you credit for giving a correct answer to my original question. Thanks.