I created a tool for automatically generating a group of hexes. It can successfully create, name, and place the GameObjects in the right place. However, when I tried to make it give the objects a default sprite, I kept getting a null reference error on line 17 which just says HexImage =. If I get rid of this part of the code, the hex objects each get an empty Sprite Renderer. Is there a way to assign he default sprite other than this, or is there some way I can resolve this issue?
Here is the error I am getting:
NullReferenceException: Object reference not set to an instance of an object
HexGenerator.Create () (at Assets/Editor/HexGenerator.cs:17)
This is the code I am using:
using UnityEngine;
using UnityEditor;
using System.Collections;
public class HexGenerator
{
[MenuItem("Hex Board/Generate Tiles")]
static void Create()
{
int y = 6;
int x = 6;
float Xdist = 1.328f; //The x distance between adjacent tiles
float Ydist = 1.016f; //The y distance between adjecent tiles
//GameObject Container = new GameObject("Hexes");
GameObject HexBlueprint;
Sprite HexImage = new Sprite();
HexImage =
Sprite.Create(Resources.Load<Texture2D>("Assets/Base Hex.png"),
new Rect(0, 0, Resources.Load<Texture2D>("Assets/Base Hex.png").width, Resources.Load<Texture2D>("Assets/Base Hex.png").height),
new Vector2(0.5f, 0.5f));
for (int i = 0; i < y; i++)
{
for (int j = 0; j < x; j++)
{
if (i % 2 == 0)
{
HexBlueprint = new GameObject("Hex " + j + "," + i);
HexBlueprint.transform.position = new Vector3(j * Xdist, i * Ydist);
SpriteRenderer renderer = HexBlueprint.AddComponent<SpriteRenderer>();
renderer.sprite = HexImage;
}
else
{
HexBlueprint = new GameObject("Hex " + j + "," + i);
HexBlueprint.transform.position = new Vector3(j * Xdist + Xdist / 2, i * Ydist);
SpriteRenderer renderer = HexBlueprint.AddComponent<SpriteRenderer>();
renderer.sprite = HexImage;
}
}
}
}
}