Witajcie
Kierując się pewnym poradnikiem prostej gry unity, postanowiłem napisać prostego węża 2d w Unity i utknąłem w pewnym momencie. Przy próbie Debuga wyrzuca mi następujący error "Object reference not set to an instance of an object ". Od raz zaznaczę że jestem zupełnie początkujący, także jeśli znajdzie się ktoś kto będzie w stanie pomóc/ wytlumaczyć to proszę możliwie jak naprościej .
Ponizej zamieszczam widok z konsoli oraz kod
https://imgshare.io/image/error.pijzvx
"Skrypt GameHandler"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CodeMonkey;
using CodeMonkey.Utils;
public class GameHandler : MonoBehaviour {
[SerializeField] private Snake snake;
private LevelGrid levelGrid;
private void Start() {
Debug.Log("GameHandler.Start");
levelGrid = new LevelGrid(20, 20);
snake.Setup(levelGrid);
levelGrid.Setup(snake);
GameObject snakeHeadGameObject = new GameObject();
SpriteRenderer snakeSpriteRenderer = snakeHeadGameObject.AddComponent<SpriteRenderer>();
snakeSpriteRenderer.sprite = GameAssets.i.snakeHeadSprite;
}
}
"Skrypt Snake"
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Snake : MonoBehaviour {
private Vector2Int gridMoveDirection;
private Vector2Int gridPosition;
private float gridMoveTimer;
private float gridMoveTimerMax;
private LevelGrid levelGrid;
public void Setup(LevelGrid levelGrid) {
this.levelGrid = levelGrid;
}
private void Awake() {
gridPosition = new Vector2Int(10, 10);
gridMoveTimerMax = 1f;
gridMoveTimer = gridMoveTimerMax;
gridMoveDirection = new Vector2Int(1, 0);
}
private void Update() {
HandleInput();
HandleGridMovement();
}
private void HandleInput() {
if (Input.GetKeyDown(KeyCode.UpArrow)) {
if (gridMoveDirection.y != -1) {
gridMoveDirection.x = 0;
gridMoveDirection.y = +1;
}
}
if (Input.GetKeyDown(KeyCode.DownArrow)) {
if (gridMoveDirection.y != +1) {
gridMoveDirection.x = 0;
gridMoveDirection.y = -1;
}
}
if (Input.GetKeyDown(KeyCode.LeftArrow)) {
if (gridMoveDirection.x != +1) {
gridMoveDirection.x = -1;
gridMoveDirection.y = 0;
}
}
if (Input.GetKeyDown(KeyCode.RightArrow)) {
if (gridMoveDirection.x != -1) {
gridMoveDirection.x = +1;
gridMoveDirection.y = 0;
}
}
}
private void HandleGridMovement() {
gridMoveTimer += Time.deltaTime;
if (gridMoveTimer >= gridMoveTimerMax) {
gridMoveTimer -= gridMoveTimerMax;
gridPosition += gridMoveDirection;
transform.position = new Vector3(gridPosition.x, gridPosition.y);
transform.eulerAngles = new Vector3(0, 0, GetAngleFromVector(gridMoveDirection) -90);
levelGrid.SnakeMoved(gridPosition);
}
}
private float GetAngleFromVector(Vector2Int dir) {
float n = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
if (n < 0) n += 360;
return n;
}
}