The essence of the game: you need to run and dodge enemies that appear every few seconds and disappear after ten seconds.
The problem is that if there are more than three such enemies, the game suddenly starts to slow down.
Perhaps there are some ways to optimize or there is an error in the code.
P.S.: FPS drops when you start the game in a unit. I didn't try to compile.
Here is the code for spawning enemies and the enemy itself:
using System.Collections;
using UnityEngine;
public class SpawnEnemy : MonoBehaviour
{
public GameObject[] enemy;
public Transform[] spawnPoint;
private int randEnemy;
private int randPosition;
public float TimeStep;
/*public float startTimeBtwSpawns;
private float timeBtwSpawns;*/
private void Start()
{
StartCoroutine(SpawnObjects());
}
private void Repeat()
{
StartCoroutine(SpawnObjects());
}
IEnumerator SpawnObjects()
{
yield return new WaitForSeconds(TimeStep);
randEnemy = Random.Range(0, enemy.Length);
randPosition = Random.Range(0, spawnPoint.Length);
Instantiate(enemy[randEnemy], spawnPoint[randPosition].transform.position, Quaternion.identity);
Repeat();
}
}
And...
using UnityEngine;
using UnityEngine.SceneManagement;
[RequireComponent(typeof(Rigidbody2D))]
public class EnemyTypeOne : MonoBehaviour
{
public Transform target;
public float speed = 5f;
public float rotateSpeed = 200f;
private Rigidbody2D rb;
Player player;
// Time for destroy
private float StartTime;
public float EndTime;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
player = FindObjectOfType<Player>();
target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
}
private void FixedUpdate()
{
// Player harassment
Vector2 direction = (Vector2)target.position - rb.position;
direction.Normalize();
float rotateAmount = Vector3.Cross(direction, transform.right).z;
rb.angularVelocity = -rotateAmount * rotateSpeed;
rb.velocity = transform.right * speed;
// Object lifetime
StartTime = 1f * Time.deltaTime;
if (StartTime >= EndTime)
Destroy(gameObject);
}
// Actions when colliding with a player
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player")) {
Destroy(gameObject);
if (player.myHealth > 5)
player.myHealth -= 5f;
else
SceneManager.LoadScene(0);
}
}
}
CodePudding user response:
If you have some lags - use the profiler to detect the reason. It can really be caused by many different things. When you know the reason, it is much easier to find the correct solution.