[학원 Unity]/[게임 클라이언트 프로그래밍]
게임오브젝트로 부터 컴포넌트를 가져올수 있는 방법
롤링페이퍼
2024. 8. 19. 14:00
인벤토리 만들어보기
1.
Hierarchy에서 GamaObject를 생성
Project에 Item에 관한 내용이 들어있는 C# Script를 생성해서
아래 내용을 작성
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Item : MonoBehaviour
{
// 멤버 변수 정의
public int damage;
public float attackSpeed;
public bool isBroken;
public string itemName;
private void Awake()
{
Debug.Log("Awake메서드 호출됨.");
// 공격력 : 0
Debug.Log($"공격력 : {this.damage}");
Debug.LogFormat("아이템명 : {0}", this.itemName);
Debug.LogFormat("공격력 : {0}", this.damage);
Debug.LogFormat("공격속도 : {0}", this.attackSpeed);
Debug.LogFormat("파괴여부 : {0}", this.isBroken);
}
// Start is called before the first frame update
void Start()
{
Debug.Log("Start 메서드 호출됨");
}
// Update is called once per frame
void Update()
{
//Debug.Log("Update");
}
}
2. Item 게임오브젝트에 item 스크립트를 컴포넌트하면 inspector에서 내용을 볼수있다
참고로 각 값들은 public으로 공개를 했기에 외부에서 확인할수 있고 수정을 할수 있다.
3.
이후 인벤토리 관련 게임오브젝트를 만들고 인벤토리 관련 c# 스크립트를 만들어 컴포넌트 시킨다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
//public GameObject itemGo; // Go : GameObject
public List<GameObject> itemGos; //<GameObject>게임오브젝트를 타입을 만들어 게임오브젝트 타입을 집어 넣을수 있게 한다
private void Awake()
{
//Debug.Log(itemGo);
//Item item = itemGo.GetComponent<Item>();
//Debug.Log($"{item.itemName}");
//Debug.Log($"{item.attackSpeed}");
//Debug.Log($"{item.damage}");
//Debug.Log($"{item.isBroken}");
//itemGos를 순회 하면서 아이템들의 이름을 출력하고 싶다.
// 1. 게임오브젝트를 만들기
// 2. 아이템 컴포넌트를 부착하기
// 3. 비어있는 이름에 부착하기
// 4. 인벤토리에 추가(어싸인)하기
// 5. 순회하면서 포문 사용
// 장검
// 단검
// 활
Debug.Log($"<color=Yellow>{itemGos.Count}</color>");
for(int i = 0; i < this.itemGos.Count;i++)
{
// 리스트의 인덱스에 해당하는 요소의 값 출력
//Debug.Log($"{1} -> {this.itemGos[i]}");
GameObject itemGo = this.itemGos[i];
Item item = itemGo.GetComponent<Item>();
Debug.Log($"{item.itemName}");
}
}
}
public List<GameObject> itemGos;
으로 <GameObject>타입으로도 사용할수 있으며
해당 배열을 만들시 외부에선
해당 배열안의 인스턴스 값에 게임오브젝트를 넣을수 있는 공간을 만들수 있다.
4.
이대 해당 인덱스에 게임오브젝트 를 넣은후 실행을 해보면
콘솔을 확인했을때 포문으로 돌려 출력하는 것을 확인할수 있을 것 이다.
참고
itemGo 변수는 LIst<GameObject> itemGos로 GameObject타입의 ItemGos 변수로 생성했으며
itemGo.GetComponent<Item>() 값은 itemGo안에 있는 인스턴스 타입이 Item 이므로 Item item 으로 생성해 값을 집어 넣는다.