1

I need to declare an Array of Lists variable in Unity. Array size is fixed and it is 5. My code is working as i want, but i think there must be a better and a shorter way to do it:

public List<GameObject>[] charactersOnBoardSortedP1 = new List<GameObject>[] {new List<GameObject>(), new List<GameObject>(), new List<GameObject>(), new List<GameObject>(), new List<GameObject>() };

I tried to do like this:

public List<GameObject>[] charactersOnBoardSortedP1 = new List<GameObject>[5];

But i have an error: Object reference not set to an instance of an object.

Is there any way to declare my variable simpler? I mean if my array has only 5 slots it's ok, but what if 100? It's kind of stupid to copy new List... 100 times in declaration.

Jim Hopper
  • 13
  • 1
  • 4
  • 1
    You could use target-type. c# 9? feature eg. https://sharplab.io/#v2:EYLgtghglgdgNAFxAJwK7wCYgNQB8ACATAAwCwAUEQIwX7EAE+VALANwW1UCcAFAESAeDcAg+3wCU7crQDMjQvQBiAe0UUA3hXqbGMgDJQAzggA8AcQhgApgHlgAKwsBjBAD4A2gF16DgBYRkEJwtkfSsYACFFPwwAZUVkBAsMAAUqegBeehgLAHd6PUNTc2s7RxcPVSzcnlE4TJz6atrKhpq6qtbm6voAXwlujkoZInozSxt7JzUNLQpuoA - https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/target-typed-new – Rand Random Nov 06 '21 at 17:11
  • Well an array of anything. You declare the array and make one of thr right size. Then if it has class based objects you would need to fill the array with the newly made class objects. Loops are often the easiest way to set it up – BugFinder Nov 06 '21 at 17:19
  • @Jim Hopper - You can accept the answer which is suitable for your solution – Shreekesh Murkar Nov 07 '21 at 12:32
  • Why not use a loop? – derHugo Nov 07 '21 at 15:44
  • Basically this is a duplicate of [What is a NullReferenceException and how do I fix it](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) since you create an array but didn't initialize the list instances – derHugo Nov 08 '21 at 05:55
  • @RandRandom it is still pretty uncanny and hardcoded if you have 100 elements ;) a loop is the better option .. also since people start to mention this all the time now: Afaik Unity doesn't support c#9 so far ... ;) – derHugo Nov 08 '21 at 05:56

3 Answers3

2

try this

var  arraySize=6; //or what size you need

List<GameObject>[] charactersOnBoardSortedP1 = new List<GameObject>[arraySize];

charactersOnBoardSortedP1=  charactersOnBoardSortedP1
                           .Select(obsp => obsp = new List<GameObject>()) 
                            .ToArray();

or if you need to init some more things in the same time

for (var i=0; i<  charactersOnBoardSortedP1.Length; i++)
{
    charactersOnBoardSortedP1[i]=new List<GameObject>();
    // if you need to add some elements in the same time
    charactersOnBoardSortedP1[i].Add(new GameObject {Id=i});
}
Serge
  • 40,935
  • 4
  • 18
  • 45
  • Have in mind that `new GameObject` spawns a new object into the scene which might not really be what OP wants to do! I think OP only wants the list instances created but without any elements within them ;) – derHugo Nov 07 '21 at 19:22
  • @derHugo Thanks, As you can see I have 2 variants - one with empty list, another variant just shows the most comfortable (IMHO) way to add some objects to the list if needed. – Serge Nov 07 '21 at 19:58
  • Just wanted to mention that because seemingly not everyone knows how `GameObject` works ;) In the first code snippet the `new List[arraySize];` is completely redundant though since later you anyway overwrite it via Linq – derHugo Nov 08 '21 at 05:52
2

Easiest way to achieve it is as follows:

int arraySize = 5;
List<GameObject>[] charactersOnBoardSortedP1 = Enumerable.Repeat(new List<GameObject>(), arraySize).ToArray();

This will create array of specified size filled with empty List<GameObject>()

If you wish to have list to have GameObject you can modify above code a bit.

int arraySize = 5;
List<GameObject>[] charactersOnBoardSortedP1 = Enumerable.Repeat(new List<GameObject> { new GameObject()}, arraySize).ToArray();
  • Have in mind that `new GameObject` spawns a new object into the scene which might not really be what OP wants to do! I think OP only wants the list instances created but without any elements within them ;) – derHugo Nov 07 '21 at 19:24
  • @derHugo I have mentioned solution for that as well. – Shreekesh Murkar Nov 08 '21 at 04:32
1

try this. Test here

Create an Array of list variables. initialise each Array items to a new list of GameObject. then you can add to said array's list.

using System;
using System.Text;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        // create array of lists
        List<GameObject>[] COBSP1 = new List<GameObject>[5]; //charactersOnBoardSortedP1
        // setup lists
        COBSP1[0] = new List<GameObject>();
        COBSP1[1] = new List<GameObject>();
        COBSP1[2] = new List<GameObject>();
        COBSP1[3] = new List<GameObject>();
        COBSP1[4] = new List<GameObject>();
        
        // add objects to said list
        COBSP1[0].Add(new GameObject());
        COBSP1[0].Add(new GameObject());
        COBSP1[0].Add(new GameObject());
        COBSP1[0].Add(new GameObject());
        
        COBSP1[1].Add(new GameObject());
        COBSP1[1].Add(new GameObject());
        COBSP1[1].Add(new GameObject());
        COBSP1[1].Add(new GameObject());
        
        COBSP1[2].Add(new GameObject());
        COBSP1[2].Add(new GameObject());
        COBSP1[2].Add(new GameObject());
        COBSP1[2].Add(new GameObject());
        
        COBSP1[3].Add(new GameObject());
        COBSP1[3].Add(new GameObject());
        COBSP1[3].Add(new GameObject());
        COBSP1[3].Add(new GameObject());
        
        COBSP1[4].Add(new GameObject());
        COBSP1[4].Add(new GameObject());
        COBSP1[4].Add(new GameObject());
        COBSP1[4].Add(new GameObject());
    }
    
}
Dean Van Greunen
  • 5,060
  • 2
  • 14
  • 28