Objects respawn out of bond ?

Hey Guys,

I’m trying to make a snake game. I created snake and a game background. Then, I tried to spawn random food to be eaten by snake. But foods respawn out of my gamebackground.

public class FoodHandler 
{
    private Vector2Int foodPosition ;
    private int width;
    private int height;

    public FoodHandler(int width, int height)
    {
        this.width = width;
        this.height = height;

        SpawnFood();
        FunctionPeriodic.Create(SpawnFood, 1f);

    }


    private void SpawnFood()
    {
        foodPosition = new Vector2Int(Random.Range(0, width), Random.Range(0, height));
        GameObject foodGameObject = new GameObject("Snake'sFood", typeof(SpriteRenderer));
        foodGameObject.GetComponent<SpriteRenderer>().sprite = GameAssets.i.foodSprite;
        foodGameObject.transform.position = new Vector3(foodPosition.x, foodPosition.y);
        
    }

}

Other Script :

public class GameHandler : MonoBehaviour {

    private FoodHandler foodHandler;

    private void Start() {

        foodHandler = new FoodHandler(20, 20);
    }

    private void Update()
    {
       
        
    }

}

The random range is returning a random value between 0 and 20, but it appears that your background object is sitting at position x0, y0. So that random position will be somewhere from the centre of the background to 20 units to the positive x (right in your screen shot) and 20 units positive y (upwards in your screen shot). You would need to change that random range so it starts at the lower left corner of your BG which is likely -10 on the x and y to +10

Any toughts ?

Thanks for your answer. It fıxed my problem