A simple shoting code that make lags
Hello,
I'm making a 2D top-down shooter. I just made a new way to shot, but it's making the game to stop for half a second when it's happening. This script make bullets spawning at 360° around the shoter.
I don't know where the lag come from. Here is my script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Vague : MonoBehaviour {
public Enemy enemy;
public int angle = 0;
public int augmAngle = 18;
public bool trou;
// Use this for initialization
void Start () {
enemy = GetComponent<Enemy>();
}
// Update is called once per frame
void Update()
{
if (Time.time >= enemy.cooldown)
{
for (int i = 0; i < 360; i+=augmAngle)
{
Rigidbody2D ebPrefab = Instantiate(enemy.enemybulletprefab, transform.position, Quaternion.identity) as Rigidbody2D;
ebPrefab.transform.SetParent(GetComponent<Collider2D>().transform.root); // ca met les tirs dans la map
ebPrefab.GetComponent<EnemyShotStrenght>().perso = enemy.persoGO;
Vector3 dir = Quaternion.AngleAxis(i, Vector3.forward) * Vector3.right;
ebPrefab.AddForce(dir * enemy.speedDelAtk);
}
enemy.cooldown = Time.time + enemy.attackspeed;
}
}
}
You closed this because you got the right answer and accepted it...
Except there were no answers, let alone one marked as accepted.
I made @Hellium's comment into an answer so you can accept it and, if you want, you can re-close for the same reason after that.
Answer by Hellium · Dec 17, 2017 at 06:12 PM
You are instantiating 20 items in a single frame, retrieving multiple components, etc.
You should seriously consider using Object pooling
That's pretty simple, but very smart ! It works fine, thank you :D
Your answer
Follow this Question
Related Questions
Can some one help me with my C# script? (HUD) 0 Answers
Acceleration issue 0 Answers
Call function when prefab is collided 1 Answer
A more optimized way to adjust duplicate integer values In a list? 0 Answers