'C#'에 해당되는 글 80건

  1. 2019.12.18 Sprite Atlas 사용하기
  2. 2019.12.18 12.18 인벤토리만들기
  3. 2019.12.17 12.17 Unity Editor 활용해 실시간으로 Json 파일 만들기
  4. 2019.12.16 12.16 토글 버튼 만들기
  5. 2019.12.16 12.16 UI 버튼 만들기
  6. 2019.12.16 오브젝트 풀링 (인스턴스로 접근)
  7. 2019.12.13 12.13 캐릭터 선택하기(랜덤포함)
  8. 2019.12.10 12.10 오브젝트 풀 활용

Sprite Atlas 사용하기

C#/Study 2019. 12. 18. 16:54

추가:

Atlas 사용하기:

0. Edit > Project Setting > Editor> Sprite Packer > Mode = Always Enabled

1. 프로젝트 폴더 우클릭해서 Create > Sprite Atlas 생성

2. (인스펙터를 잠금한 후)Objects for Packing에 넣을 스프라이트들을 드래그하여 넣는다. 

(Pack Preview 클릭하면 미리보기 가능)

3. 코드창에 

추가:

using UnityEngine.U2D;

선언:
public SpriteAtlas atlas;

사용:

atlas.GetSprite(이름);

(atlas 안에 있는 스프라이트를 꺼내온다)

'C# > Study' 카테고리의 다른 글

오브젝트 풀링 (인스턴스로 접근)  (0) 2019.12.16
12.10 오브젝트 풀 활용  (0) 2019.12.10
12.09 드래곤플라이트 2 (이펙트 추가)  (0) 2019.12.09
12.02 객체 충돌  (0) 2019.12.02
struct 와 클래스의 차이  (0) 2019.11.02
:

12.18 인벤토리만들기

C#/실습 2019. 12. 18. 16:48

Scene: TestPopup 

코드:

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class TestHQ : MonoBehaviour
{
    public UIPopup_SelectedStage popup_SelectedStage;
    public Button stageBtn;
    public Image dim;
    public List<UserItem> userItems = new List<UserItem>();
    UserItem[] arrUserItems;
    ItemData[] ItemDatas;
    private void Awake()
    {
        string json = File.ReadAllText("ItemData.json"); 
        ItemDatas = JsonConvert.DeserializeObject<ItemData[]>(json); // 아이템 row 데이터 로드
        if (File.Exists("UserItemData.json")) //유저가 갖고있던 아이템 로드
        {
            Debug.Log("Real user Items");
            string userItemJson = File.ReadAllText("UserItemData.json");
            arrUserItems = JsonConvert.DeserializeObject<UserItem[]>(userItemJson);            
            foreach(UserItem userItem in arrUserItems)
            {
                userItems.Add(userItem);
            }
        }
        else//기존 유저 아이템 파일이 없다면
        {
            Debug.Log("Sample user Items");
            arrUserItems = new UserItem[3];
            arrUserItems[0= new UserItem(ItemDatas[0].id, ItemDatas[0].name, ItemDatas[0].iconName, 2);
            arrUserItems[1= new UserItem(ItemDatas[1].id, ItemDatas[1].name, ItemDatas[1].iconName, 2);
            arrUserItems[2= new UserItem(ItemDatas[2].id, ItemDatas[2].name, ItemDatas[2].iconName, 2);
            foreach (UserItem userItem in arrUserItems)
            {
                userItems.Add(userItem);
            }
        }
        
 
    }
    void Start()
    {
 
        popup_SelectedStage.Init(new UserInfo("홍길동"315753603920), userItems);
        stageBtn.onClick.AddListener(() =>
        {
            popup_SelectedStage.Show();
            dim.gameObject.SetActive(true);
        });
        popup_SelectedStage.closeBtn.onClick.AddListener(() =>
        {
            popup_SelectedStage.Hide();
            dim.gameObject.SetActive(false);
        });
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class ItemData
{
    public int id;
    public string name;
    public string iconName;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
public class UIPopup_SelectedStage : MonoBehaviour
{
    public Button closeBtn;
    public Text text;
    UserInfo userInfo;
    public InventoryItems[] inventoryItems;
    public SpriteAtlas atlas;
 
    public void Init(UserInfo userInfo, List<UserItem> userItems)
    {
        for(int i =0; i<inventoryItems.Length; i++)//초기화
        {
            if(i<9)
            {
                inventoryItems[i].iconStatus = eItemIconStatus.none; //열려있는 아이템칸 설정
            }
            else
            {
                inventoryItems[i].iconStatus = eItemIconStatus.locked; // 닫혀있는 아이템 칸 설정
            }
        }
        this.userInfo = userInfo;
        this.text.text = "UserName: \t" + userInfo.userName + "\n Attack: \t\t" + userInfo.atk + "\n Defense: \t" + userInfo.def + "\n Health: \t\t" + userInfo.hp;        
        for(int i=0; i<userItems.Count; i++// 아이템칸에 차례대로 내 아이템 넣기.
        {
            inventoryItems[i].iconStatus = eItemIconStatus.have;
            inventoryItems[i].userItems = userItems[i];
            inventoryItems[i].gameObject.transform.GetChild(1).gameObject.transform.GetChild(0).GetComponent<Text>().text = inventoryItems[i].userItems.count.ToString();
        }
        for(int i = 0; i<inventoryItems.Length; i++// 아이콘의 상태에 따라 스프라이트 바꾸기
        {
            switch(inventoryItems[i].iconStatus)
            {
                case eItemIconStatus.locked :
                    {
                        inventoryItems[i].gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>("MyInfo/inventory_item_lock"));
                        inventoryItems[i].gameObject.transform.GetChild(0).gameObject.SetActive(false);
                        inventoryItems[i].gameObject.transform.GetChild(1).gameObject.SetActive(false);
                        break;
                    }
                case eItemIconStatus.have:
                    {
                        for(int j = 0; j< userItems.Count; j++)
                        {
                            string iconName = string.Format("MyInfo/{0}",inventoryItems[j].userItems.iconName);
                            inventoryItems[j].gameObject.transform.GetChild(0).gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>(iconName));
                        }
                        break;
                    }
                case eItemIconStatus.none:
                    {
                        inventoryItems[i].gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>("MyInfo/inventory_item_bg"));
                        inventoryItems[i].gameObject.transform.GetChild(0).gameObject.SetActive(false);
                        inventoryItems[i].gameObject.transform.GetChild(1).gameObject.SetActive(false);
                        break;
                    }
            }
        }
 
    }
    public void Show()
    {
        this.gameObject.SetActive(true);
    }
    public void Hide()
    {
        this.gameObject.SetActive(false);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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;
 
public class UserInfo
{
    public string userName;
    public int level;
    public int atk;
    public int def;
    public int hp;
    public UserInfo(string userName, int level, int atk, int def, int hp)
    {
        this.userName = userName;
        this.level = level;
        this.atk = atk;
        this.def = def;
        this.hp = hp;
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public enum eItemIconStatus { have, none, locked}
public class InventoryItems : MonoBehaviour
{
    public eItemIconStatus iconStatus;
    public UserItem userItems;
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
 
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 UserItem 
{
    public int id;
    public string name;
    public string iconName;
    public int count;
    public UserItem(int id, string name, string iconName, int count)
    {
        this.id = id;
        this.name = name;
        this.iconName = iconName;
        this.count = count;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

:

12.17 Unity Editor 활용해 실시간으로 Json 파일 만들기

C#/실습 2019. 12. 17. 17:52

Unity 파일명: Study_015 Title

 

코드:

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
 
public enum eStars { one, two, three, none }
 
public class HQ : MonoBehaviour
{    
    public StageInfo[] stageInfos = new StageInfo[18];
    public eStageStatus[] stageStatuses;
    public eStars[] stars;
    public Stage[] stages;
    private GameObject star1;
    private GameObject star2;
    private GameObject star3;
    int starsN = 0;
 
    // Start is called before the first frame update
    private void Awake()
    {
        star1 = Resources.Load<GameObject>("Stage/Star1");
        star2 = Resources.Load<GameObject>("Stage/Star2");
        star3 = Resources.Load<GameObject>("Stage/Star3");
        
 
    }
    void Start()
    {
        for(int i=0; i<stages.Length; i++)
        {
            stages[i].stageStatus = stageStatuses[i];
            stages[i].gameObject.transform.GetChild(0).gameObject.GetComponent<Text>().text = i.ToString();
        }
 
        for (int i = 0; i<stages.Length; i++// stage status 체크
        {
            if(stages[i].stageStatus == eStageStatus.Cleared) //깬 경우
            {
                stages[i].gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>("Stage/Cleared"));
                stages[i].Stars = (int)stars[starsN];
                starsN++;
                switch(stages[i].Stars)
                {
                    case 0:
                        {
                            var model = Instantiate(star1);
                            model.transform.SetParent(stages[i].gameObject.transform.GetChild(1).transform, false);
                            model.transform.localPosition = Vector3.zero;
                            break;
                        }
                        
                    case 1:
                        {
                            var model = Instantiate(star2);
                            model.transform.SetParent(stages[i].gameObject.transform.GetChild(1).transform, false);
                            model.transform.localPosition = Vector3.zero;
                            break;
                        }
                    case 2:
                        {
                            var model = Instantiate(star3);
                            model.transform.SetParent(stages[i].gameObject.transform.GetChild(1).transform, false);
                            model.transform.localPosition = Vector3.zero;
                            break;
                        }                        
                }
            }
            else if(stages[i].stageStatus == eStageStatus.Opened)
            {
                stages[i].gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>("Stage/Opened"));
            }
            else if(stages[i].stageStatus == eStageStatus.Locked)
            {
                stages[i].gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>("Stage/Locked"));
                stages[i].gameObject.transform.GetChild(0).gameObject.SetActive(false);
            }
        }
    }
    public void GenerateJson()
    {
        for (int i = 0; i < stageInfos.Length; i++)
        {
            //stageInfos[i].stageID = i;
            //stageInfos[i].stageStatus = (int)stageStatuses[i];
            //stageInfos[i].stars = (int)stars[i];
 
            StageInfo stageInfo = new StageInfo(i, (int)stageStatuses[i], (int)stars[i]);
            stageInfos[i] = stageInfo;
            
        }
        string json = JsonConvert.SerializeObject(stageInfos);
        File.WriteAllText("StageInfo", json);
 
    }
 
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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 UnityEditor;
 
[CustomEditor(typeof(HQ))]
 
public class GenerateJson : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
 
        HQ generator = (HQ)target;
        if (GUILayout.Button("Generate Json"))
        {
            generator.GenerateJson();
        }
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class StageInfo
{
    public int stageID = 0;
    public int stageStatus;
    public int stars = 0;
    public StageInfo(int stageID, int stageStatus, int stars)
    {
        this.stageID = stageID;
        this.stageStatus = stageStatus;
        this.stars = stars;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public enum eStageStatus { Opened, Cleared, Locked}
public class Stage : MonoBehaviour
{
    public eStageStatus stageStatus;
    private int stars = 0;
    public int Stars { get { return stars; } set { stars = value; } }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

'C# > 실습' 카테고리의 다른 글

12.18 인벤토리만들기  (0) 2019.12.18
12.16 UI 버튼 만들기  (0) 2019.12.16
12.13 캐릭터 선택하기(랜덤포함)  (0) 2019.12.13
12.09 충돌감지와 sprite활용하기(delegate)  (0) 2019.12.09
12.06 드래곤플라이트 구현  (0) 2019.12.06
:

12.16 토글 버튼 만들기

C#/과제 2019. 12. 16. 17:53
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class UIToggleBtnMessage : UIToggleBtn
{
    public InputField inputField;    
    public override void Start()
    {
 
        btn.onClick.AddListener(() =>
        {
            toggle = !toggle;
            if (toggle)
            {
                string text = this.inputField.textComponent.text;
                image.gameObject.SetActive(toggle);
                this.image.gameObject.transform.GetChild(0).GetComponent<Text>().text = text;
                Debug.Log(text);
                this.gameObject.transform.GetChild(0).GetComponent<Text>().text = "Hide";
 
            }
            else
            {
                image.gameObject.SetActive(toggle);
                this.gameObject.transform.GetChild(0).GetComponent<Text>().text = "Show";
            }
        });                
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIToggleBtn : MonoBehaviour
{
    public Button btn;
    public Image image;
    public bool toggle = false;
    // Start is called before the first frame update
    public virtual void Start()
    {
        btn.onClick.AddListener(() =>
        {
            toggle = !toggle;
            if(toggle)
            {
                image.gameObject.SetActive(toggle);
                this.gameObject.transform.GetChild(0).GetComponent<Text>().text = "Hide";
 
            }
            else
            {
                image.gameObject.SetActive(toggle);
                this.gameObject.transform.GetChild(0).GetComponent<Text>().text = "Show";
            }
        });
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

'C# > 과제' 카테고리의 다른 글

2019.12.08 드래곤플라이트 과제  (0) 2019.12.08
:

12.16 UI 버튼 만들기

C#/실습 2019. 12. 16. 17:04

코드:

 

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 System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Title : MonoBehaviour
{
    enum eMenuType { Items, Shop, Message, Mission, Ranking, Settings};
    public UIButtonMenu[] arrBtnMenu;
    public Sprite[] sprites;
    public string[] btnMenuNames;
    // Start is called before the first frame update
    void Start()
    {                
        for(int i = 0; i<this.arrBtnMenu.Length; i++)
        {
            eMenuType menus = (eMenuType)i;
            this.arrBtnMenu[i].Init(menus.ToString(),sprites[i]);
            Button btn = arrBtnMenu[i].gameObject.transform.GetChild(1).GetComponent<Button>();
            btn.onClick.AddListener(() =>
            {
                Debug.LogFormat("selected Menu: {0}, {1} i: {2}", menus.ToString(), (int)menus);
            });
            
        }    
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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 UIButtonMenu : MonoBehaviour
{
    public Image icon;
    public Text textBtnName;
    public Button btn;
 
    public void Init(string btnName, Sprite spIcon)
    {
        this.textBtnName.text = btnName;
        this.icon.sprite = spIcon;
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class UISelectedButton : MonoBehaviour
{
    public Button btn;
    public System.Action Onselected;
    public Text text;
    void Start()
    {        
        this.btn.onClick.AddListener(() =>
        {
            this.Onselected();
        });
    }
    public void Init(string text)
    {
        this.gameObject.transform.GetChild(1).gameObject.SetActive(false);
        this.text.text = text;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

Horizontal LayOut Group 컴포넌트를 이용해 더욱 쉽게 정렬을 할 수 있었다.

 

:

오브젝트 풀링 (인스턴스로 접근)

C#/Study 2019. 12. 16. 10:06
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class objectPool : MonoBehaviour
{
    private List<Bullet> bullets;
    private GameObject bulletPrefab;
    public void Init(GameObject bulletprefab) //Init을 해줘야한다!
    {
        this.bullets = new List<Bullet>();
        this.bulletPrefab = bulletprefab;
    }
    public void PreLoad()//만들기
    {
        for(int i =0; i<10; i++)
        {
            var bulletGo = Instantiate<GameObject>(this.bulletPrefab);
            bulletGo.transform.SetParent(this.transform, false);
            bulletGo.transform.localPosition = Vector3.zero;
            bulletGo.SetActive(false);
            var bullet = bulletGo.GetComponent<Bullet>();
            this.bullets.Add(bullet);
        }
    }
    public Bullet GetBullet() //꺼내기
    {
        Bullet bullet = null;
        if (this.bullets.Count > 0)
        {
            bullet = this.bullets[0];
            this.bullets.RemoveAt(0);
            bullet.gameObject.SetActive(true);
            bullet.transform.SetParent(null);
        }
        else
        {
            //재사용할 총알 없음
            bullet = Instantiate<GameObject>(this.bulletPrefab).GetComponent<Bullet>();           
        }
        return bullet;
    }
    public void Release(Bullet bullet) // 넣기
    {
        bullet.transform.SetParent(this.transform, false);
        bullet.transform.localPosition = Vector3.zero;
        bullet.gameObject.SetActive(false);
        this.bullets.Add(bullet);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

App 클래스에서 퍼블릭 멤버 변수로 선언하여 사용한다.

 

'C# > Study' 카테고리의 다른 글

Sprite Atlas 사용하기  (0) 2019.12.18
12.10 오브젝트 풀 활용  (0) 2019.12.10
12.09 드래곤플라이트 2 (이펙트 추가)  (0) 2019.12.09
12.02 객체 충돌  (0) 2019.12.02
struct 와 클래스의 차이  (0) 2019.11.02
:

12.13 캐릭터 선택하기(랜덤포함)

C#/실습 2019. 12. 13. 17:07

코드:

 

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Ingame : MonoBehaviour
{
    public UISelectedButton[] btns;
    public UISelectedButton randomBtn;
    public string[] btnNames;
    public Image image;
    private Coroutine changeC;
    private GameObject selectedObject;
    public Button selectBtn;
    public Text selectedText;
    public void Awake()
    {
 
        Debug.Log("Ingame: Awake");
 
    }
    private void Start()
    {
        selectBtn.onClick.AddListener(() =>
        {
            StopAllCoroutines();
            this.selectedText.text = this.selectedObject.transform.GetChild(0).GetComponent<Text>().text;
        });
        int i = 0;
        foreach(var btn in btns)
        {
            btn.Onselected = () =>
            {
                foreach(var btn2 in btns)
                {
                    btn2.gameObject.transform.GetChild(1).gameObject.SetActive(false);
                }
                StopAllCoroutines();
                btn.gameObject.transform.GetChild(1).gameObject.SetActive(true);
                this.selectedObject = btn.gameObject;
                this.image.sprite = btn.gameObject.GetComponent<Image>().sprite;
            };
            Debug.Log(btnNames[i]);
            btn.Init(btnNames[i]);
            i++;
        }
        randomBtn.Onselected = () =>
        {
            changeC = StartCoroutine(changeImage());
            foreach (var btn2 in btns)
            {
                btn2.gameObject.transform.GetChild(1).gameObject.SetActive(false);
                this.selectedObject = randomBtn.gameObject;
                randomBtn.gameObject.transform.GetChild(1).gameObject.SetActive(true);
 
            }
        };
        randomBtn.Init("random");
 
    }
    IEnumerator changeImage()
    {
        int i=0;
        while(true)
        {
            if(i >= 4)
            {
                i = 0;
            }
            this.image.sprite = btns[i].gameObject.GetComponent<Image>().sprite;
            this.selectedObject = btns[i].gameObject;
            yield return new WaitForSeconds(0.2f);
            i++;
        }
    }
    public void Init()
    {
        Debug.Log("게임 초기화");
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class UISelectedButton : MonoBehaviour
{
    public Button btn;
    public System.Action Onselected;
    public Text text;
    void Start()
    {        
        this.btn.onClick.AddListener(() =>
        {
            this.Onselected();
        });
    }
    public void Init(string text)
    {
        this.gameObject.transform.GetChild(1).gameObject.SetActive(false);
        this.text.text = text;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

씬전환은 덤이다.

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.SceneManagement;
 
public class App : MonoBehaviour
{
    private void Awake()
    {
    }
    void Start()
    {
        var oper = SceneManager.LoadSceneAsync("Ingame", LoadSceneMode.Additive);
        oper.completed += (ao) =>
        {
            Debug.Log("Ingame 씬 로드완료");
 
        };
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
:

12.10 오브젝트 풀 활용

C#/Study 2019. 12. 10. 16:47

코드:

 

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class App : MonoBehaviour
{
    public Button btn;
    public GameObject bulletPrefab;
    public objectPool objectPool;
    // Start is called before the first frame update
    void Start()
    {
        this.objectPool.Init(this.bulletPrefab);
        this.objectPool.PreLoad();
 
        btn.onClick.AddListener(() => {
            var bullet = this.objectPool.GetBullet();
            var initPos = new Vector3(001);
            bullet.Init(initPos);
            bullet.onDestroy = () =>
            {
                objectPool.Release(bullet);
            };
        });
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Bullet : MonoBehaviour
{
    public float speed =3.5f;
    public System.Action onDestroy;
    private Coroutine coroutine;
    public void Init(Vector3 initPos)
    {
        this.transform.position = initPos;
        this.gameObject.SetActive(true);
        this.Move();
    }
    public void Move()
    {
        coroutine = this.StartCoroutine(this.MoveImpl());
    }
    public IEnumerator MoveImpl()
    {
        while(true)
        {
            this.transform.Translate(Vector3.up * this.speed * Time.deltaTime);            
            yield return null;
        }
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        Debug.LogFormat("OnTriggerEnter2D:{0}", collision);
        StopCoroutine(coroutine);
        this.onDestroy();
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class objectPool : MonoBehaviour
{
    private List<Bullet> bullets;
    private GameObject bulletPrefab;
    public void Init(GameObject bulletprefab)
    {
        this.bullets = new List<Bullet>();
        this.bulletPrefab = bulletprefab;
    }
    public void PreLoad()//만들기
    {
        for(int i =0; i<10; i++)
        {
            var bulletGo = Instantiate<GameObject>(this.bulletPrefab);
            bulletGo.transform.SetParent(this.transform, false);
            bulletGo.transform.localPosition = Vector3.zero;
            bulletGo.SetActive(false);
            var bullet = bulletGo.GetComponent<Bullet>();
            this.bullets.Add(bullet);
        }
    }
    public Bullet GetBullet() //꺼내기
    {
        Bullet bullet = null;
        if (this.bullets.Count > 0)
        {
            bullet = this.bullets[0];
            this.bullets.RemoveAt(0);
            bullet.gameObject.SetActive(true);
            bullet.transform.SetParent(null);
        }
        else
        {
            //재사용할 총알 없음
            bullet = Instantiate<GameObject>(this.bulletPrefab).GetComponent<Bullet>();           
        }
        return bullet;
    }
    public void Release(Bullet bullet) // 넣기
    {
        bullet.transform.SetParent(this.transform, false);
        bullet.transform.localPosition = Vector3.zero;
        bullet.gameObject.SetActive(false);
        this.bullets.Add(bullet);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

'C# > Study' 카테고리의 다른 글

Sprite Atlas 사용하기  (0) 2019.12.18
오브젝트 풀링 (인스턴스로 접근)  (0) 2019.12.16
12.09 드래곤플라이트 2 (이펙트 추가)  (0) 2019.12.09
12.02 객체 충돌  (0) 2019.12.02
struct 와 클래스의 차이  (0) 2019.11.02
: