Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

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

Discussion in '2019.2 Beta' started by TFlippy, Mar 31, 2019.

  1. TFlippy

    TFlippy

    Joined:
    Nov 12, 2014
    Posts:
    27
    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:

    Code (CSharp):
    1. public NetEntity OverlapPoint(Vector2 inPosition, Mask inMask)
    2. {
    3.     Collider2D collider = this.physicsScene.OverlapPoint(inPosition, (int)inMask);
    4.     if (collider != null)
    5.     {
    6.         var script = collider.GetComponent<BaseEntityObject>()?.script;
    7.         if (script != null)
    8.         {
    9.             if (script is NetEntity netEntity) return netEntity;
    10.             else if (script is ENT_Grid.GridBoundingBox boundingBox) return boundingBox.grid;
    11.             else return null;
    12.         }
    13.         else return null;
    14.     }
    15.     else return null;
    16. }
    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<BaseEntityObject>() call.

    Code (CSharp):
    1. public NetEntity OverlapPoint(Vector2 inPosition, Mask inMask)
    2. {
    3.     Collider2D collider = this.physicsScene.OverlapPoint(inPosition, (int)inMask);
    4.     if (collider != null)
    5.     {
    6.         var script = collider.gameObject.Data;
    7.  
    8.         if (script is NetEntity netEntity) return netEntity;
    9.         else if (script is ENT_Grid.GridBoundingBox boundingBox) return boundingBox.grid;
    10.         else return null;
    11.     }
    12.     else return null;
    13. }
     
  2. lukaszunity

    lukaszunity

    Administrator

    Joined:
    Jun 11, 2014
    Posts:
    461
    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.
     
    Peter77 and karl_jones like this.