Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

Помогите с Unity - ошибка NullReferenceException

Иван Программист Ученик (110), открыт 1 неделю назад
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameWorld : MonoBehaviour
{
public Dictionary<Vector2Int, ChunkData> ChunkDatas = new Dictionary<Vector2Int, ChunkData>();
public ChunkRenderer ChunkPrefab;

private Camera mainCamera;

private void Start()
{
mainCamera = Camera.main;

for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
float xPos = x * ChunkRenderer.ChunkWidth * ChunkRenderer.BlockScale;
float zPos = y * ChunkRenderer.ChunkWidth * ChunkRenderer.BlockScale;

ChunkData ChunkData = new ChunkData();
ChunkData.ChunkPosition = new Vector2Int (x, y);
ChunkData.Blocks = TerrainGenerator.GenerateTerrain(xPos, zPos);
ChunkDatas.Add(new Vector2Int(x, y), ChunkData);

var chunk = Instantiate(ChunkPrefab, new Vector3(xPos, 0, zPos), Quaternion.identity, transform);
chunk.ChunkData = ChunkData;
chunk.ParentWorld = this;

ChunkData.Renderer = chunk;
}
}

}

private void Update()
{
if(Input.GetMouseButtonDown(1))
{
Ray ray = mainCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f));

if (Physics.Raycast(ray, out var hitInfo))
{
Vector3 blockCenter = hitInfo.point + hitInfo.normal * ChunkRenderer.BlockScale / 2;
Vector3Int blockWorldPos = Vector3Int.FloorToInt(blockCenter / ChunkRenderer.BlockScale);
Vector2Int chunkPos = GetChunkContainingBlock(blockWorldPos);
if(ChunkDatas.TryGetValue(chunkPos, out ChunkData ChunkData))
{
Vector3Int chunkOrigin = new Vector3Int(chunkPos.x, 0 , chunkPos.y) * ChunkRenderer.ChunkWidth;
ChunkData.Renderer.SpawnBlock(blockWorldPos - chunkOrigin);
}
}
}
}

public Vector2Int GetChunkContainingBlock(Vector3Int blockWorldPos)
{
return new Vector2Int(blockWorldPos.x / ChunkRenderer.ChunkWidth, blockWorldPos.z / ChunkRenderer.ChunkWidth);
}
}
0 ответов
Похожие вопросы