Attempting to create path finding cause editor to freeze/stuck on entering play mode

So im attempting to make a path finding algorithm.
I dont think the logic is wrong (please do tell me if its wrong), but somehow the editor freezes when playing the scene.

main logic :

void FixedUpdate()
    {
        self = this.gameObject;
        Rigidbody2D hitbox = self.GetComponent<Rigidbody2D>();

        Vector2 walkdirecton = directions[Random.Range(0, directions.Length)];
        
        for(int i = 0; i <= Random.Range(1,10);i--){
            if(i != 1){
                if (!Theres_a_wall(walkdirecton))
                {    
                    hitbox.MovePosition(hitbox.position + speed * Time.fixedDeltaTime * walkdirecton);  
                }
                else{
                    walkdirecton = new Vector2(0,0);
                }
            }
        }
    }

for checking if theres a wall in walk direction :

private bool Theres_a_wall(Vector2 direction)
    {
        wallLayer = LayerMask.NameToLayer("the fucking wall");
        Vector2 checkPosition = (Vector2)transform.position + direction * checkDistance;
        Collider2D collider = Physics2D.OverlapCircle(checkPosition, checkRadius, wallLayer);
        return collider != null; 
    }

directions use Vector2 up, down, left, right

Your for-loop starts at zero and goes backwards, meaning you will never go above the randomly generated positive value. Did you mean to do i++ instead?

Mind you there’s a lot more to go into but outside what I can type on a phone.

oh you’re right
sorry

1 Like

Nothing to apologise about! You can be coding for years and still fall into an infinite loop. Just a matter of looking at your loops and reasoning why they go infinite.

If you’re having trouble deducing that, this is where using a proper debugger helps: Unity - Manual: Debug C# code in Unity

With them you can step through the code line by line in a controlled manner and see what causes it to keep spinning.

1 Like