Search Unity

Getters/Setters with C# Arrays

Discussion in 'Scripting' started by stereosound, May 31, 2013.

  1. stereosound

    stereosound

    Joined:
    Sep 13, 2011
    Posts:
    75
    Hi All,

    I have an array of GameObjects that gets swapped a lot based on the current game state. They have a script attached to them (say SomeScript) that contains a lot of unique properties about that particular GameObject. In an effort to decrease my GetComponent calls, as well as create some cleaner code, I'd like the following to happen:

    If I set GameObj[1] = SomeGO; I want GameObjScripts[1] = SomeGO.GetComponent<SomeScript>();

    My current attempt (trying to follow http://msdn.microsoft.com/en-us/library/2549tw02(v=vs.80).aspx which I think is the relevant msdn page):

    Code (csharp):
    1.  
    2. public static class TEST
    3. {
    4.    private GameObject[] mGameObj;
    5.    public  SomeScript[] GameObjScripts;
    6.  
    7.    public static GameObject GameObj(int index)
    8.    {
    9.       get
    10.       {
    11.          return mGameObj[index];
    12.       }
    13.       set
    14.       {
    15.          mGameObj[index] = value;
    16.          GameObjScripts = value.GetComponent<SomeScript>() as SomeScript;
    17.       }
    18.    }
    19. }
    20.  
    However this doesn't work. Does anyone have any experience/recommendations for getting this to compile?
     
  2. SkaredCreations

    SkaredCreations

    Joined:
    Sep 29, 2010
    Posts:
    296
    It cannot be a static property since you need an indexer for it, so here is your class:

    Code (csharp):
    1.  
    2. public class TEST
    3. {
    4.  
    5.    private GameObject[] mGameObj;
    6.    public SomeScript[] GameObjScripts;
    7.  
    8.    public GameObject this [int index]
    9.    {
    10.       get
    11.       {
    12.          return mGameObj[index];
    13.       }
    14.       set
    15.       {
    16.          mGameObj[index] = value;
    17.          GameObjScripts = value.GetComponent<SomeScript>() as SomeScript;
    18.       }
    19.    }
    20. }
    21.  
     
    Last edited: May 31, 2013
  3. stereosound

    stereosound

    Joined:
    Sep 13, 2011
    Posts:
    75
    I saw you changed it to "this [int index]" as well -- how exactly is this getter/setter utilized? What command do I do to trigger the setter?