- Home /
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.
Answer by Roland1234 · Nov 27, 2013 at 04:00 PM
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 :(
If you've verified that your colliders are set-up correctly then try:
Add a bool to the player controller class, initialized to false, and add the logic to only destroy the ship if it is false (setting it to true the first time it has been queued up to Destroy).
Remove the CheckSphere condition and add a timer to the player controller class ins$$anonymous$$d (initialized at something like 2 seconds) which will exit the OnTrigger$$anonymous$$ethod until it winds down to zero. Remove the CancelInvoke call as it shouldn't be necessary.
These may be considered just intermediary steps to try and narrow down the issue - if none of the above work then there's something else going on and I'd need to see the full scripts involved (and maybe more details about your scene setup).
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Flip over an object (smooth transition) 3 Answers