Hey,
Creating my first project ever, a snake game, and I’m running into a confusing bug.
I create an instance of a sprite which I called Food, and I set it’s position to a random position in a range of 20 by 20, whenever I press play, the sprite does not appear on the game view, but the game continues to run perfectly without errors regardless. I included an example image below.
I have three very small scripts that handle the spawning of the food game object, which I have included below:
LevelGrid Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LevelGrid
{
private Vector2Int foodGridPosition;
private int width;
private int height;
public LevelGrid(int width, int height)
{
this.width = width;
this.height = height;
SpawnFood();
}
private void SpawnFood()
{
foodGridPosition = new Vector2Int(Random.Range(0, width), Random.Range(0, height));
GameObject foodGameObject = new GameObject("Food", typeof(SpriteRenderer));
foodGameObject.GetComponent<SpriteRenderer>().sprite = GameAssets.i.foodSprite;
foodGameObject.transform.position = new Vector3(foodGridPosition.x, foodGridPosition.y);
}
}
GameAssets Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameAssets : MonoBehaviour
{
public static GameAssets i;
private void Awake()
{
i = this;
}
public Sprite snakeHeadSprite;
public Sprite foodSprite;
}
GameHandler Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameHandler : MonoBehaviour
{
private LevelGrid levelGrid;
private void Start()
{
Debug.Log("GameHandler Called!");
levelGrid = new LevelGrid(20, 20);
}
}
Would anyone know why this bug is occuring?
Thank you
Example of issue (no food sprite appearing):