C#/수업내용

2020.05.07. 수업내용 - 지정된 위치에 몬스터와 캐릭터 생성시키기

dev_sr 2020. 5. 8. 09:35

 

*Hierarchy에서 카메라 클릭후 ctrl+shift+F를 누르면 Scene에서 맞춘 구도로 미리보기를 맞출 수 있음

 

1. App

 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class App : MonoBehaviour
{
    public Hero hero;
    public Monster monster;
    public GameObject[] arrHero;
    public string HeroName;
    public Button heroBtn;
    public Button monsterBtn;
    public GameObject getMonster;
 
 
    // Start is called before the first frame update
    void Start()
    {
        this.heroBtn.onClick.AddListener(() => {
            GameObject newhero = this.CreateNewHero(this.HeroName);
            this.hero.Init(newhero);
        });
 
        this.monsterBtn.onClick.AddListener(() => {
            GameObject newMonster = this.CreateNewMonster();
            this.monster.Init(newMonster);
        });
 
    }
 
    private GameObject CreateNewHero(string heroName)
    {
        GameObject foundObject = null;
 
        foreach(var data in this.arrHero)
        {
            if(data.name==heroName)
            {
                foundObject = data.gameObject;
                break;
            }
            
        }
 
        var newhero = Instantiate(foundObject);
        return newhero;
    }
 
    private GameObject CreateNewMonster()
    {
        return Instantiate(this.getMonster.gameObject);
    }
 
 
}
 

 

 

2. Hero

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Hero : MonoBehaviour
{
    public GameObject model;
    public GameObject heroPos;
    //public GameObject heroPos;
 
    public void Init(GameObject newhero)
    {
        this.model = newhero;
        this.model.transform.SetParent(this.gameObject.transform);
        Debug.Log(this.heroPos.transform.position);
        this.model.transform.position = this.heroPos.transform.position;
    }
}
 

 

 

3. Monster

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

 

 

4. 결과값

-노란색으로 표시된 위치에 캐릭터가 생김

-빨간색으로 표시된 위치에 몬스터가 생김