Hi guys,
I have been trying to access the Renderer from a Transform that I have instantiated.
The error is "Object reference not set to an instance of an object", and it appeared at the GridEnable and GridDisable functions, where I called the tile.gameObject.renderer.enabled.
This is the GridScript, which control the grid in a 2D plane:
using UnityEngine;
using System.Collections;
public class GridScript : MonoBehaviour {
public int gridWidth = 9;
public int gridHeight = 9;
public int remainingGrid;
public int totalGrid;
public Transform[,] grid;
public int[,] gridStatus;
public int[,] gridBorder;
private PlayerControl playerControl;
// Use this for initialization
void Awake ()
{
playerControl = GameObject.FindWithTag ("Player").GetComponent();
}
public void GridEnable(Transform tile)
{
tile.gameObject.renderer.enabled = true;
int x = Mathf.RoundToInt (tile.localPosition.x);
int y = Mathf.RoundToInt (tile.localPosition.y);
gridStatus [x, y] = 0;
}
public void GridDisable(Transform tile)
{
tile.gameObject.renderer.enabled = false;
int x = Mathf.RoundToInt (tile.localPosition.x);
int y = Mathf.RoundToInt (tile.localPosition.y);
gridStatus [x, y] = 1;
}
}
And This is the GridSetup, which used to generate the grid from a text file
using UnityEngine;
using System.Collections;
public class GridSetup : MonoBehaviour {
public int gridHeight = 9;
public int gridWidth = 9;
public Transform normalTile;
public TextAsset textFile;
private GridScript gridScript;
private string text;
// Use this for initialization
void Awake () {
gridScript = GetComponent();
text = textFile.text;
CreateGrid (text, gridScript);
}
// Translate a text file into a map of grid, store in gridScript
void CreateGrid (string text, GridScript gridScript) {
// Initialize the grid
gridScript.gridHeight = gridHeight;
gridScript.gridWidth = gridWidth;
gridScript.grid = new Transform[gridWidth + 2, gridHeight + 2];
gridScript.gridStatus = new int[gridWidth + 2, gridHeight + 2];
gridScript.gridBorder = new int[gridWidth + 2, gridHeight + 2];
gridScript.totalGrid = gridHeight * gridWidth;
int xx = 0;
int yy = gridHeight;
foreach (char c in text)
{
if (c == '\r') continue;
if (c == '\n') {
xx = 0;
yy--;
}
else {
xx++;
gridScript.grid[xx, yy] =
Instantiate(normalTile, new Vector3((float)xx, (float)yy, 8f), Quaternion.identity) as Transform;
if (c == 'x') {
gridScript.GridDisable(gridScript.grid[xx, yy]);
gridScript.totalGrid--;
}
else
{
gridScript.GridEnable(gridScript.grid[xx, yy]);
}
}
}
gridScript.remainingGrid = gridScript.totalGrid;
}
}
↧