Question

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

Was it helpful?

Solution 2

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;
        }
    }
}

OTHER TIPS

It may be one or more of these three things:

1 - the float comparison with the int 1 always return false. Use Mathf.Approximately:

if (Mathf.Approximately(tex.GetPixel(x,tex.height-y).r, 1f) return;

2 - you do not test the limits of the texture, so x and y grow to +infinity and -infinity, since GetPixel off the limits won't return anything red :)

3 - Stack memory is a limited resource, if you have a big texture the stack won't be enough to stack so many method calls. Use System.Collections.Generic.Stack<> instead.

May I ask you why are you implementing a flood-fill algorithm in Unity?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top