gameObject destroying itself

So I have a gameObject ‘playerShip’ that is my ship in my asteroids re-make. For some reason whenever I try to instantiate it, weird stuff happens. When it collides with an asteroid it destroys itself, decrements p1Lives and then Instantiates a new playerShip. Sometimes it creates the playerShip, and then 2 seconds later after it moves it destroys itself. Sometimes it doesn’t even spawn the asteroid. I don’t know why, but here’s some code to hopefully trigger someone’s lightbulb as to why this is happening. If you need more code I will gladly post it.

//player controller class 
	void OnTriggerEnter(Collider other){
		if(other.transform.tag == "a_large" || other.transform.tag == "a_medium" || other.transform.tag == "a_small")
		{
			GC.p1Lives--;
			GC.RespawnPlayer();
			Destroy (gameObject);
		}
	}
//Destroy (gameObject) is refering to gameObject 'playerShip'

//GameController class calls the RespawnPlayer method
	public void RespawnPlayer()
	{
		if(p1Lives > 0){
			if(!Physics.CheckSphere (Vector3.zero, 256f)){
			Instantiate(playerShip, new Vector3(0,0,0), Quaternion.identity);	
			//print (p1Lives);
				CancelInvoke ("RespawnPlayer");
			}
		}
	}
//i put in "print(p1Lives)" to see if it was problems with decrementing, but this is not the case.

1 Answer

1

Would need more details on your setup to verify this, but are you passing in the reference of the gameObject that you are queueing up for destruction to the Instantiate method? That might account for the behaviour you’re seeing. Try making your player ship into a prefab and pass that in to Instantiate instead.

I assume you have a way of accounting for that CheckSphere failing as well.

“Sometimes it doesn’t even spawn the asteroid” - did you mean playerShip or are you actually needing to spawn another asteroid or something?

Yeah sorry not asteroid, but 'playerShip' also, my playership is a prefab :(