https://gall.dcinside.com/m/game_dev/102197

아까 썼던 글 좀 더 상세하게 적어봄



Monster.cs

public abstract class Monster : MonoBehaviour
{
    public string key;
    public int hp;
    public int dmg;


    public abstract void Initialise();

}


Monster라는 추상 클래스 만듦

key, hp, dmg라는 변수를 가집니다





Lion.cs


public class Lion : Monster
{
    public override void Initialise()

{

        string[] _key = {"lion01", "lion02" };
        int r = Random.Range(0, _key.Length);

        key = key[r];
        hp = 25;
        dmg = 10;
    }
}


Monster.cs를 받는 Lion 클래스.

테스트를 위해 key 값은 lion01과 lion02 중에 랜덤하게 정해집니다.

이후 오브젝트 프리팹을 만들고, Lion.cs를 붙입니다. (라이온 프리팹)



Generator.cs


public class Generator : MonoBehaviour
{
    public Monster animal;
    public List<Monster> animalList = new List<Monster>();

    void Update()
    {

        for (int i = 0; i < 5; i++)
        {
            animalList.Add(animal);
            animalList.ElementAt(i).Initialise();
         }
    }
}


이렇게 작성한 후, 인스펙터 창에서 라이온 프리팹을 할당합니다.

게임을 실행하면 인스펙터 창에서 Generator.cs animalList의 항목들을 살펴봐도 Initialise()가 실행된 흔적이 보이질 않습니다.


근데 막상 for문에서 Debug.Log(animalList.ElementAt(i).key) 이렇게 써두면 로그에선 제대로 할당된 걸로 나와요