팀 프로젝트
아이템 기능을 맡은 팀원이 도와달라고 해서 그 부분을 도와줬다. 아이템을 플레이어에게 적용하는 부분과 몬스터를 죽였을 때 아이템이 확률적으로 드랍되는 시스템을 ScriptableObject를 사용하여 만들었다.
Unity : ScriptableObject
아래가 아이템 드랍에 관련되 ScriptableObject이다.
[CreateAssetMenu]는 커스텀 에셋을 생성하는데 도움을 주는 속성이다.
Items라는 Serializable 필드를 생성하여서 Unity Inspector에서 쉽게 아이템과 드랍확률을 설정할 수 있게 하였고
모든 아이템의 가중치를 합해서 0 ~ 가중치의 합까지 랜덤한 값을 뽑아 확률에 맞게 아이템을 주어진 위치에 생성하는 기능을 가지고 있다.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[CreateAssetMenu]
public class ItemDropTable : ScriptableObject
{
[System.Serializable]
public class Items
{
public GameObject item;
public int weight;
}
public List<Items> items = new List<Items>();
protected GameObject PickItem()
{
int sum = 0;
foreach (var item in items)
{
sum += item.weight;
}
var rnd = Random.Range(0, sum);
for (int i = 0; i < items.Count; i++)
{
var item = items[i];
if (item.weight > rnd) return items[i].item;
else rnd -= item.weight;
}
return null;
}
public void ItemDrop(Vector3 pos, int exp)
{
var item = PickItem();
if (item == null) return;
ExpCoin coin = item.GetComponent<ExpCoin>();
if (coin != null)
coin.SetExp(exp);
Instantiate(item, pos, Quaternion.identity);
}
}