Hi guys,
I’m developing a space game and i did a script for asteroids where everytime it gets shooted 6 times it destroy itself and instantiate 2 gameObjects like it but the half of its, anyway the problem is that when i destroy the gameObject my game has an absurd prestation drop. How can i optimize this thing?
ps. sorry for my bad english, it’s not my first language.
using UnityEngine;
using System.Collections;
public class AsteroideScript : MonoBehaviour {
public float velocita = 1f;
public float velocitaRotazione = 1f;
private int numeroAsteroide;
public GameObject asteroidePrefab;
private GameObject asteroidePrefabIstanziato;
private GameObject asteroidePrefabIstanziato2;
public GameObject proiettile;
public AudioClip colpoAudio;
public AudioClip distruzioneAudio;
private AudioSource source;
public GameObject esplosionePrefab;
private float lunghezza = 8.28959f;
private bool oneTime = true;
void Awake() {
source = GetComponent<AudioSource>();
if (lunghezza / this.transform.localScale.x >= 2) {
velocita *= 2;
velocitaRotazione *= 2;
}
}
void Start() {
}
public AsteroideScript() {
numeroAsteroide = 0;
}
public AsteroideScript(int numeroAsteroide) {
this.numeroAsteroide = numeroAsteroide;
}
public void OnTriggerEnter2D(Collider2D collision) {
Debug.Log("Collisione");
if (collision.name == string.Format("{0}(Clone)", proiettile.name)) {
if (numeroAsteroide == 5 && lunghezza / transform.localScale.x <= 2) {
source.PlayOneShot(distruzioneAudio, 1f);
if (oneTime) {
Invoke("generaA", 0.1f);
Invoke("generaB", 0.2f);
}
oneTime = false;
Destroy(this.gameObject, 0.3f);
} else if (numeroAsteroide >= 5 && lunghezza / transform.localScale.x > 2) {
source.PlayOneShot(colpoAudio, 1f);
Destroy(this.gameObject);
} else {
source.PlayOneShot(colpoAudio, 1f);
Instantiate(esplosionePrefab, collision.gameObject.transform.position, Quaternion.identity);
numeroAsteroide++;
}
}
}
void Update() {
}
void generaA() {
Debug.Log("Genera A");
asteroidePrefabIstanziato = (GameObject)Instantiate(
asteroidePrefab,
new Vector3(this.transform.position.x - (transform.GetComponent<Collider2D>().bounds.size.x / 2),
this.transform.position.y,
0),
Quaternion.identity);
asteroidePrefabIstanziato.transform.localScale = this.transform.localScale / 2;
}
void generaB() {
Debug.Log("Genera B");
asteroidePrefabIstanziato2 = (GameObject)Instantiate(
asteroidePrefab,
new Vector3(this.transform.position.x + (transform.GetComponent<Collider2D>().bounds.size.x / 2),
this.transform.position.y,
0),
Quaternion.identity);
asteroidePrefabIstanziato2.transform.localScale = this.transform.localScale / 2;
}
void FixedUpdate() {
this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y + velocita, 0);
this.transform.Rotate(Vector3.back * velocitaRotazione);
}
}