유니티 기초

몬스터를 죽이면 리스트에서 없애고 임의 위치에 포탈생성

다모아 2023. 8. 10. 11:54

https://dpdwm.tistory.com/19

[랜덤]

 

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

namespace Test3
{
    //씬의 모든 객체들을 관리
    public class Test_CreatePortalMain : MonoBehaviour
    {
        [SerializeField]
        private MonsterGenerator monsterGenerator;

        [SerializeField]
        private GameObject portal;

        private List<MonsterController> monsterList;
        // Start is called before the first frame update
        void Start()
        {
            //컬렉션 사용전 반드시 초기화
            this.monsterList = new List<MonsterController>();
            MonsterController turtle = this.monsterGenerator.Generate(GameEnums.eMonsterType.Turtle, new Vector3(-3, 0, 0));
            MonsterController slime = this.monsterGenerator.Generate(GameEnums.eMonsterType.Slime, new Vector3(0, 0, 3));
            //만들어진 개체들을 그룹화 관리
            //배열, 컬렉션
            //동적 배열
            this.monsterList.Add(turtle);
            this.monsterList.Add(slime);
            Debug.LogFormat("this.monsterList.Count: {0}", this.monsterList.Count);
            //리스트의 요소를 출력
            foreach (MonsterController monster in this.monsterList)
            {
                Debug.LogFormat("monster: {0}", monster);
            }
        }

        // Update is called once per frame
        void Update()
        {
            //Test
            //Ray연습할겸 클릭해서 선택 몬스터를 제거하자
            if(Input.GetMouseButtonDown(0))
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                Debug.DrawRay(ray.origin, ray.direction * 100f, Color.red, 2f);

                RaycastHit hit;

                if(Physics.Raycast(ray, out hit, 100f))
                {
                    if(hit.collider.tag == "Monster")
                    {
                        int i = 0;
                        Debug.LogFormat("hit.collider.tag: {0}", hit.collider.tag);
                        Destroy(hit.collider.gameObject);
                        this.monsterList.Remove(monsterList[i++]);
                        Debug.LogFormat("남은 몬스터의 수: {0}", monsterList.Count);
                        if(monsterList.Count == 0)
                        {
                            float randX = Random.Range(-3f, 3f);
                            float randZ = Random.Range(-3f, 3f);
                            this.portal.transform.position = new Vector3(randX, 0f, randZ);
                            this.portal.SetActive(true);
                        }
                    }
                }
            }
        }
    }
}