Add a System.Object field to UnityEngine.GameObject to allow tagging with arbitrary data

Would be possible for the developers to add a System.Object field to UnityEngine.GameObject or UnityEngine.Object, so you could link them with arbitrary data?

Currently for example, I’m using a custom class for game entities (sort of an abstraction with extra code and MonoBehaviour-related things hidden underneath to make modding more controllable).

However, when I need to retrieve a physics-supported entity via custom OverlapPoint() implementation, I have to check do this:

public NetEntity OverlapPoint(Vector2 inPosition, Mask inMask)
{
    Collider2D collider = this.physicsScene.OverlapPoint(inPosition, (int)inMask);
    if (collider != null)
    {
        var script = collider.GetComponent<BaseEntityObject>()?.script;
        if (script != null)
        {
            if (script is NetEntity netEntity) return netEntity;
            else if (script is ENT_Grid.GridBoundingBox boundingBox) return boundingBox.grid;
            else return null;
        }
        else return null;
    }
    else return null;
}

Which, however, isn’t an exactly elegant solution. With being able to “tag” the GameObjects with a System.Object, I could just initialize the script and set the gameObject.Data to the script internally, which I could then access like this, skipping the unnecessary GetComponent() call.

public NetEntity OverlapPoint(Vector2 inPosition, Mask inMask)
{
    Collider2D collider = this.physicsScene.OverlapPoint(inPosition, (int)inMask);
    if (collider != null)
    {
        var script = collider.gameObject.Data;

        if (script is NetEntity netEntity) return netEntity;
        else if (script is ENT_Grid.GridBoundingBox boundingBox) return boundingBox.grid;
        else return null;
    }
    else return null;
}

We will not be adding any additional fields to UnityEngine.GameObject nor UnityEngine.Object at this point in time.

I think you are taking the right approach with looking up the data with GetComponent.

2 Likes