-1

At the beginning of my script I have this line:

Color[] oldColor;

Later I want to fill it with elements so in a function I wrote:

for (int i = 0; i < targets.Length; i++)
        oldColor[i] = targets[i].color;

However, the first line is underlined in green and it says that I can't assign a value except from its default value (which is null). Also the line below the for loop (where it should copy the values from one array to the other) gives me NullReferenceException when I run it in Unity.

'targets' is defined as

SpriteRenderer[] targets;

All of its elements are assigned via the Inspector.

I don't understand what happens. Why doesn't it assign the variables?

NicknEma
  • 414
  • 3
  • 13
  • 2
    What if you initialize oldColor like this - ```Color[] oldColor = new Color[targets.Length];``` The error I get when I put your code in LINQPad is ```Use of unassigned local variable 'oldColor'``` You need to initialize it before you can use it. – nickfinity May 19 '20 at 12:19
  • Refer this Link [enter link description here](https://stackoverflow.com/questions/202813/adding-values-to-a-c-sharp-array) – Iam_NSA May 19 '20 at 12:24

2 Answers2

4

You have to initialize an array and set its size before adding items to it:

Color[] oldColor = new Color[10];   // just an example - use whatever size is appropriate

Then you can set its elements.

A more flexible solution (if you don't know the size beforehand) is to use List instead:

List<Color> oldColor = new List<Color>();

for(...)
{
    oldColor.Add(targets[i].color);
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240
0

with linq you could copy directly the value of target.color to oldColor, no array size problem

using System.Linq;
:
:
Color[] oldColor = targets.Select(s => s.color).ToArray();
Frenchy
  • 16,386
  • 3
  • 16
  • 39