Instantiate(this.gameObject) causing crash

I’m creating a game similar to asteroids. Currently I have an asteroid with X max health, and upon reaching half of that, it reduces in size, sets max hp to current, then makes a copy of itself. When an asteroid’s health hits <= 1, it’s destroyed.

public class AsteroidBreak : MonoBehaviour {
	
	public int startingHealth;
	private int health;

	void Start () {
		health = startingHealth;
	}

	void OnTriggerEnter (Collider other){
		Debug.Log("It's a hit!");
		if (other.tag == "Shot") {
			health--;
		}
		if (health <= 1) {
			Destroy(this.gameObject);
		}
		if (health <= startingHealth/2) {
			transform.localScale = transform.localScale/2;
			startingHealth = health;
			Instantiate(this.gameObject);
		}
	}
}

However, I’m finding the game grinds to <5 fps or crashes upon destroying a copied asteroid. I tested it with

//Instantiate(this.gameObject);

and the asteroids reduced in size and were destroyed fine. I went back and tested it more with cloning, and it only seems to be the copies’ copies getting destroyed that causes a crash. (The original asteroid keeps moving in the same direction after shrinking, so it’s easy to tell which are copies/originals).

I’m not really sure what the problem is. I was hoping to come up with some system that allows for dynamic asteroid size.

I can’t help with the crash but i have some advice. A simple work around would be to attach a prefab to the script in the editor and instantiate that. i’ve never tried to instantiate anything like that however. I know sometimes static anything can cause small issues in mono, but i doubt that is the case. If i were you I’d restart your PC or at least Unity and if that fails, try the work around.

I figured out the problem! Here’s the complete working script:

public class AsteroidBreak : MonoBehaviour {
	
	public int startingHealth;
	private int health;

	void Start () {
		health = startingHealth;
	}

	void OnTriggerEnter (Collider other){
		if (other.tag == "Shot") {
			health--;
		}
		if (health <= 1) {
			Destroy(gameObject);
		}
		if (health <= startingHealth/2 && health > 1) {
			transform.localScale = transform.localScale*0.6f;
			transform.rotation = Quaternion.Euler(0, 0, Random.Range(0, 359));
			startingHealth = health;
			Instantiate(gameObject);
		}
	}
}

adding the “&& health > 1” condition to the last if statement seemed to fix the problem. I guess that sometimes the object ran the third if statement before the script was stopped.