Z
Z
Zefirot2021-11-06 17:25:57
C++ / C#
Zefirot, 2021-11-06 17:25:57

How to create an array of objects without size (without List and Dictionary)?

For certain reasons, I need to create arrays of objects GameObject[] ArrayObj
But I don’t always know how many there will be, as I understand it is impossible to set an array of indefinite size, also for certain reasons I don’t want to use List or Dictionary (we won’t go into details why) ...
So far I have 2 ideas how to do it:

1. Create an array with much more elements , for example, set 10 objects there and when pulling them out like this

GameObject[] ArrayObj = new GameObject[100];

foreach(GameObject obj in ArrayObj){ if(obj != null){ ........... }}


2. the same as the first option using a temporary array to calculate the length
GameObject[] ArrayObjTemp = new GameObject[100];
foreach(GameObject obj in ArrayObjTemp){ if(obj != null){ ++n }}
GameObject[] ArrayObj = new GameObject[n];
foreach(GameObject obj in ArrayObjTemp){ if(obj != null){ ArrayObj[n] = obj; ++n }}


I understand that many will say "why such bicycles", but I now need arrays of objects without List and Dictionary ...
Tell me how best to do what was planned?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vasily Bannikov, 2021-11-07
@vabka

Reading the comments - the reasons why you want to use arrays instead of List`1 are
speculation, and based on nothing.
In practice, you will not feel any difference between a List and an array in terms of memory and speed.
So take System.Collections.Generic.List<T>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question