Search code examples
c#unity-game-enginepixel

Make everything inside the red line red


I have a Stack overflow error in unity. This will make everyhing within the red line red. Is there a way to solve this? or is there a better way to make everything in the red line red?

void Checkpoint(Texture2D tex, int x, int y){

    if (tex.GetPixel(x,tex.height-y).r == 1) return;

    tex.SetPixel(x,tex.height-y,Color.red);

    Checkpoint(tex,x+1,y);
    Checkpoint(tex,x,y+1);
    Checkpoint(tex,x-1,y);
    Checkpoint(tex,x,y-1);

    return;
}

I want to make everything red within the red line enter image description here


Solution

  • I have find the way. Here is my coe

    void Stack(int x, int y, Texture2D tex){
    
        //make a list and add the first pixel 
        List<PT> toDo = new List<PT>();
        toDo.Add(new PT(x,y,state));
    
        while(toDo.Count != 0){
    
            PT thisPoint = toDo[toDo.Count-1];
    
            switch(thisPoint.State){
                case 0:
    
                    //remove this pixel from the list when he is red
                    if (tex.GetPixel(thisPoint.X,tex.height-thisPoint.Y).r == 1f) {
                        toDo.RemoveAt(toDo.Count-1);
                    }else{
    
                        //change state and add the right pixel
                        tex.SetPixel(thisPoint.X,tex.height-thisPoint.Y,new Color(1,0,0));
                        toDo[toDo.Count-1].State = 1;
                        toDo.Add(new PT(thisPoint.X+1,thisPoint.Y,0));
                    }
                break;
    
                //add the pixel below this one
                case 1:
                    toDo[toDo.Count-1].State = 2;
                    toDo.Add(new PT(thisPoint.X,thisPoint.Y+1,0));
                break;
    
                //add left pixel
                case 2:
                    toDo[toDo.Count-1].State = 3;
                    toDo.Add(new PT(thisPoint.X-1,thisPoint.Y,0));
                break;
    
                //add the last pixel and remove himself
                case 3:
                    toDo.RemoveAt(toDo.Count-1);
                    toDo.Add(new PT(thisPoint.X,thisPoint.Y-1,0));
                break;
            }
        }
    }