Is there any way to declare a variable on a built in unity class? Specifically, I’d like to declare an additional enum that I can change in the inspector on a collider object.
Can this be accomplished? I have tried to use extension methods but to little avail…
1 Like
Nope it’s not possible to extend Collider. Most of it is implemented on the native C++ side.
You can freely attach as many other custom components you want to the same GameObject though.
1 Like
You can’t add fields/variables to an existing class that you don’t control the source to.
You’d have to inherit from it and then use instances of that. You’d have to add an instance of that class instead, but that would do it.
BUT unfortunately Unity generally has their classes set to not be inheritable (either sealing them, requiring a special attribute, or flat out just throwing errors if you try). Colliders being one of these classes.
Instead what you can do is just composite a 2nd script of your own making that has the variable in question. Then you get that component and access it that way. Mind you… having to know this 2nd type is necessary even if you inherited as well since the compiler wouldn’t know the object had this field/variable unless it was cast as your custom class. The compositing technique is getting similar functionality just without inheriting.
You could then create extension methods that made it easy to do so:
public enum MyColliderVariable
{
A, B, C
}
public class ExtraColliderVariables : MonoBehaviour
{
public MyColliderVariable CustomColliderVariable;
}
public static class ExtraColliderVariablesExtensions
{
public static MyCustomEnum GetCustomColliderVariable(this Collider c)
{
var vars = c.GetComponent<ExtraColliderVariables>();
return vars != null ? vars.CustomColliderVariable : MyColliderVaraible.A; //A being the default
}
public static void SetCustomColliderVariable(this Collider c, MyColliderVariable value)
{
var vars = c.GetComponent<ExtraColliderVariables>();
if (vars == null) vars = c.AddComponent<ExtraColliderVariables>();
vars.CustomColliderVariable = value;
}
}
used:
BoxCollider box = *some box gotten somehow*;
var e = box.GetCustomColliderVariable();
switch(e)
{
//do stuff
}
2 Likes
Thanks for the responses guys. I just went with attaching my own component to the game objects with colliders.
I didn’t want this solution as I wanted it to default to an enum value if I ever forgot to attach the component, and the new type is used pretty universally.
I ended up just writing into my scripts that used the desired default behaviour if a detected collider didn’t have the attached script.