在一个统一中创造超过三个敌人后FPS下降



游戏的精髓:你需要奔跑并躲避每隔几秒出现并在十秒后消失的敌人。问题是,如果有超过三个这样的敌人,游戏就会突然开始变慢。
也许有一些方法可以优化,或者代码中有错误。
附注当你以单位开始游戏时,FPS会下降。我没有试着去编译。
下面是生成敌人和敌人本身的代码:

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();
}
}

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);                     
}
}
}

如果有一些滞后-使用分析器来检测原因。它可能是由很多不同的原因引起的。当你知道原因时,就更容易找到正确的解决办法。

最新更新