1
  private Material NewMat;
  private Color[] oldColor;
  private Color[] newColor;

for(int i=0; i<6; i++)
            { 
                NewMat = dropObj.transform.GetChild(0).gameObject.transform.GetChild(i).GetComponent<MeshRenderer>().material;
                var tempcolor = NewMat.color;
                print(tempcolor);
                oldColor[i] = new Color(tempcolor.r,tempcolor.g,tempcolor.b,tempcolor.a); //the problem is here
                print ("Position="+i);
                newColor[i] = oldColor[i];
                dropObj.transform.GetChild(0).gameObject.transform.GetChild(i).GetComponent<MeshRenderer>().material.SetColor("_Color", newColor[i]);
            }

This Line of code Showing Error(Null):- oldColor[i] = new Color(tempcolor.r,tempcolor.g,tempcolor.b,tempcolor.a); How to fix this

Savad
  • 1,240
  • 3
  • 21
  • 50

1 Answers1

1

I suspect the problem is that oldColor and newColor arrays are not initialized. The error states a null value. Color is a struct, a value type, therefore it cannot point to null. But an array of type Color can point to null because it is a reference type.

The solution would be to initialize said arrays before using them:

oldColor = new Color[size]; //6?
newColor = new Color[size]; //6?
for(int i = 0; i < 6; i++) 
{...}

size needs to be declared and initialized before using it, of course.

A couple of notes not directly related to the question:

  1. If you don't know how big the arrays should be, consider using a generic List<Color> instead. You can add elements to it using the Add method:

    oldColor = new List<Color>();
    newColor = new List<Color>();
    for(int i = 0; i < 6; i++) 
    {
       ..
       .. 
       oldColor.Add(new Color(..));
       ..
       ..  
    }
    
  2. A lot could go wrong with the first line inside the for loop. I suggest breaking it down into multiple lines so debugging it would be easier. A direct reference to the gameObject in question could help, if it is the same gameObject always.

  3. It is a bad practice to hard code values into the condition portion of a for loop decleration. if the for loop should iterate over the entire array of old colors, declare the loop like so:

    for(int i = 0; i < oldColor.Length; i++)
    

This will make sure that for any given size of oldColor, the for loop will still iterate the entire array.

Guy Michael
  • 134
  • 10