Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

HowTo: Add method to the GameObject class? IE: add custom variables to every instance

Discussion in 'Scripting' started by by0log1c, May 18, 2011.

  1. by0log1c

    by0log1c

    Joined:
    Jan 30, 2011
    Posts:
    40
    Hey guys,

    well I'll try to use the right words but give me some slack here ;)

    So I'd like to add methods to the GameObject class. For example, let's say I would like each and every instance of GameObject to hold a variable named "creationTime: DateTime" which I'd fill accordingly.

    I'm confused with the implements/inherits/override/super stuff so any help is greatly appreciated. :p
     
  2. KyleStaves

    KyleStaves

    Joined:
    Nov 4, 2009
    Posts:
    821
    To be honest, I'm not sure you can inherit from GameObject.

    Your best bet might be to create a simple component that you can add to every GameObject manually. Something like...

    Code (csharp):
    1.  
    2. public class MyMetadata : MonoBehavior {
    3.      float _creationTimestamp;
    4.      public float CreationTimestamp { get { return _creationTimestamp; }}
    5.  
    6.     void Awake () {
    7.         _creationTimestamp = Time.time;
    8.     }
    9. }
    10.  
    Then you would access that information like...

    Code (csharp):
    1.  
    2. // I would check to see if this is null before you access it or you'll error out on any gameobject missing the script
    3. gameObject.GetComponent<MyMetadata>().CreationTimestamp;
    4.  
    If you had to access it often it's probably worth caching, but GetComponent isn't nearly as slow as .Find - so it's not mandatory (or even worth it in a lot of cases).

    EDIT:

    If you want to get really fancy, you might even be able to use a C# extension method to add a more convenient way to get the information...

    Code (csharp):
    1.  
    2. public static class UnityExtensions
    3. {
    4.     public static float CreationTime(this GameObject go){
    5.         MyMetadata dataScript = go.GetComponent<MyMetadata>();
    6.         if (dataScript == null){
    7.             dataScript = go.AddComponent<MyMetadata>();
    8.         }
    9.        
    10.         return dataScript.CreationTimestamp;
    11.     }
    12. }
    13.  
    NOTE: I have absolutely never tried to use C# extension methods with Unity, I have no idea if they are supported. If it does work though, it would be pretty awesome - you could easily add the script simply by running GameObject.CreationTime() - accessing it would add it if missing (and set the creation time to the current time).
     
    Last edited: May 18, 2011
  3. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
    You can't derive from Unity's classes; they're sealed. But even if you could, that wouldn't mean that Unity would use your class instead of its own. This isn't the way to do what you want to do, but I'm not actually sure what the best way is; my guess would be an XML document that you read/write. You could write extension methods for GameObject that would do it.
     
    Last edited: May 18, 2011
  4. by0log1c

    by0log1c

    Joined:
    Jan 30, 2011
    Posts:
    40
    Thanks alot for the fast answers. Always appreciated to see how friendly the community is! As for the issue at hand:

    I thought about adding a custom component or saving the info to a XML but I'd need the variables to be 'internal' to the GameObject.

    The real goal I'm trying to achieve is for each and every GameObject(ever) to own a unique id I could use to see if the users moved, deleted stuff around in the scene. That would also allow me to easily save a reference to any GameObject (through my custom methods).

    Maybe I'm overcomplicating stuff. Again, any opinions is appreciated :D

    EDIT:
    I just want to be able to find the right GameObject named "Player" with tag "Player" in a group. Even after - for example - the level designer go in and make a mess out of my scene.
     
    Last edited: May 18, 2011
  5. KyleStaves

    KyleStaves

    Joined:
    Nov 4, 2009
    Posts:
    821
    It sounds to me like you need two classes.

    1) The metadata class that stores the unique ID on the game object

    2) An ExecuteInEditor class that iterates through your scene, checks to see if the object has a unique ID already - if it does not, add the new metadata script to the object and assign a unique ID to the script.

    Then you would just save the reference to the unique ID any way you want.

    It can't be internal to GameObject though, it has to be a component. Or you can handle it all with a single class and a custom made serializable dictionary, but the component approach is probably easier/more reliable.
     
  6. Quietus2

    Quietus2

    Joined:
    Mar 28, 2008
    Posts:
    2,058
  7. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,400
  8. by0log1c

    by0log1c

    Joined:
    Jan 30, 2011
    Posts:
    40
    Thanks again for the answers.
    I've went for KyleStaves solution and a script is constantly managing the whole identification process while in EditMode.

    I didn't even bother to try the GetInstanceID recently as I think I remember noticing the ID wasn't persistent through play,stop and even quit. I really should have, and still should but I'm too lazy, thanks though :)

    Now I've faced the my-data-aren't-persistent problem (again) but managed to figured the first half, I'll open a new thread for those kindly bored enough. :D
     
  9. Kironde-Namusanga

    Kironde-Namusanga

    Joined:
    Dec 11, 2014
    Posts:
    12
    public static class MonobehaviourExtensions
    {
    public static void Extension(this GameObject mb)
    {

    }

    }
     
  10. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,194
    When you're trying to give help to an 8 year old post, where the question asker was here last 4 years ago, please use code tags, explain your post properly, and don't repeat advice already given in the thread.
     
  11. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,745
    No way. In unity there's different desing principle used. You want to add method to game object to extend it functionality. In unity, the basic functional unit is not a class method, it is component. When you modelling your game, you create classes of objects in your game via creating prefabs and your extended those class via adding components onto those prefabs.