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 Jagged Array of integers

Discussion in 'Scripting' started by TecknoUnity, Jul 23, 2022.

  1. TecknoUnity

    TecknoUnity

    Joined:
    Jul 17, 2022
    Posts:
    5
    How to make jagged arrays in unity / c#. I have been doing so research online but I give up.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class JaggedArray: MonoBehaviour
    6. {
    7.     public int[][] array = new int[3][3];
    8.  
    9. }
    10.  
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,845
    TecknoUnity and Bunny83 like this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,524
    What spiney said is correct. Unity does not support the serialization of jagged or multidimensional arrays and therefore can't show them / edit them in the inspector. However you "create" them like explained over here. They can be used in code just fine, you just don't get any inspector or serialization support for them.

    From your one line descrption it's not really clear what you want to do. What you have to understand is that jagged arrays essentially consists of two main parts: the main array and all the sub arrays that are stored inside the main array. You can not create all those objects with a single "new" statement. Just have a look at the code example in the documentation page I've linked.

    If you need a solution that can be serialized / edited in the inspector you have to use a single dimensional list / array of a serializable class that would contain another array.

    Code (CSharp):
    1. [System.Serializable]
    2. public class MyClass
    3. {
    4.     public int[] subArray;
    5. }
    6.  
    7. public MyClass[] array;
    This can be serialized by Unity. Each element of "array" contains a MyClass instance and each of that instance has its own "subArray".
     
    d3eds and TecknoUnity like this.
  4. TecknoUnity

    TecknoUnity

    Joined:
    Jul 17, 2022
    Posts:
    5
    Thank you so much @Bunny83, but one question. If I am going for the solution I want to be serialized / edited in the inspector, then do I need 2 C# files?

    1.--
    Code (CSharp):
    1. [System.Serializable]
    2. public class MyClass
    3. {
    4.     public int[] subArray;
    5. }
    2.--
    Code (CSharp):
    1. public MyClass[] array;
     
  5. TecknoUnity

    TecknoUnity

    Joined:
    Jul 17, 2022
    Posts:
    5
    I managed to create a jagged array already so I would like to make numbers to show up in the inspector.