I need help finding why an “Object reference not set to an instance of an object” error is happening. I know what it means (I’ve read some threads before this) but I’ve definitely defined everything before the start function and created all of my objects and variables int the start function. The error says it is at line 78, but I don’t see anything wrong with that line. Here is my code:
//Simulates and generates the terrain
using UnityEngine;
using Assets;
public class SimulateTerrain : MonoBehaviour
{
//Gameobject
public GameObject terrain;
//Texture for gameobject
public Texture2D terrainTX;
//Array of each simulated pixel (custom object)
public Pixel[] pix;
//Array of colors for texture
public Color32[] col;
//transparency
private Color32 air;
//base color for dirt
private Color32 dirt;
// Use this for initialization
//brighten or darken color
Color32 DarkLight(Color32 a, int c)
{
byte r = ((byte)(a.r + c) < 0) ? ((byte)0) : (byte)(a.r + c);
byte g = ((byte)(a.g + c) < 0) ? ((byte)0) : (byte)(a.g + c);
byte b = ((byte)(a.b + c) < 0) ? ((byte)0) : (byte)(a.b + c);
return new Color32(r,g,b, 255);
}
void Start()
{
//initialize color presets
dirt = new Color32(60, 50, 20, 255);
air = new Color32(0, 0, 0, 0);
//Initialize object parts
terrain = GameObject.Find("Terrain");
terrainTX = new Texture2D(Screen.width/2,Screen.height/2, TextureFormat.ARGB32, false);
//initiallize arrays for storing color and pixel data
col = new Color32[terrainTX.width * terrainTX.height];
pix = new Pixel[terrainTX.width * terrainTX.height];
//make initial sprite transparent
for (int x = 0; x < terrainTX.width; x++)
{
for (int y = 0; y < terrainTX.height; y++)
{
col[x + (y * terrainTX.width)] = air;
}
}
//apply
terrainTX.Apply();
//generate dirt pixels (just a rectangle for now)
for (int x = 0; x < terrainTX.width; x++)
{
for (int y = 0; y < 100; y++)
{
pix[x + (y * terrainTX.width)] = new Pixel(x,y,0,DarkLight(dirt,Random.Range(0,40)-20),0);
}
}
//put pixel colors into color array
foreach (Pixel p in pix)
{
col[p.X + (p.Y * terrainTX.width)] = p.C;
}
}
//TODO: Make efficient update function.
void Update()
{
terrainTX.SetPixels32(col);
terrainTX.Apply();
terrainTX.filterMode = FilterMode.Point;
SpriteHandler.TextureToGameObject(terrain, terrainTX);
}
}
Also, yes I am aware that I am creating an object for every pixel. Yes it is for something cool.