Unity/수업내용

2020-05-07 캐릭터 인스턴스화

J월드 2020. 5. 7. 18:17

소스코드를 깔끔하게 코딩하여, 캐릭터 실체화 하는것을 배웠다.

------------------------------------------------------------------------------------------------------------------

App.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
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using TMPro;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.UI;
 
public class App : MonoBehaviour
{
    public GameObject[] arrHeroModels;
    public GameObject[] arrMonsterModels;
 
    public Hero hero;
    public Monster monster;
 
    public string heroModelName;
    public string monsterModelName;
 
    // Start is called before the first frame update
    void Start()
    {
        var heroModel = this.CreateHero(heroModelName);
        this.hero.Init(heroModel);
 
        var monsterModel = this.CreateMonster(monsterModelName);
        this.monster.Init(monsterModel);
    }
    public GameObject CreateHero(string modelName)
    {
        GameObject foundmodel = null;
 
        foreach (var model in this.arrHeroModels)
        {
            if (model.name == modelName)
            {
                foundmodel = model;
                break;
            }
        }
        var newModel = UnityEngine.Object.Instantiate(foundmodel);
        return newModel;
    }
 
    public GameObject CreateMonster(string monsterName)
    {
        GameObject foundmodel = null;
        foreach (var model in this.arrMonsterModels)
        {
            if (model.name == monsterName)
            {
                foundmodel = model;
                break;
            }
        }
        var newModel = UnityEngine.Object.Instantiate(foundmodel);
        return newModel;
    
    }
}
 
 
 
 

Hero.Class

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Hero : MonoBehaviour
{
    private GameObject hero;
    private Hero()
    {
 
    }
    public void Init(GameObject hero)
    {
        this.hero = hero;
        this.hero.transform.SetParent(this.gameObject.transform);
    }
}
 
 
 

Monster.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 Monster : MonoBehaviour
{
    private GameObject monster;
 
    public void Init(GameObject monster)
    {
        this.monster = monster;
        this.monster.transform.SetParent(this.gameObject.transform);
    }
}