negitamago
2/5/2019 - 6:32 AM

DI 可能な状態でオブジェクトを繰り返し生成する

DI 可能な状態でオブジェクトを繰り返し生成する

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Zenject;    // Zenject https://github.com/svermeulen/Zenject

/// <summary>
/// DI 可能な状態でオブジェクトを繰り返し生成する
/// </summary>
public class ItemSpawner : MonoBehaviour
{
    [SerializeField] GameObject itemPrefab = null;
    [SerializeField] float delay = default;
    [SerializeField] float span = default;
    [SerializeField] int kaisuu = default;
    [SerializeField] Transform itemsParent = null;

    [Inject] DiContainer container = null;

    /// <summary>
    /// 生成するpositionの範囲
    /// </summary>
    [System.Serializable]
    public class SpawnBoundary
    {
        public float xMin, xMax, yMin, yMax, zMin, zMax;
    }
    [SerializeField] SpawnBoundary boundary = null;

    private void Start () => StartCoroutine ( Spawn () );

    private IEnumerator Spawn ()
    {
        yield return new WaitForSeconds ( delay );

        int count = 0;
        while ( count < kaisuu )
        {
            var spawnPosition = new Vector3(
                Random.Range(boundary.xMin, boundary.xMax),
                Random.Range(boundary.yMin, boundary.yMax),
                Random.Range(boundary.zMin, boundary.zMax));

            container.InstantiatePrefab (
                itemPrefab, spawnPosition, Quaternion.identity,
                itemsParent );

            count++;
            yield return new WaitForSeconds ( span );
        }

        Debug.Log ( "Spawn Finished" );
    }
}