Hello , I’m doing my first game , a simple 2D space shooter for mobile, but I’m having problems with the shooting script, unfortunately it is causing a lag and I did not know how to solve , anyone have any idea how can I improve it ?
Some parts of the code are in my native language , if someone can not understand , I can explain their functions in code. Sry for my English.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Atirar02 : MonoBehaviour
{
public Stack<GameObject> s = new Stack<GameObject> ();//GameObject Pool
public GameObject Projectile;
public GameObject ExitPoint_1;
public GameObject ExitPoint_2;
private bool CanFire;
public float ProjectileSpeed;
public bool ButtonClick;
void Awake()
{
for(int i = 0; i < 40; i++)
{
GameObject aux;
aux = (GameObject) Instantiate(Projectile);
Physics2D.IgnoreCollision(this.gameObject.GetComponent<Collider2D>(),
aux.gameObject.GetComponent<Collider2D>());
aux.AddComponent<PorNaPool>();//if a collision occurs re-add the object to the pool
aux.SetActive(false);
s.Push(aux);
}
}
void Start ()
{
Physics2D.IgnoreCollision(this.gameObject.GetComponent<Collider2D>(),
Projectile.gameObject.GetComponent<Collider2D>());
CanFire = true;
ButtonClick = false;
}
void Delay()
{
CanFire = true;
}
public void OnAtirar()
{
ButtonClick = true;
}
public void OffAtirar()
{
ButtonClick = false;
}
void FixedUpdate ()
{
if ( ButtonClick )
{
if( CanFire )
{
GameObject aux,aux2;
aux = s.Pop();
aux2 = s.Pop();
aux.SetActive(true);
aux2.SetActive(true);
aux.transform.position = ExitPoint_1.transform.position;
Physics2D.IgnoreCollision(this.gameObject.GetComponent<Collider2D>(),
aux.gameObject.GetComponent<Collider2D>());
aux.GetComponent<Rigidbody2D>().velocity = transform.up * ProjectileSpeed;
aux2.transform.position = ExitPoint_2.transform.position;
Physics2D.IgnoreCollision(this.gameObject.GetComponent<Collider2D>(),
aux2.gameObject.GetComponent<Collider2D>());
aux2.GetComponent<Rigidbody2D>().velocity = transform.up * ProjectileSpeed;
CanFire = false;
Invoke( "Delay", 0.25f );
}
}
}
}