Search Unity

Possible to add properties in an extension class?

Discussion in 'Scripting' started by RedHotFlashman, Feb 21, 2020.

  1. RedHotFlashman

    RedHotFlashman

    Joined:
    Mar 16, 2018
    Posts:
    35
    Is it possible to add properties or Getter&Setter to an extension?

    // Extension
    public static class GameObjectExtension
    {
    public static float x( this GameObject go ) => go.transform.position.x;
    public static void SetX( this GameObject go, float n ) =>
    go.transform.position = new Vector3( n, go.transform.position.y, go.transform.position.z );
    }

    // usage:
    float posX = objectA.x();
    objectB.SetX( posX );

    // PREFERED USAGE:
    float posX = objectA.x;
    objectB.x = posX;
     
  2. adi7b9

    adi7b9

    Joined:
    Feb 22, 2015
    Posts:
    181
  3. RedHotFlashman

    RedHotFlashman

    Joined:
    Mar 16, 2018
    Posts:
    35
  4. adi7b9

    adi7b9

    Joined:
    Feb 22, 2015
    Posts:
    181
    I cannot test right now. Can you see if this works?
    Code (CSharp):
    1. public static float posX { get; set; }
    or
    Code (CSharp):
    1. private static float mPosX;
    2.  
    3. public static float PosX
    4. {
    5.   get
    6.   {
    7.     return mPosX;
    8.   }
    9.   set
    10.   {
    11.     mPosX = value;
    12.   }
    13. }
     
    Last edited: Feb 21, 2020
  5. RedHotFlashman

    RedHotFlashman

    Joined:
    Mar 16, 2018
    Posts:
    35
    Dude... òO
     
  6. adi7b9

    adi7b9

    Joined:
    Feb 22, 2015
    Posts:
    181
    Code (CSharp):
    1. public static void SetX(this Transform trans)
    2. {
    3.   trans.position = new Vector3( posX, trans.position.y, trans.position.z );
    4. }
    If you cannot pass var through methods.