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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Initalizing Arrays with Variable Length

Discussion in 'Scripting' started by CobaltTheFox, Feb 10, 2019.

  1. CobaltTheFox

    CobaltTheFox

    Joined:
    May 29, 2015
    Posts:
    27
    I would like to create an array whose length can be changed per a variable. It will not let me initialize the array using the variable's length.

    This is somewhat of an demonstration of what I would like:
    Code (CSharp):
    1. public int max_slots;
    2. public int[][,] inventory = new int[max_slots][,];
    It says that I can't use a non-static variable in this way. Is there some way around this?
     
  2. drcrck

    drcrck

    Joined:
    May 23, 2017
    Posts:
    328
    make it static?
    Code (csharp):
    1.  
    2. static public int max_slots = 10;
    3. public int[][,] inventory = new int[max_slots][,];
    4.  
    or, if you want it to be non-static (to edit in inspector), init your array in OnEnable
     
    Last edited: Feb 10, 2019
    Ryiah likes this.
  3. CobaltTheFox

    CobaltTheFox

    Joined:
    May 29, 2015
    Posts:
    27
    Thank you!