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

Question How to make a static read-only array?

Discussion in 'Scripting' started by OutDoorsScene, Jul 14, 2023.

  1. OutDoorsScene

    OutDoorsScene

    Joined:
    Sep 9, 2022
    Posts:
    140
    I can't add
    const
    to an array and
    readonly
    is not preventing the array from being edited.
    Code (CSharp):
    1.  
    2.  public const string OceanMenu = "OceanMenu";
    3.  public const string IslandMenu = "IslandMenu";
    4. public static readonly string[]  MenuScenes = new string[] {OceanMenu, IslandMenu,};
    5.  
    Code (CSharp):
    1.  
    2.         DefaultSceneNames.MenuScenes[1] = "override";
    3.  
    4.         for (int i = 0; i < 20; i++)
    5.         {
    6.             int randomIndex = Random.Range(0, DefaultSceneNames.MenuScenes.Length);
    7.  
    8.             Debug.Log(DefaultSceneNames.MenuScenes[randomIndex]);
    9.         }
     
  2. KillDashNine

    KillDashNine

    Joined:
    Apr 19, 2020
    Posts:
    449
    The readonly modifier obviously only affects the variable, not the array object behind the variable. I personally don't bother when coding games cos of the general tongue-in-the-cheekness, but you can use
    ReadOnlyCollection<T>
    class if you need this.
     
  3. SisusCo

    SisusCo

    Joined:
    Jan 29, 2019
    Posts:
    1,104
    Alternatively you can cast the array to
    IReadOnlyList<string>
    .
    Code (CSharp):
    1. public static readonly IReadOnlyList<string> MenuScenes = new string[] {OceanMenu, IslandMenu,};
     
    Bunny83 likes this.
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    It's the kind of thing you can obfuscate behind an enumerator:

    Code (CSharp):
    1. public const string OceanMenu = "OceanMenu";
    2. public const string IslandMenu = "IslandMenu";
    3.  
    4. private static string[] menuScenes = new string[] { OceanMenu, IslandMenu };
    5.  
    6. public static IEnumerable<string> EnumerateMenuScenes()
    7. {
    8.     int sceneCount = menuScenes.Length;
    9.     int (i = 0; i < sceneCount; i++)
    10.     {
    11.         yield return menuScenes[i];
    12.     }
    13. }
     
    Kurt-Dekker and Bunny83 like this.
  5. OutDoorsScene

    OutDoorsScene

    Joined:
    Sep 9, 2022
    Posts:
    140
    Your IReadOnlyList works, but I forgot that simply making the array private can prevent it from being edited by other classes.

    Code (CSharp):
    1.  private static string[] MenuScenes = new string[] {OceanMenu, IslandMenu};
    2.  
    3.     public static string GetRandomMenuScene()
    4.     {
    5.         return MenuScenes[Random.Range(0, MenuScenes.Length)];
    6.     }
     
    SisusCo likes this.