using System.Collections.Generic;
using UnityEngine;
public class CactusBase : MonoBehaviour
{
public float cactusSpeed = 1;
public Vector2 startPosition;
private void OnEnable()
{
transform.position = startPosition;
}
void Update()
{
// 왼쪽으로 이동
transform.Translate(Vector2.left * Time.deltaTime * cactusSpeed);
// 왼쪽 넘어가면 안보이게
if (transform.position.x < -6)
{
gameObject.SetActive(false);
}
}
}
변수
cactusSpeed
: 이동 속도
startPosition
: 선인장 오브젝트의 초기 위치
흐름
OnEnable()
Update()
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using Random = UnityEngine.Random;
public class CactusRespawnManager : MonoBehaviour
{
public List<GameObject> cactusPool = new List<GameObject>();
public GameObject[] objs;
public int objCnt = 1;
private void Awake()
{
for (int i = 0; i < objs.Length; i++)
{
for (int j = 0; j < objCnt; j++)
{
cactusPool.Add(CreateObj(objs[i], transform));
}
}
}
private void Start()
{
StartCoroutine(CreateCactus());
}
IEnumerator CreateCactus()
{
while (true)
{
cactusPool[SelectDeactivateCactus()].SetActive(true);
yield return new WaitForSeconds(Random.Range(1f, 3f));
}
}
int SelectDeactivateCactus()
{
List<int> deactiveList = new List<int>();
for (int i = 0; i < cactusPool.Count; i++)
{
// 비활성화된 것을 추리기
if (!cactusPool[i].activeSelf)
deactiveList.Add(i);
}
int num = 0;
if (deactiveList.Count > 0)
num = deactiveList[Random.Range(0, deactiveList.Count)];
return num;
}
GameObject CreateObj(GameObject obj, Transform parent)
{
GameObject copy = Instantiate(obj);
copy.transform.SetParent(parent);
copy.SetActive(false);
return copy;
}
}
변수
cactusPool
: 비활성화된 선인장 오브젝트들을 저장할 리스트objs
: 선인장의 종류를 나타내는 게임 오브젝트 배열objCnt
: 각 선인장 종류마다 생성될 개수흐름
Awake()
Start()
SelectDeactivateCactus()
CreateObj()