스토리지

[4.28] 캐릭터를 동적으로 가져오기 본문

Unity/유니티 기본

[4.28] 캐릭터를 동적으로 가져오기

ljw4104 2021. 4. 28. 16:21

캐릭터가 프리팹으로 생성되어져 있다.

동적으로 생성되는 캐릭터는 구조가

껍데기

  ㄴ 모델

로 대부분 이루어져있다. 애니메이터와 같은 것들은 모델에서 처리해주고 나머지는 본체 껍데기에서 처리해주면 된다.

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

public class InGame : MonoBehaviour
{
    private void Start()
    {
        this.Init(0);
    }

    public void Init(int id)
    {
        GameObject go = new GameObject();
        go.name = "Hero";

        var prefab = Resources.Load<GameObject>("birdOrc");
        var model = Instantiate(prefab);
        model.transform.SetParent(go.transform);

        go.AddComponent<Hero>();
        var box = go.AddComponent<BoxCollider2D>();
        var rigid = go.AddComponent<Rigidbody2D>();

        rigid.constraints = RigidbodyConstraints2D.FreezeRotation;
        rigid.gravityScale = 0;
        box.offset = new Vector2(-0.08304083f, 0.8341819f);
        box.size = new Vector2(1.422753f, 1.792661f);
        model.transform.localScale = new Vector2(0.005f, 0.005f);
    }
}

원래는 Box콜라이더의 사이즈와 프리팹의 이름은 엑셀에서 데이터로 가져오는 것이 맞다.

 

=================================================================

데이터 연동

public class CharacterData
{
    public int id;
    public string prefab_name;
    public float boxOffsetX;
    public float boxOffsetY;
    public float boxSizeX;
    public float boxSizeY;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InGame : MonoBehaviour
{
    public bool isAvailable;

    private static InGame instance;
    public static InGame Instance
    {
        get
        {
            if (instance == null)
            {
                instance = FindObjectOfType<InGame>();
            }
            return instance;
        }
    }
    private InGame() { }

    public void Init(CharacterData data)
    {
        GameObject go = new GameObject();
        go.name = "Hero";

        var prefab = Resources.Load<GameObject>(data.prefab_name);
        var model = Instantiate(prefab);
        model.transform.SetParent(go.transform);

        go.AddComponent<Hero>();
        var box = go.AddComponent<BoxCollider2D>();
        var rigid = go.AddComponent<Rigidbody2D>();

        rigid.constraints = RigidbodyConstraints2D.FreezeRotation;
        rigid.gravityScale = 0;
        box.offset = new Vector2(data.boxOffsetX, data.boxOffsetY);
        box.size = new Vector2(data.boxSizeX, data.boxSizeY);
        model.transform.localScale = new Vector2(0.005f, 0.005f);

        this.isAvailable = true;
    }
}
Comments