adjacent tiles within range
I made a script that highlights all tiles within a range. It works fine when it is far from the edges but it gives me " NullReferenceException: Object reference not set to the instance of an object" at line 83
Here is the script:
public List<Tile> highlihtedTiles = new List<Tile>();
public void HighlightAdjacentTiles(int xPos,int yPos,int _range)
{
int range = _range + 1;
for (int x = -range; x < range; x++)
{
for (int y = -range; y < range; y++)
{
if (xPos - x > 0 && yPos - y > 0 && xPos + x < mapSizeX && yPos + y < mapSizeY)
{
if ((Mathf.Abs(x - y) < range) && (Mathf.Abs(y + x) < range))
{
var result = tiles[xPos + x, yPos + y];
highlihtedTiles.Add(result);
}
}
}
}
for (int x = 0; x < highlihtedTiles.Count; x++)
{
highlihtedTiles[x].GetComponent<SpriteRenderer>().color = Color.green;// line 83
highlihtedTiles[x].highlightd = true;
}
}
Comment
Answer by Jessespike · Nov 15, 2015 at 03:34 PM
Seems like some of the highlightedTiles do not have a SpriteRenderer. I guess the simplest fix would be to check for any nulls:
for (int x = 0; x < highlihtedTiles.Count; x++)
{
if (highlihtedTiles[x] != null && highlihtedTiles[x].GetComponent<SpriteRenderer>() != null)
{
highlihtedTiles[x].GetComponent<SpriteRenderer>().color = Color.green;// line 83
highlihtedTiles[x].highlightd = true;
}
|
Your answer
![](https://koobas.hobune.stream/wayback/20220612045151im_/https://answers.unity.com/themes/thub/images/avi.jpg)