Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections.Generic;
- public struct EnemyData
- {
- public float health;
- public float speed;
- }
- public class EnemySpawner : MonoBehaviour
- {
- public EnemyHandler enemyHandler;
- public GameObject enemyPrefab;
- void Spawn()
- {
- var go = Instantiate(enemyPrefab);
- enemyHandler.RegisterEnemy(go.transform, 100f, 3f);
- }
- }
- public class EnemyHandler : MonoBehaviour
- {
- public Transform target;
- List<Transform> transforms = new();
- List<EnemyData> enemies = new();
- public void RegisterEnemy(Transform t, float health, float speed)
- {
- transforms.Add(t);
- enemies.Add(new EnemyData
- {
- health = health,
- speed = speed
- });
- }
- void Update()
- {
- Vector3 targetPos = target.position;
- for (int i = enemies.Count - 1; i >= 0; i--)
- {
- if (enemies[i].health <= 0f)
- {
- Destroy(transforms[i].gameObject);
- transforms.RemoveAt(i);
- enemies.RemoveAt(i);
- continue;
- }
- Vector3 dir = (targetPos - transforms[i].position).normalized;
- transforms[i].position += dir * enemies[i].speed * Time.deltaTime;
- }
- }
- public void Damage(int index, float dmg)
- {
- EnemyData e = enemies[index];
- e.health -= dmg;
- enemies[index] = e;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment