I cant by the love of all things good, understand why I get the error:
NullReferenceException: Object reference not set to an instance of an object
MonsterSpawner.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/MonsterSpawner.cs:25)
this is the part of the script that seems to be wrong?
The particular line it is coplaining about is: if (!objectHit.getIsMonster())
void OnTriggerEnter(Collider other)
{
DamageManagement objectHit = (DamageManagement)other.GetComponent("DamageManagement");
if (!objectHit.getIsMonster())
{
for (int i = 0; i < numberOfJotuns; i++)
Instantiate(monster1, new Vector3(spawnPoint.x + 15 * randomBool(), spawnPoint.y - 2, spawnPoint.z + (Random.value * 10 * randomBool())), Quaternion.identity);
Debug.Log("It Works " + randomBool());
Destroy(this.gameObject);
}
}
The wierd thing is that everything is working as it is supposed to do? And the if sentence works as intended as well? Its just annoying getting the error, and I would like to get rid of it.
It must be the case that the object which was collided with did not have a "DamageManagement" component at all (and therefore 'objectHit' would be null).
Since you're not checking whether it's null, you'll get this error.
To correct it, try this modification, which includes an explicit check for a null reference:
void OnTriggerEnter(Collider other)
{
DamageManagement objectHit = (DamageManagement)other.GetComponent("DamageManagement");
if (objectHit == null)
{
Debug.Log("collided with "+other.name+" which has no DamageManagement!");
} else {
if (!objectHit.getIsMonster())
{
for (int i = 0; i < numberOfJotuns; i++)
Instantiate(monster1, new Vector3(spawnPoint.x + 15 * randomBool(), spawnPoint.y - 2, spawnPoint.z + (Random.value * 10 * randomBool())), Quaternion.identity);
Debug.Log("It Works " + randomBool());
Destroy(this.gameObject);
}
}
}