본문 바로가기
Project/[Unity] 지진 시뮬레이션

[Unity] 지진 시뮬레이션 10 - 오브젝트 복제

by ruki 2024. 4. 2.

플레이어를 코드로 복제하여 리스로 쉽게 값에 접근할 수 있도록 할 것이다.


1. 플레이어 생성

플레이어를 복제하고, 코드에서 리스트로 관리할 것이다.

gameManager코드를 생성한다.

 

그리고 함수를 추가한다.

public int Count; 
public GameObject BaseObject; 
public GameObject ParentObject; 
public List<GameObject> ObjectList = new List<GameObject>(); 

void SetObject()
{
    for (int i = 0; i < Count; i++) 
    {
        ObjectList.Add(Instantiate(BaseObject, ParentObject.transform));
        ObjectList[i].SetActive(true);
    } 
}

대상 오브젝트를 특정 오브젝트 아래로 일정 개수만큼 복사하는 함수이다.

 

gameManager 오브젝트를 생성하여 코드를 위치시킨다.

그리고 값을 할당하면

잘 작동한다.


2. 플레이어 탈락

플레이어가 탈락할 경우 비활성화되도록 만들 것이다.

 

먼저 임시로 만들어운 BOOM!!! 을 비활성화 하도록 수정한다.

if(damage > 1) print("BOOM!!!");
if(damage > 1) gameObject.SetActive(false);

 

연약한 플레이어는 벽의 흔들림에도 상처를 입기 때문에 벽에 닿은 경우에도 탈락하도록 만든다.

태그를 추가하여 벽에 할당해 준다.

코드를 추가해 준다.

else if(other.transform.parent.gameObject.tag == "wall") 
gameObject.SetActive(false);

wall 태그는 상위 오브젝트 하나만 가지고 있기 때문에 접촉한 오브젝트의 부모 오브젝트로 접근할 수 있도록 하였다.

 

잘 작동한다.

 

전체 코드

gameManager

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

public class gameManager : MonoBehaviour
{
    public static gameManager instance;
    
    private void Awake() 
    {
        instance = this;
    } 
    public int Count; 
    public GameObject BaseObject; 
    public GameObject ParentObject; 
    public List<GameObject> ObjectList = new List<GameObject>(); 

    void Start()
    {
        SetObject();
    }

    void SetObject()
    {
        for (int i = 0; i < Count; i++) 
        {
            ObjectList.Add(Instantiate(BaseObject, ParentObject.transform));
            ObjectList[i].SetActive(true);
        } 
    }
}

 

playerDamage

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

public class playerDamage : MonoBehaviour
{
    void OnTriggerEnter(Collider other)
    {
        if(other.tag == "box" || other.tag == "book") 
        {
            float damage = other.GetComponent<Rigidbody>().velocity.magnitude;
            if(damage > 1) gameObject.SetActive(false);
        }
        else if(other.transform.parent.gameObject.tag == "wall") gameObject.SetActive(false);
    }   
}

오브젝트의 복사와 제거가 유동적인 경우에는 Instantiate()와 Destroy()를 사용하기보다 Pooling을 통해 관리하면 데이터를 절약할 수 있다.