- Home /
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.
Answer by dadamsj1 · Jan 26 at 11:00 PM
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?
They are still GameObjects in this case because they are derived from MonoBehaviour. It will be like a normal GameObject but with your script attached from the onset.
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.
If you want to be more specific about the issue you are facing, I'd be happy to help.
Basically, I'm creating a puzzle game and I'm not sure of the best way to compare the properties of the puzzle pieces with the others in order to deter$$anonymous$$e the outcome when they combine. I've been working on my own to figure it out, but I should probably follow a puzzle game tutorial and learn how "the pros" do it before tackling it on my own.