Unity/수업내용

2020-05-21 수업내용 캐릭터선택 및 상태화면

J월드 2020. 5. 22. 09:18

과제 : 캐릭터 선택창에서 영웅 선택 버튼을 누르면, 해당하는 영웅이 InGame씬에서 생성되게 만들기

 

결과 : 캐릭터에게 기능이 붙을 수도 있으니, Hero스크립트를 하나만들어 영웅을 동적생성하면서 스크립트를 컴포넌트로 붙여줌.

그리고 인게임의 자식으로 붙여주었다.

 

CharacterData.class

더보기
1
2
3
4
5
6
7
8
9
10
11
12
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class CharacterData
{
    public int id;
    public int hp;
    public string res_name;
    public string thumb_name;
}
 
 
 

DataManager.class

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.Linq;
 
public class DataManager
{
    static DataManager instance;
    private Dictionary<int, CharacterData> dicCharacterData;
 
    private DataManager()
    {
        this.dicCharacterData = new Dictionary<int, CharacterData>();
    }
 
    public static DataManager Getinstance()
    {
        if (DataManager.instance == null)
            instance = new DataManager();
 
        return DataManager.instance;
    }
 
    public void LoadData()
    {
        string json = Resources.Load<TextAsset>("Data/character_data").text;
        this.dicCharacterData = JsonConvert.DeserializeObject<CharacterData[]>(json).ToDictionary(x => x.id, x => x);
 
        //test
        //foreach (var pair in this.dicCharacterData)
        //{
        //    Debug.LogFormat("{0},{1}", pair.Value.id, pair.Value.res_name);
        //}  
    }
 
    public CharacterData GetCharacterDatas(int id)
    {
        return this.dicCharacterData[id];
    }
 
    public List<CharacterData> GetdicCharacterDatas()
    {
        return this.dicCharacterData.Values.ToList();
    }
}
 
 
 

Lobby.class

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Lobby : MonoBehaviour
{
    public UILobby uiLobby;
 
    private void Start()
    {
        DataManager.Getinstance().LoadData();
        DataManager.Getinstance().GetdicCharacterDatas();
        this.uiLobby.Init();       
    }
}
 
 
 

UILobby.class

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 
public class UILobby : MonoBehaviour
{
    public Transform contentsTrans; //
    private GameObject listItemPrefab; //프리팹 로드위해
 
    public void Init()
    {
 
        this.listItemPrefab = Resources.Load<GameObject>("Prefabs/UI/UIListItem_Hero");
        var characterDatas = DataManager.Getinstance().GetdicCharacterDatas();
 
        foreach (var data in characterDatas)
        {
            var listItemGo = Instantiate<GameObject>(this.listItemPrefab);
            var listItem = listItemGo.GetComponent<UIListItem_Hero>();
 
            //ui prefab load
            var uiModelPrefabName = string.Format("Prefabs/UI/ui_{0}", data.res_name);
            var uiModelPrefab = Resources.Load<GameObject>(uiModelPrefabName);
 
            //ui 모델 Instantiate
            var uiModel = Instantiate<GameObject>(uiModelPrefab);
 
            //listItem 초기화
            listItem.Init(data.id,data.res_name, uiModel);
 
            //버튼 이벤트 등록
            listItem.btn.onClick.AddListener(() =>
            {
                Debug.LogFormat("selected character ID: {0}", data.id);
 
                SceneManager.LoadScene("InGame");
 
                SceneManager.sceneLoaded += (Scene arg0, LoadSceneMode arg1) => {
                    InGame inGame = GameObject.FindObjectOfType<InGame>();
                    inGame.Init(data.id);
                    Debug.LogFormat("data.id :: {0}", data.id);
                };
 
            });
 
            //parent 설정
            //false때문에 안보였다.... 에러날시에는 일지정지해놓고 오브젝트가 어느곳에 생기는지 확인 후 검증
            listItem.transform.SetParent(this.contentsTrans, false); 
        }
    }
 
    void Start()
    {
        
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
 
 

InGame.class

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class InGame : MonoBehaviour
{
    public UIInGame uIInGame;
    private int selectedHeroId;
    private CharacterData selectedCharacterData;
 
    private GameObject prefab;
    private Hero hero;
 
    public void Start()
    {
        DataManager.Getinstance().LoadData();
    }
 
    public void Init(int selectedHeroId)
    {
        this.selectedHeroId = selectedHeroId;
        this.selectedCharacterData = DataManager.Getinstance().GetCharacterDatas(this.selectedHeroId);
 
        //이름 (ch_01_01)
        //썸네일 (thumb_ch_01_01)
        //체력 게이지(current hp / max hp)
        //경험치 게이지(current exp, target exp)
        //레벨(1)
 
        this.uIInGame.Init(
            new UIInGameParam
            {
                Name = selectedCharacterData.res_name,
                ThumbName = selectedCharacterData.thumb_name,
                CurrentHp = selectedCharacterData.hp,
                MaxHp = selectedCharacterData.hp,
                CurrentExp = 50,
                TargetExp = 100,
                Level = 1,
            });
 
        this.hero = this.CreateHero(selectedHeroId);
 
        this.hero.gameObject.transform.SetParent(this.gameObject.transform);
 
        this.hero.Init(this.selectedCharacterData, Vector3.zero);
 
    }
 
 
    public Hero CreateHero(int selectedHeroId)
    {
        this.prefab = Resources.Load<GameObject>(string.Format("Prefabs/{0}"this.selectedCharacterData.res_name));
 
        //인스턴스화
        GameObject shellHero = new GameObject();
        shellHero.name = "Hero";
 
        Instantiate<GameObject>(prefab).transform.SetParent(shellHero.transform);
        var hero = shellHero.AddComponent<Hero>();
 
        return hero;
    }
}
 
 
 

UIInGame.class

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
 
public class UIInGame : MonoBehaviour
{
    public UIHeroState uIHeroState;
    public SpriteAtlas uiInGameAtlas;
 
    public Sprite[] arrThumbIcons; //테스트
 
    public void Init(UIInGameParam param)
    {
        Debug.LogFormat("{0},{1},{2},{3},{4},{5},{6}"
            param.Name, param.ThumbName, param.CurrentHp,
            param.MaxHp, param.CurrentExp, param.TargetExp, param.Level);
 
        //이름
        //썸네일 변경
        //체력 게이지
        //경험치 게이지
 
        Sprite spThumb = null;
 
        //foreach (var thumb in this.arrThumbIcons)
        //{
        //    if (thumb.name == param.ThumbName) {
        //        spThumb = thumb;
        //        break;
        //    }
        //}
 
        //위의 코드를 한줄로..
        spThumb = this.uiInGameAtlas.GetSprite(param.ThumbName);
 
        this.uIHeroState.Init(spThumb, param.CurrentHp,
            param.MaxHp, param.CurrentExp, param.TargetExp, param.Level, param.Name);
 
    }
}
 
 
 

UIListItem_Hero.class

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class UIListItem_Hero : MonoBehaviour
{
    public Text txtId;
    public Text txtName;
    public Button btn;
 
    private GameObject uiModel;
 
    public void Init(int id, string name, GameObject uiModel)
    {
        this.txtId.text = id.ToString();
        this.txtName.text = name;
        this.uiModel = uiModel;
        this.uiModel.transform.SetParent(this.transform, false);
    }
}
 
 
 

UIHeroState.class

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class UIHeroState : MonoBehaviour
{
    public Image imgThumb;
    public Slider sliderHp;
    public Slider sliderExp;
    public Text txtProgress;
    public Text txtLevel;
    public Text txtName;
 
    public void Init(Sprite spThumb, int currentHp, int maxHp, int currentExp, int targetExp, int level, string heroname)
    {
        this.imgThumb.sprite = spThumb;
 
        //1 : x = maxhp : currentHp 
        //x * maxhp = currentHp
        //x = currentHp / maxHp
 
        this.sliderHp.value = (float)currentHp / (float)maxHp;
        this.sliderExp.value = (float)currentExp / (float)targetExp;
        var strProgress = string.Format("{0}/{1}", currentHp, maxHp);
        this.txtProgress.text = strProgress;
        this.txtName.text = heroname;
        this.txtLevel.text = level.ToString();
    }
}
 
 

UIInGameParam.class

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class UIInGameParam 
{
    public string Name;
    public string ThumbName;
    public int CurrentHp;
    public int MaxHp;
    public int CurrentExp;
    public int TargetExp;
    public int Level;
}
 
 
 

Hero.class

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Hero : MonoBehaviour
{
    public CharacterData data;
 
    void Start()
    {
        
    }
 
    public void Init(CharacterData data, Vector3 initPos)
    {
        this.data = data;
        //test
        //Debug.LogFormat("{0},{1},{2},{3}", this.data.id, this.data.res_name, this.data.hp, this.data.thumb_name);
 
        this.gameObject.transform.position = initPos;
        this.gameObject.transform.rotation = Quaternion.Euler(01800);
 
    }
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
 
 

 

 

실행화면