- Home /
Getting NullReferenceException from the enemies my spawner makes and it won't collide with my weapon.
I'm getting the NullReferenceException error in my game from the enemies that I spawn using my spawner. I have some enemies on the stage that work fine but when they are all destroyed the error occurs with the new batch where my weapon doesn't collide with them anymore because it can't find the gameobject.
This is what I used for my spawner: public class bugSpawner : MonoBehaviour {
public float spawnTime = 5f; // The amount of time between each spawn.
public float spawnDelay = 3f; // The amount of time before spawning starts.
public GameObject[] enemies; // Array of enemy prefabs.
private Vector3 startPosition;
public GameObject enemybug;
void Start ()
{
// // Start calling the Spawn function repeatedly after a delay .
InvokeRepeating("Spawn", spawnDelay, spawnTime);
}
void Spawn ()
{
startPosition = transform.position;
GameObject bugspawn = Instantiate(enemybug) as GameObject;
bugspawn.transform.position = transform.position;
}
}
And this is for my weapon
void OnTriggerEnter2D (Collider2D col)
{
GameObject Bugbot = GameObject.Find ("bugspawn");
Transform BugbotTransform = Bugbot.transform;
// get player position
Vector3 bugbotxposition = BugbotTransform.position;
// If it hits an enemy...
if (col.tag == "Enemy") {
col.gameObject.GetComponent<Bugbot>().HP -= 2;
if (gameObject.transform.position.x > bugbotxposition.x){
col.gameObject.GetComponent<Bugbot>().bumpRight();
}
if (gameObject.transform.position.x < bugbotxposition.x){
col.gameObject.GetComponent<Bugbot>().bumpLeft();
}
}
}
Edit:
I get this error everytime NullReferenceException: Object reference not set to an instance of an object Swatter.OnTriggerEnter2D (UnityEngine.Collider2D col) (at Assets/Scripts/Swatter.cs:19)
line 19 is:
Transform BugbotTransform = Bugbot.transform;
Please edit your question and paste in a copy of the error message from the console. Also indicate in your question what line is generating the error.
Oh sorry, new at this. Here's the weird part: I have a bugbot in the scene when the game starts and while that bugbot is present all the others work fine and I can destroyed them and the script finds all the bugbots being spawned. But when the first bugbot, the one present at the start, gets destroyed all the bugbots now return a nullreferenceexception. I did the same as the 2d tutorial did but for some reason it's not finding the gameobjects that I spawn.