유니티 오브젝트 자동 spawn하는 방법

728x90

유니티 오브젝트 자동 스폰 방법

오브젝트가 중력이 적용되어 지면에 닿으면 튀게 하는 효과 : 마우스 왼쪽 클릭 - Physical Material - bounciness(1)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawner : MonoBehaviour
{
    public GameObject BallPrefab;
    public float minDelay = 0.1f;
    public float maxDelay = 1f;
    public float DestroyDelay = 5f;
    private IEnumerator coroutine;

    void Start()
    {
        coroutine = SpawnFruits(DestroyDelay);
        StartCoroutine(coroutine);
    }
    /*void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            float SpawnX = Random.Range(-3f, 3f);
            Vector3 SpawnPoint = new Vector3(SpawnX, 3, 0);
            GameObject SpawnedBall = Instantiate(BallPrefab, SpawnPoint, Quaternion.identity);
            Destroy(SpawnedBall, DestroyDelay);
        }
    }*/
    IEnumerator SpawnFruits(float DDelay)
    {
        while(true)
        {
            float delay = Random.Range(minDelay, maxDelay);
            yield return new WaitForSeconds(delay);

            float SpawnX = Random.Range(-3f, 3f);
            Vector3 SpawnPoint = new Vector3(SpawnX, 1, 0);

            GameObject Spawnedball = Instantiate(BallPrefab, SpawnPoint, Quaternion.identity);
            Destroy(Spawnedball, DDelay);
        }
    }
}

또는

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawner2 : MonoBehaviour
{
    public GameObject BallPrefab;
    public float DestroyDelay = 5f;
    public float minDelay = 0.1f;
    public float maxDelay = 1f;

    void Start()
    {
        StartCoroutine(SpawnFruits());
    }
    IEnumerator SpawnFruits()
    {
        while (true)
        {
            float delay = Random.Range(minDelay, maxDelay);
            yield return new WaitForSeconds(delay);
            Bfunc();
        }
    }
    void Bfunc()
    {
        float SpawnX = Random.Range(-3f, 3f);
        Vector3 SpawnPoint = new Vector3(SpawnX, 3, 0);
        GameObject SpawnedBall = Instantiate(BallPrefab, SpawnPoint, Quaternion.identity);
        Destroy(SpawnedBall, DestroyDelay);
    }
}
728x90