응용프로그램/유니티(Unity)

Unity - 스폰 시스템 만들기

zelkova 2016. 11. 14. 22:20

<목차로 돌아가기>


  스폰시스템 만들기



출처 : Sebastian Lague


LivingEntity에서 아래의 코드를 잘 삽입~




    public event System.Action OnDeath;


        if (OnDeath != null)

        {

            OnDeath(); //죽을때마다. 이벤트가 들어감

        }



Spawner.cs

  1. using UnityEngine;
  2.  using System.Collections;

  3.  public class Spawner : MonoBehaviour {

  4.     public Wave[] waves;
  5.     public Enemy enemy;

  6.     int enemiesRemainingToSpawn;
  7.     int enemiesRemainingAlive;
  8.     float nextSpawnTime;

  9.     Wave currentWave;
  10.     int currentWaveNumber;

  11.     void Start()
  12.     {
  13.        NextWave();
  14.     }

  15.     void Update()
  16.     {
  17.     if (enemiesRemainingToSpawn > 0 && Time.time > nextSpawnTime)
  18.     {
  19.        enemiesRemainingToSpawn--;
  20.        nextSpawnTime = Time.time + currentWave.timeBetweenSpawns;

  21.        Enemy spawnedEnemy = Instantiate(enemy, Vector3.zero, 
  22.            Quaternion.identity)as Enemy;
  23.        spawnedEnemy.OnDeath += OnEnemyDeath;
  24.     }
  25.     }

  26.     void OnEnemyDeath()
  27.     {
  28.        enemiesRemainingAlive--;

  29.        if (enemiesRemainingAlive == 0)
  30.        {
  31.           NextWave();
  32.        }
  33.     }

  34.     void NextWave()
  35.     {
  36.     currentWaveNumber++;
  37.     print("Wave:" + currentWaveNumber);
  38.     if(currentWaveNumber - 1 < waves.Length)
  39.     {
  40.        currentWave = waves[currentWaveNumber - 1];
  41.        enemiesRemainingToSpawn = currentWave.enemyCount;
  42.        enemiesRemainingAlive = enemiesRemainingToSpawn;
  43.        }
  44.     }

  45.     [System.Serializable]
  46.     public class Wave
  47.     {
  48.        public int enemyCount;
  49.        public float timeBetweenSpawns;

  50.     }
  51. }



반응형