Search Unity

How to name elements of an array?

Discussion in 'Scripting' started by Rob21894, May 28, 2017.

  1. Rob21894

    Rob21894

    Joined:
    Nov 21, 2013
    Posts:
    309
    How would i go about naming elements of an array? I know it would require using the custom editor.

    Just the unity tutorial on this is terrible and doesn't really explain anything useful and other questions don't have any explaination

    Any help would be great
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,537
    What do you mean name?

    Like is it an array of GameObjects, and you want to set the name of each element?

    Or do you mean you want the editor to display a title for each element in the array?

    Something else all together?

    Be specific.
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    You normally don't name them. The contents of an array are identified by index.

    Are you looking for a dictionary instead?
     
  4. RodrigoSeVeN

    RodrigoSeVeN

    Joined:
    Jul 10, 2010
    Posts:
    15
    Simple answer:

    Make an array of a struct and include a string parameter named "title" like so:

    Code (CSharp):
    1. public MyStruct[] structArray;
    2. [System.Serializable]
    3. public struct MyStruct {
    4.     public string title;
    5.     public int number;
    6. }
    The second parameter being the actual value type you want to save in your original array.
     
    Yousef_Hadhrami likes this.
  5. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,196
    That should work... If I put that on a class of mine, I get this in the inspector:

    upload_2018-5-16_19-28-54.png

    Is that not working for you?
     
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Call it Name and Unity does inspector magic for you.
     
  7. douglasg14b

    douglasg14b

    Joined:
    Oct 2, 2014
    Posts:
    34
    Yes, but how can this be done without having to dirty up your models unnecessarily?
     
  8. RodrigoSeVeN

    RodrigoSeVeN

    Joined:
    Jul 10, 2010
    Posts:
    15
    It was already answered, the best approach is using dictionaries.
    Names would be the key and your values would be, well, the value.

    The answer using a struct array is only if you really need to see the array on inspector, otherwise there's no need for it.
     
  9. Fitbie

    Fitbie

    Joined:
    Aug 17, 2021
    Posts:
    66
    Put something like this in the top of your class/struct
    Code (CSharp):
    1. #if UNITY_EDITOR
    2. [SerializeField] private string title;
    3. #endif