Hello everyone, this is my first time posting a question, although I’ve been stalking the forums for a few months as I teach myself Unity and C#.
So the problem is, I’m instantiating an enemy object and grabbing its specific AI sensor component. I then attempt to initialize a few variables, and it returns the infamous “Object reference not set to an instance of an object”. It then, obviously, doesn’t initialize the variables. Although the scene runs fine with no compile errors.
Here is the function
void SpawnEnemies()
{
SensorAI newEnemySensor = (Instantiate (enemies[cycleColor], proceduralWaypoints[0].transform.position + new Vector3(0,1,0), Quaternion.Euler (Vector3.zero))as GameObject).GetComponent<SensorAI>();
newEnemySensor.transform.parent = transform;
newEnemySensor.waypoints = proceduralWaypoints;
}
Any and all help is appreciated. Thanks!!
I would suggest breaking this line down so that you can examine each part:
SensorAI newEnemySensor = (Instantiate (enemies[cycleColor], proceduralWaypoints[0].transform.position + new Vector3(0,1,0), Quaternion.Euler (Vector3.zero))as GameObject).GetComponent<SensorAI>();
This could be broken down to:
Vector3 position = proceduralWaypoints[0].transform.position + new Vector3(0,1,0);
Quaternion rotation = Quaternion.Euler(Vector3.zero); // this could also be Quaternion.identity
GameObject go = Instantiate(enemies[cycleColor], position, rotation) as GameObject;
SensorAI newEnemySensor = go.GetComponent<SensorAI>();
Now if any errors occur you can isolate it’s location to a smaller piece of code. I suggest setting a breakpoint or using Debug.Log()
statements to confirm that each variable is assigned the expected value on each line.
“Object reference not set to an instance of an object” means something is null and you’re trying to access its methods/properties. You can’t access methods/properties of something that doesn’t exist. Either your GameObject is null, meaning enemies[cycleColor] is returning null, or the GameObject prefab doesn’t have a SensorAI component. Try this to find out which is null.
void SpawnEnemies() {
GameObject newEnemy = (GameObject)Instantiate(enemies[cycleColor], proceduralWaypoints[0].transform.position + Vector3.up, Quaternion.identity);
if (newEnemy == null) {
Debug.Log("GameObject is null");
return;
//GameObject is null. That means enemies[cycleColor] is null
}
SensorAI newEnemySensor = newEnemy.GetComponent<SensorAI>();
if (newEnemySensor == null) {
Debug.Log("SensorAI is null");
//SensorAI is null. Means your prefab doesn't have a SensorAI component
}
}