Question by
uptownleaf151 · Feb 05, 2021 at 04:48 PM ·
gameobjectinstantiatespawntimerloop
My gameObject (enemy) is being spawned rapidly to the point of crashing, how do I fix this?
I am having a problem where when the prefab is spawned, it spawns rapidly multiple times, getting faster and faster until it lags and crashes, I do not know how to fix it. Any suggestions? Heres the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlastScript : MonoBehaviour
{
private Rigidbody2D rb;
float timer = 0.0f; //keep track of time passed
float randtime; //stores random spawn time
public GameObject spawnPoint; //gives spawn position
public GameObject enemy; //gameObject for EnemyShip
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.rotation = Random.Range(0f, 360f);
randtime = Random.Range(0f, 15f);
}
// Update is called once per frame
void FixedUpdate()
{
rb.AddForce(transform.up * 120);
if(timer < randtime)
{
GameObject ship = Spawn();
Vector2 dir = (Vector2)(Quaternion.Euler(0, 0, Random.Range(0f, 1f)) * Vector2.right);
ship.GetComponent<Rigidbody2D>().velocity = dir * Random.Range(100f, 200f) * Time.deltaTime;
randtime = Random.Range(0.1f, 0.2f);
timer = 0.0f;
}
timer += Time.deltaTime;
}
GameObject Spawn()
{
return Instantiate(enemy, spawnPoint.transform.position, Quaternion.Euler(0f, 0f, 0f));
}
}
Comment