Hi,
I’m getting the ever-so-common null reference exception error. Although, I can’t for the life of me, figure out why. The error is as follows:
NullReferenceException: Object
reference not set to an instance of an
object Tile.OnMouseDown () (at
Assets/Scripts/Tile.cs:32)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)
Tile.cs is:
public class Tile : MonoBehaviour
{
public Vector2 GridPosition = Vector2.zero;
private Renderer rend;
private Color defaultColor;
// Use this for initialization
void Start () {
rend = GetComponent<Renderer>();
defaultColor = rend.material.color;
}
// Update is called once per frame
void Update () {
}
void OnMouseEnter()
{
rend.material.color = Color.red;
}
void OnMouseExit()
{
rend.material.color = defaultColor;
}
void OnMouseDown()
{
Debug.Log("Executes!");
Debug.Log(this);
GameManager.Instance.moveCurrentPlayer(this);
Debug.Log("Maybe?");
}
}
and GameManager.cs:
public class GameManager : MonoBehaviour {
public static GameManager Instance;
public GameObject TilePrefab;
public GameObject CharacterPrefab;
public int MapSize = 11;
int PlayerIndex;
List<List<Tile>> map = new List<List<Tile>>();
List<Player> players = new List<Player>();
void awake()
{
Instance = this;
}
// Use this for initialization
void Start ()
{
GenerateMap();
GeneratePlayers();
}
// Update is called once per frame
void Update ()
{
players[PlayerIndex].TurnUpdate();
}
public void NextTurn()
{
if (PlayerIndex + 1 < players.Count)
{
PlayerIndex++;
}
else
{
PlayerIndex = 0;
}
}
public void moveCurrentPlayer(Tile destinationTile)
{
Debug.Log(destinationTile);
Debug.Log("Player Index: " + PlayerIndex + " : " + players[PlayerIndex]);
players[PlayerIndex].moveDestination = destinationTile.transform.position + 1.5f * Vector3.up;
}
}
Background:
- Tile.cs is a component of a “tile” prefab.
- These tiles are generated at run time (this works as intended)
- The Mouse Enter/Exit stuff changes the colour of the tiles as intended
Debug.Log("Executes")
runs, than the null reference exception.- all of the debugs in moveCurrentPlayer Do Not run, nor does
Debug.Log("Maybe?");
When I click on the selected tile it gives me above stated error. But, if I debug.log(this)
it gives me the Object Name. Additionally, I checked to make sure Players[PlayerIndex]
wasn’t the issue by commenting it out adding Debug.Log(destinationTile.transform.position)
and got the same error.
If anyone can help I would be eternally grateful!