C#/수업내용

2020.05.14. 수업내용 - Scene 전환 후 스테이지 클리어하기(ObjectPool) 미완성

dev_sr 2020. 5. 15. 01:35

 

 

ObjectPool과 DataManager를 이용해서 데이터를 로드하고 오브젝트들을 생성하였고

stage Scene들은 level 클래스를 상속받아서 구현하려고 합니다.

 

ObjectPool을 이용해서 데이터를 가져오는 것,

Scene사이에서 데이터를 주고받는 것, 

몬스터를 공격하는 부분 (딜레이 동안 Idle로 있다가 다시 공격하기) 애니메이션 구현하는 것,

몬스터가 둘 이상일 때 찾는 것이

잘 안돼서 좀더 연습한 뒤에 주말에 다시 할 예정입니다

 

 

1. UIStudio 

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
 
public class UIStudio : MonoBehaviour
{
    public Button[] btn;
    public Image weaponIconImage;
    public Sprite[] arrSprite;
    public Button attackBtn;
    public Button nextBtn;
 
    private GameObject weaponAsset;
    private GameObject fxAsset;
    private WeaponData weaponData;
    private Hero hero;
 
    private int characterId;
 
    private void Awake()
    {
        DontDestroyOnLoad(this);
    }
 
    void Start()
    {
        ObjectPool.GetInstance().Load();
 
        this.characterId = 103;
        this.hero = ObjectPool.GetInstance().CreateHeroById(characterId);
 
        int lastIndex = 0;
 
        for (int i = 0; i < this.btn.Length; i++)
        {
            int capturedIndex = i;
 
            int weaponId = capturedIndex + 200;
 
            this.btn[capturedIndex].onClick.AddListener(() =>
            {
                this.weaponIconImage.gameObject.GetComponent<Image>().sprite = this.arrSprite[capturedIndex];
 
                int ObjectPoolWeaponlistCount = ObjectPool.GetInstance().GetWeaponListCount();
 
                if (ObjectPoolWeaponlistCount > 0)
                {
                    hero.ReleaseWeapon(this.weaponAsset, this.fxAsset);
                }
 
                this.weaponAsset = ObjectPool.GetInstance().GetWeaponAssetById(weaponId);
                this.weaponData = DataManager.GetInstance().GetWeaponDataById(weaponId);
                this.fxAsset = ObjectPool.GetInstance().GetFxAssetById(this.weaponData.fx_id);
 
                hero.GetWeapon(this.weaponAsset, this.weaponData);
 
                lastIndex = capturedIndex;
            });
 
        }
 
        this.attackBtn.onClick.AddListener(() =>
        {
            hero.Attack();
        });
 
        this.nextBtn.onClick.AddListener(() =>
        {
 
            SceneManager.sceneLoaded += SceneManager_sceneLoaded;
            SceneManager.LoadScene("Stage01");
        });
    }
 
    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        GameObject stage01Go = GameObject.Find("Stage01");
        Stage01 stage01 = stage01Go.GetComponent<Stage01>();
        stage01.Init(this.characterId, this.weaponData.id);
    }
}

 

 

2. ObjectPool 

 

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class ObjectPool : MonoBehaviour
{
    private static ObjectPool instance;
    private List<GameObject> weaponAssetList;
    private List<GameObject> fxAssetList;
    private List<GameObject> characterList;
 
    private List<WeaponData> weaponDataList;
 
    private void Awake()
    {
        ObjectPool.instance = this;
        this.weaponAssetList = new List<GameObject>();
        this.fxAssetList = new List<GameObject>();
        this.characterList = new List<GameObject>();
 
        this.weaponDataList = new List<WeaponData>();
 
    }
 
    public static ObjectPool GetInstance()
    {
        return ObjectPool.instance;
    }
 
    public void Load()
    {
        DataManager.GetInstance().Load();
    }
 
    public GameObject GetWeaponAssetById(int id)
    {
        WeaponData data = DataManager.GetInstance().GetWeaponDataById(id);
 
        string weaponPath = string.Format("Prefabs/{0}", data.res_name);
        GameObject weapon = Resources.Load(weaponPath) as GameObject;
        weapon.name = data.name;
        GameObject weaponGo = Instantiate(weapon) as GameObject;
        this.weaponAssetList.Add(weaponGo);
 
        weaponGo.transform.SetParent(this.transform);
        weaponGo.SetActive(false);
 
        return weaponGo;
    }
 
    public Hero CreateHeroById(int id)
    {
        CharacterData data = DataManager.GetInstance().GetCharacterDataById(id);
        string path = string.Format("Prefabs/{0}", data.res_name);
 
        GameObject heroShell = new GameObject();
        heroShell.name = "Hero";
        Hero hero = heroShell.AddComponent<Hero>();
        GameObject heroLoad = Resources.Load(path) as GameObject;
        GameObject heroGo = Instantiate(heroLoad) as GameObject;
 
        heroGo.transform.SetParent(heroShell.transform);
        heroShell.transform.SetParent(this.transform);
 
        hero.Init(heroGo, data);
 
        this.characterList.Add(heroGo);
 
        Debug.LogFormat("{0}, {1}, {2}, {3}", data.id, data.name, data.res_name, data.attack_damage);
 
 
        return hero;
    }
 
    public GameObject GetFxAssetById(int id)
    {
        FxData fxData = DataManager.GetInstance().GetEffectDataById(id);
        string fxPath = string.Format("Effect/{0}", fxData.res_name);
        GameObject fx = Resources.Load(fxPath) as GameObject;
        fx.name = fxData.name;
        GameObject fxGo = Instantiate(fx) as GameObject;
 
        fxGo.transform.position = this.transform.position;
 
        this.fxAssetList.Add(fxGo);
 
        fxGo.transform.SetParent(this.transform);
 
        fxGo.SetActive(true);
 
        return fxGo;
    }
 
    public int GetWeaponListCount()
    {
        return this.weaponAssetList.Count;
    }
 
    public Monster GetMonsterAsset()
    {
        GameObject monsterShell = new GameObject();
        monsterShell.name = "Monster";
 
        Monster monster = monsterShell.AddComponent<Monster>();
 
        GameObject monsterLoad = Resources.Load("Prefabs/StoneMonster"as GameObject;
        GameObject monsterGo = Instantiate(monsterLoad) as GameObject;
 
        monsterShell.transform.SetParent(this.transform);
        monsterGo.transform.SetParent(monsterShell.transform);
 
        return monster;
    }
 
    public GameObject GetPortalAsset()
    {
        GameObject portalShell = new GameObject();
        portalShell.name = "Portal";
 
        GameObject potalLoad = Resources.Load("Effect/Portal"as GameObject;
        GameObject potalGo = Instantiate(potalLoad) as GameObject;
 
        portalShell.transform.SetParent(this.transform);
        potalGo.transform.SetParent(portalShell.transform);
 
        return portalShell;
 
    }
 
 
    public void ReleaseAsset(GameObject weaponGo, GameObject fxGo)
    {
        weaponGo.transform.SetParent(this.transform);
        weaponGo.transform.position = this.transform.position;
        weaponGo.transform.localRotation = Quaternion.Euler(Vector3.zero);
        weaponGo.SetActive(false);
 
        fxGo.transform.SetParent(this.transform);
        fxGo.SetActive(false);
    }
 
 
}
 

 

 

3. DataManager

 

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 System.Runtime.CompilerServices;
using UnityEngine;
using Newtonsoft.Json;
using System.Linq;
 
public class DataManager
{
 
    private static DataManager Instance;
    private Dictionary<int, WeaponData> dicWeaponDatas;
    private Dictionary<int, FxData> dicFxDatas;
    private Dictionary<int, CharacterData> dicChracterDatas;
 
    private DataManager()
    {
        this.dicWeaponDatas = new Dictionary<int, WeaponData>();
        this.dicFxDatas = new Dictionary<int, FxData>();
        this.dicChracterDatas = new Dictionary<int, CharacterData>();
 
    }
 
    public static DataManager GetInstance()
    {
        if (DataManager.Instance == null)
        {
            DataManager.Instance = new DataManager();
            return DataManager.Instance;
        }
        return DataManager.Instance;
    }
 
    public void Load()
    {
        TextAsset weaponText = Resources.Load("Data/weapon_data"as TextAsset;
        string weaponJson = weaponText.text;
 
        TextAsset effectText = Resources.Load("Data/fx_data"as TextAsset;
        string effectJson = effectText.text;
 
        TextAsset characterText = Resources.Load("Data/character_data"as TextAsset;
        string characterJson = characterText.text;
 
        this.dicWeaponDatas = JsonConvert.DeserializeObject<WeaponData[]>(weaponJson).ToDictionary(x => x.id, x => x);
        this.dicFxDatas = JsonConvert.DeserializeObject<FxData[]>(effectJson).ToDictionary(x => x.id, x => x);
        this.dicChracterDatas = JsonConvert.DeserializeObject<CharacterData[]>(characterJson).ToDictionary(x => x.id, x => x);
    }
 
    public WeaponData GetWeaponDataById(int id)
    {
        return this.dicWeaponDatas[id];
    }
 
    public CharacterData GetCharacterDataById(int id)
    {
        return this.dicChracterDatas[id];
    }
 
 
    public FxData GetEffectDataById(int id)
    {
        return this.dicFxDatas[id];
    }
}

 

 

4. WeaponData

 

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 WeaponData
{
    public int id;
    public string name;
    public string res_name;
    public float attack_damage;
    public float attack_range;
    public float attack_speed;
    public int fx_id;
 
}

 

 

5. CharacterData

 

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 CharacterData
{
    public int id;
    public string name;
    public string res_name;
    public float attack_damage;
    public float move_speed;
    public float attack_range;
    public float attack_speed;
 
}

 

 

6. FxData 

 

 

1
2
3
4
5
6
7
8
9
10
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class FxData : MonoBehaviour
{
    public int id;
    public string name;
    public string res_name;
}

 

 

7. Level 

 

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
66
67
68
69
70
71
72
73
74
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
 
public class Level : MonoBehaviour
{
    public GameObject portal;
    public Monster monster;
    public List<Monster> monsterList;
 
    void Start()
    {
        this.monsterList = new List<Monster>();
    }
 
    public virtual void Init(int characterId, int weaponId)
    {
        GameObject objectPoolShell = new GameObject();
        objectPoolShell.name = "ObjectPool";
        objectPoolShell.AddComponent<ObjectPool>();
 
        Debug.Log(characterId);
        Debug.Log(weaponId);
 
        Hero hero = ObjectPool.GetInstance().CreateHeroById(characterId);
 
        var weaponAsset = ObjectPool.GetInstance().GetWeaponAssetById(weaponId);
        var weaponData = DataManager.GetInstance().GetWeaponDataById(weaponId);
        //var fxAsset = ObjectPool.GetInstance().GetFxAssetById(weaponData.fx_id);
 
        hero.GetWeapon(weaponAsset, weaponData);
 
        this.SetGoalPosition();
        this.CreateMonster();
 
        if (this.monsterList.Count > 0)
        {
            hero.MoveToMoster();
        }
 
        else if (this.monsterList.Count == 0)
        {
            hero.MoveToPortal();
        }
 
    }
    public virtual void CreateMonster()
    {
        this.monster = ObjectPool.GetInstance().GetMonsterAsset();
 
        this.monsterList.Add(this.monster);
 
        float positionX = Random.Range(1f, 5f);
        float positionZ = Random.Range(1f, 5f);
 
        Debug.LogFormat("몬스터 위치 ({0},{1})", positionX, positionZ);
 
        this.monster.transform.position = new Vector3(positionX, 0, positionZ);
 
    }
 
    public virtual void SetGoalPosition()
    {
        this.portal = ObjectPool.GetInstance().GetPortalAsset();
 
        float positionX = Random.Range(1f, 5f);
        float positionZ = Random.Range(1f, 5f);
 
        portal.transform.position = new Vector3(positionX, 0, positionZ);
        Debug.LogFormat("포탈 위치 ({0},{1})", positionX, positionZ);
 
    }
}

 

 

8. Stage01 

 

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
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.Events;
 
public class Stage01 : Level
{
 
    private void Awake()
    {
        Debug.Log("stage01");
    }
 
    public override void Init(int characterId, int weaponId)
    {
        base.Init(characterId, weaponId);
    }
 
    public override void CreateMonster()
    {
        base.CreateMonster();
    }
 
}

 

 

9. Hero 

 

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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Hero : MonoBehaviour
{
    private Animation anim;
    private AnimationState animstate;
    private bool isAttack;
    private float elapsedTimeCompareAttackEnd;
    private GameObject model;
    private Transform dummyRHand;
    private bool isMovePortal;
    private GameObject portal;
    private bool isMoveMonster;
    private GameObject monsterGo;
    private Monster monster;
    private float impactTime;
    private float delayTime;
    private bool isAttackMonster;
 
    public float attack_damage;
    public float attack_range;
    public float attack_speed;
    public float move_speed;
 
 
    void Start()
    {
        Debug.Log("hi");
 
    }
 
    public void Init(GameObject model, CharacterData data)
    {
        this.model = model;
 
        this.attack_damage = data.attack_damage;
        this.attack_range = data.attack_range;
        this.attack_speed = data.attack_speed;
        this.move_speed = data.move_speed;
 
        this.anim = model.GetComponent<Animation>();
        this.animstate = this.anim["attack_sword_01"];
        float animAttackFrameRate = this.animstate.clip.frameRate;
        float totalFrame = this.animstate.length * animAttackFrameRate;
        float impactFrame = 8f;
 
        this.impactTime = impactFrame * this.animstate.length / totalFrame;
 
    }
    public void GetWeapon(GameObject weaponGo, WeaponData weaponData)
    {
        this.attack_damage = weaponData.attack_damage;
        this.attack_range = weaponData.attack_range;
        this.attack_speed = weaponData.attack_speed;
 
        this.dummyRHand = this.model.GetComponent<HeroModel>().dummyRHand;
        weaponGo.transform.SetParent(dummyRHand, false);
 
        if (weaponGo.transform.rotation.y != 180)
        {
            weaponGo.transform.Rotate(new Vector3(01800));
        }
        weaponGo.transform.localScale = new Vector3(0.2f, 0.2f, 0.2f);
        weaponGo.SetActive(true);
 
    }
 
    public void ReleaseWeapon(GameObject weaponGo, GameObject fxGo)
    {
        ObjectPool.GetInstance().ReleaseAsset(weaponGo, fxGo);
    }
 
 
    public void Attack()
    {
        this.anim.Play("attack_sword_01");
        this.isAttack = true;
    }
 
    private void Stop()
    {
        this.anim.Play("idle@loop");
        this.isAttack = false;
        this.isMovePortal = false;
    }
 
    public void Move()
    {
        this.anim.Play("run@loop");
    }
 
    public void MoveToMoster()
    {
        Debug.Log("몬스터에게 이동");
        this.monsterGo = GameObject.Find("Monster");
        this.monster = this.monsterGo.GetComponent<Monster>();
        this.Move();
        this.isMoveMonster = true;
    }
 
    public void MoveToPortal()
    {
        Debug.Log("포탈로 이동");
        this.portal = GameObject.Find("Portal");
        this.transform.LookAt(this.portal.transform);
        this.Move();
        this.isMovePortal = true;
    }
 
    public void MonsterAttack()
    {
        this.Attack();
 
    }
 
    void Update()
    {
        if (this.isAttack)
        {
            this.elapsedTimeCompareAttackEnd += Time.deltaTime;
 
            if (this.elapsedTimeCompareAttackEnd >= this.animstate.length)
            {
                Debug.LogFormat("공격 경과된 시간 {0}", elapsedTimeCompareAttackEnd);
                Debug.LogFormat("공격 시간 {0}"this.animstate.length);
                this.elapsedTimeCompareAttackEnd = 0;
                this.Stop();
                
            }
        }
 
        if (this.isMovePortal)
        {
            float distance = Vector3.Distance(this.portal.transform.position, this.transform.position);
            //Vector3 dir = this.portal.transform.position - this.transform.position;
            this.transform.Translate(Time.deltaTime * this.move_speed * Vector3.forward);
 
            if (distance < 0.02f)
            {
                this.Stop();
            }
        }
 
        if (this.isMoveMonster)
        {
            float distance = Vector3.Distance(this.monsterGo.transform.position, this.transform.position);
            Vector3 dir = this.monsterGo.transform.position - this.transform.position;
            this.transform.Translate(Time.deltaTime * this.move_speed * dir.normalized);
 
            if (distance < 0.02f)
            {
                MonsterAttack();
                this.isMoveMonster = false;
            }
        }
 
    }
}
 

 

 

10. Monseter

 

 

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
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Monster : MonoBehaviour
{
    public float hp;
    public Animation anim;
 
    void Start()
    {
        Debug.Log("Monster: Hi");
        this.hp = 5;
        GameObject monsterGo = GameObject.Find("StoneMonster(Clone)");
 
        this.anim = monsterGo.GetComponent<Animation>();
 
 
    }
 
    public void Damage()
    {
        this.anim.Play("Anim_Damage");
    }
 
    public void Die()
    {
        this.anim.Play("Anim_Death");
    }
}