블록에 BoxCollider2D를 부착한 후 클릭을 하면

해당 블록의 배열로서의 위치와 Vector2의 위치가 출력됨

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;

public class AtlasManager : MonoBehaviour
{
    public static AtlasManager instance;
    public SpriteAtlas blockAtlas;
    //싱글톤
    private void Awake()
    {
        //AtlasManager 클래스의 인스턴스를 instance에 할당
        instance = this;
    }
}

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.U2D;
using Random = UnityEngine.Random;

public class Test : MonoBehaviour
{
    public Board board;
    private void Start()
    {
        board.CreateBoard();
    }
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            Debug.DrawRay(ray.origin, ray.direction * 100f, Color.red, 1);
            RaycastHit2D raycastHit2D = Physics2D.Raycast(ray.origin, ray.direction);
            if (raycastHit2D.collider != null)
            {
                Block block = raycastHit2D.collider.GetComponent<Block>();
                Debug.Log($"[{block.row}, {block.col}] ({block.transform.position.x}, {block.transform.position.y}), {block.blockType}");
            }
        }
    }
}

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using Random = UnityEngine.Random;

public class Board : MonoBehaviour
{
    private Block[,] board; //1차원 배열이 Block들을 관리
    public GameObject blockPrefab;

    public void CreateBoard()
    {
        //크기가 9인 BlockType의 1차원 배열 만들기
        board = new Block[5, 9]; // 2차원 배열로 변경
        //5행 9열의 Block타입의 2차원 배열 만들기
        for (int i = 0; i < board.GetLength(0); i++)
        {
            for (int j = 0; j < board.GetLength(1); j++)
            {
                CreateBlock(i, j);
            }
        }
        PrintBoard();
    }

    public void CreateBlock(int row, int col)
    {
        Vector2 pos = new Vector2(col, row);
        Block.BlockType blockType = (Block.BlockType)Random.Range(0, 5);
        GameObject blockGo = Instantiate(blockPrefab);
        Block block = blockGo.GetComponent<Block>();
        block.Init(blockType);
        block.SetPosition(pos);

        //배열의 요소에 블록 넣기
        board[row, col] = block;
    }

    public void PrintBoard()
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < board.GetLength(0); i++)
        {
            for (int j = 0; j < board.GetLength(1); j++)
            {
                sb.Append($"({i},{j})"); // StringBuilder에 문자열 추가
            }
            sb.AppendLine(); // 새로운 행 추가
        }
        Debug.Log(sb); // StringBuilder에 저장된 문자열을 출력
    }
}

 

using System.Collections;
using System.Collections.Generic;
using TMPro;
using Unity.Mathematics;
using UnityEngine;

public class Block : MonoBehaviour
{
    public enum BlockType
    {
        Blue, Gray, Green, Pink, Yellow
    }

    public BlockType blockType;
    public SpriteRenderer spriteRenderer;
    public TMP_Text debugText;
    public int row;
    public int col;
    public void Init(BlockType blockType)
    {
        this.blockType = blockType;
        //이미지 변경 
        ChangeSprite(blockType);
    }

    public void ChangeSprite(BlockType blockType)
    {
        //블록의 이름을 넣어서 아틀라스에서 같은 이름인 sprite를 찾고 할당
        Sprite sp =
            AtlasManager.instance.blockAtlas.GetSprite(blockType.ToString());
        spriteRenderer.sprite = sp;
    }

    public void SetPosition(Vector2 pos)
    {
        transform.position = pos;
        var index = Position2Index(pos);
        row = index.row;
        col = index.col;
        debugText.text = $"[{index.row}, {index.col}]";
    }

    public static (int row, int col) Position2Index(Vector2 pos)
    {
        return ((int)pos.y, (int)pos.x);
    }

    public static (int x, int y) Index2Position(Vector2 index)
    {
        return ((int)index.x, (int)index.y);
    }
}

한 것

2개 이하 클릭시 해제 하고 다른 스킬 선택가능

2개가 초과될 시 다른 스킬 버튼 interactable = fasle;

shuffle시 클릭 된 것들 초기화

 

+ 클릭 된 것들의 데이터를 매핑할 인포 클래스를 만들어 저장하여

지정된 경로에 저장이 된다.

 

해야 할 것

인포에 들어간 데이터를 위에 만들어논 슬롯에 들어가게 하며

슬롯에는 이미지

클릭 or 호버 시에는 각 스킬에 대한 정보가 나와야 한다.

 

 

using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI;

public class SkillManager : MonoBehaviour
{
    public static SkillManager instance; // 싱글톤

    public SpriteAtlas skillsAtlas;
    public Button levelUpBtn;
    public Button closeBtn;
    public GameObject selectSkillPopUp;
    public SkillData[] skillDatas;
    private List<int> rememberRandomIndex = new List<int>();

    private void Awake() // 싱글톤
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }

    public void Start()
    {
        levelUpBtn.onClick.RemoveAllListeners();
        OnClickLevelUpBtn();
        OnClickCloseBtn();
        TextAsset asset = Resources.Load<TextAsset>("data/skills_data");
        string json = asset.text;

        skillDatas = JsonConvert.DeserializeObject<SkillData[]>(json);
    }

    public SkillData GetDataById(int id)
    {
        SkillData foundSkillData = null;
        foreach (SkillData skillData in skillDatas)
        {
            if (skillData.id == id)
            {
                foundSkillData = skillData;
                break;
            }
        }
        return foundSkillData;
    }

    public int GetRandomAtlasImgId(int randomIndex)
    {
        return skillDatas[randomIndex].id;
    }

    public string GetRandomAtlasName(int randomIndex)
    {
        return skillDatas[randomIndex].name;
    }

    public string GetRandomAtlasDesc(int randomIndex)
    {
        return skillDatas[randomIndex].desc;
    }

    public Sprite GetRandomAtlasImg(int randomIndex)
    {
        return skillsAtlas.GetSprite(skillDatas[randomIndex].name);
    }

    public int GetSkillsRandomNum()
    {
        int randomIndex;
        do
        {
            randomIndex = Random.Range(0, skillDatas.Length);
        } while (rememberRandomIndex.Contains(randomIndex));

        rememberRandomIndex.Add(randomIndex);

        Debug.Log("랜덤으로 선택된 스킬 인덱스: " + randomIndex);
        return randomIndex;
    }

    public void OnClickLevelUpBtn()
    {
        levelUpBtn.onClick.AddListener(() =>
        {
            selectSkillPopUp.SetActive(true);

            int randomIndex = GetSkillsRandomNum();

            GetRandomAtlasImg(randomIndex);
            GetRandomAtlasName(randomIndex);
            GetRandomAtlasDesc(randomIndex);
        });
    }

    public void OnClickCloseBtn()
    {
        closeBtn.onClick.AddListener(() =>
        {
            selectSkillPopUp.SetActive(false);
        });
    }
}

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using UnityEngine.U2D;
using UnityEditor;
using Newtonsoft.Json;

public class SelectSkillPopUp : MonoBehaviour
{
    public GameObject[] selectSkills;
    public Image[] skillImgs;
    public TMP_Text[] skillIds;
    public TMP_Text[] skillNames;
    public TMP_Text[] skillDescs;

    public Button shuffleSkills;
    public Button selectBtn;
    public SpriteAtlas skillsAtlas;
    List<SkillData> skillList = new List<SkillData>();

    private int selectedCount = 0;
    private List<int> selectedIndexes = new List<int>();

    private List<SkillInfo> selectedSkillInfos = new List<SkillInfo>(); // 스킬 정보를 담을 리스트

    public void Start()
    {
        selectBtn.gameObject.SetActive(false);
        ShowLevelUp();

        foreach (var data in SkillManager.instance.skillDatas)
        {
            skillList.Add(data);
        }
        shuffleSkills.onClick.AddListener(ShuffleSkills);

        // Add click event to each skill object
        for (int i = 0; i < selectSkills.Length; i++)
        {
            int index = i;
            selectSkills[i].GetComponent<Button>().onClick.AddListener(() =>
            {
                ToggleSkill(index);
            });
        }

        // Select 버튼의 클릭 이벤트 추가
        selectBtn.onClick.AddListener(SaveSelectedSkillData);
    }

    public void ShowLevelUp()
    {
        selectedIndexes.Clear();

        for (int i = 0; i < skillImgs.Length; i++)
        {
            int randomIndex = SkillManager.instance.GetSkillsRandomNum();
            selectedIndexes.Add(randomIndex);

            skillImgs[i].sprite = SkillManager.instance.GetRandomAtlasImg(randomIndex);
            skillIds[i].text = SkillManager.instance.GetRandomAtlasImgId(randomIndex).ToString();
            skillNames[i].text = SkillManager.instance.GetRandomAtlasName(randomIndex);
            skillDescs[i].text = SkillManager.instance.GetRandomAtlasDesc(randomIndex);
        }
    }

    public void ShuffleSkills()
    {
        selectedCount = 0;

        for (int i = 0; i < skillImgs.Length; i++)
        {
            int randomIndex = GetUniqueRandomIndex();
            selectedIndexes[i] = randomIndex;

            skillIds[i].text = SkillManager.instance.GetRandomAtlasImgId(randomIndex).ToString();
            skillNames[i].text = SkillManager.instance.GetRandomAtlasName(randomIndex);
            skillDescs[i].text = SkillManager.instance.GetRandomAtlasDesc(randomIndex);
            skillImgs[i].sprite = SkillManager.instance.GetRandomAtlasImg(randomIndex);
            SetImageAlpha(skillImgs[i], 1f); // Reset alpha value
        }

        UpdateSelectBtn();
    }

    int GetUniqueRandomIndex()
    {
        int randomIndex;
        do
        {
            randomIndex = Random.Range(0, skillList.Count);
        } while (selectedIndexes.Contains(randomIndex));

        return randomIndex;
    }

    void SetImageAlpha(Image image, float alpha)
    {
        Color color = image.color;
        color.a = alpha;
        image.color = color;
    }

    void UpdateSelectBtn()
    {
        selectBtn.gameObject.SetActive(selectedCount == 2);
    }

    public void ToggleSkill(int index)
    {
        Image skillImage = skillImgs[index].GetComponent<Image>();
        float alpha = GetImageAlpha(skillImage);

        if (alpha == 1f)
        {
            // Select the skill
            if (selectedCount < 2)
            {
                SetImageAlpha(skillImage, 65f / 255f);
                selectedCount++;

                // 클릭된 스킬의 정보를 SkillInfo 객체에 담고 리스트에 추가
                SkillData selectedSkill = skillList[selectedIndexes[index]];
                SkillInfo skillInfo = new SkillInfo(selectedSkill.id, selectedSkill.name, selectedSkill.sprite_name, selectedSkill.desc);
                selectedSkillInfos.Add(skillInfo);
            }
        }
        else
        {
            // Deselect the skill
            SetImageAlpha(skillImage, 1f);
            selectedCount--;

            // 해당 스킬을 리스트에서 제거
            SkillData selectedSkill = skillList[selectedIndexes[index]];
            selectedSkillInfos.RemoveAll(skillInfo => skillInfo.id == selectedSkill.id);
        }

        UpdateSelectBtn();
    }

    float GetImageAlpha(Image image)
    {
        return image.color.a;
    }

    public void SaveSelectedSkillData()
    {
        // 선택된 스킬의 정보를 직렬화하여 로컬에 저장
        string json = JsonConvert.SerializeObject(selectedSkillInfos);
        // 저장할 경로를 지정하고 파일에 쓰기
        string filePath = Application.persistentDataPath + "/selected_skills.json";
        System.IO.File.WriteAllText(filePath, json);
        Debug.Log("Selected skill data saved to: " + filePath);
    }
    public List<SkillInfo> GetSelectedSkillInfos()
    {
        return selectedSkillInfos;
    }
}

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SkillData
{
    public int id;
    public string name;
    public string sprite_name;
    public string desc;
}

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SkillInfo
{
    public int id;
    public string name;
    public string sprite_name;
    public string desc;

    public SkillInfo(int id, string name, string sprite_name, string desc)
    {
        this.id = id;
        this.name = name;
        this.sprite_name = sprite_name;
        this.desc = desc;
    }
}

해야 할 것

스크립트를 하나로 합쳤는데

2개 클릭 시 다시 다른 버튼 클릭을 막으려다

현재 클릭된 버튼도 클릭이 막힌 상태

클릭이 된 2개를 기준으로 클릭을 해제하면 다른 것을 클릭할 수 있도록 수정하기

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using UnityEngine.U2D;
using UnityEditor;

public class SelectSkillPopUp : MonoBehaviour
{
    public GameObject[] selectSkills;
    public Image[] skillImgs;
    public TMP_Text[] skillIds;
    public TMP_Text[] skillNames;
    public TMP_Text[] skillDescs;

    public Button shuffleSkills;
    public Button selectBtn;
    public SpriteAtlas skillsAtlas;
    List<SkillData> skillList = new List<SkillData>();

    private int selectedCount = 0;
    private List<int> selectedIndexes = new List<int>();

    void Start()
    {
        selectBtn.gameObject.SetActive(false);
        ShowLevelUp();

        foreach (var data in SkillManager.instance.skillDatas)
        {
            skillList.Add(data);
        }
        shuffleSkills.onClick.AddListener(ShuffleSkills);

        // 각 스킬 오브젝트에 대해 클릭 이벤트 추가
        for (int i = 0; i < selectSkills.Length; i++)
        {
            int index = i;
            selectSkills[i].GetComponent<Button>().onClick.AddListener(() =>
            {
                ToggleSkill(index);
            });
        }
    }

    void ShowLevelUp()
    {
        selectedIndexes.Clear();

        for (int i = 0; i < skillImgs.Length; i++)
        {
            int randomIndex = SkillManager.instance.GetSkillsRandomNum();
            selectedIndexes.Add(randomIndex);

            skillImgs[i].sprite = SkillManager.instance.GetRandomAtlasImg(randomIndex);
            skillIds[i].text = SkillManager.instance.GetRandomAtlasImgId(randomIndex).ToString();
            skillNames[i].text = SkillManager.instance.GetRandomAtlasName(randomIndex);
            skillDescs[i].text = SkillManager.instance.GetRandomAtlasDesc(randomIndex);
        }
    }

    void ShuffleSkills()
    {
        selectedCount = 0;

        for (int i = 0; i < skillImgs.Length; i++)
        {
            int randomIndex = GetUniqueRandomIndex();
            selectedIndexes[i] = randomIndex;

            skillIds[i].text = SkillManager.instance.GetRandomAtlasImgId(randomIndex).ToString();
            skillNames[i].text = SkillManager.instance.GetRandomAtlasName(randomIndex);
            skillDescs[i].text = SkillManager.instance.GetRandomAtlasDesc(randomIndex);
            skillImgs[i].sprite = SkillManager.instance.GetRandomAtlasImg(randomIndex);
            SetImageAlpha(skillImgs[i], 1f); // 알파 값을 원래대로 초기화
        }

        UpdateSelectBtn();
    }

    int GetUniqueRandomIndex()
    {
        int randomIndex;
        do
        {
            randomIndex = Random.Range(0, skillList.Count);
        } while (selectedIndexes.Contains(randomIndex));

        return randomIndex;
    }

    void SetImageAlpha(Image image, float alpha)
    {
        Color color = image.color;
        color.a = alpha;
        image.color = color;
    }

    void UpdateSelectBtn()
    {
        selectBtn.gameObject.SetActive(selectedCount == 2);
    }

    public void ToggleSkill(int index)
    {
        if (selectedCount >= 2)
        {
            // 이미 2개의 스킬이 선택되었으므로 다른 스킬 선택을 막음
            return;
        }

        Image skillImage = skillImgs[index].GetComponent<Image>();
        if (GetImageAlpha(skillImage) != 65f / 255f)
        {
            SetImageAlpha(skillImage, 65f / 255f);
            selectedCount++;
        }
        else
        {
            SetImageAlpha(skillImage, 1f);
            selectedCount--;
        }

        UpdateSelectBtn();
    }

    float GetImageAlpha(Image image)
    {
        return image.color.a;
    }
}

 

using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI;

public class SkillManager : MonoBehaviour
{
    public static SkillManager instance; // 싱글톤

    public SpriteAtlas skillsAtlas;
    public Button levelUpBtn;
    public Button closeBtn;
    public GameObject selectSkillPopUp;
    public SkillData[] skillDatas;
    private List<int> rememberRandomIndex = new List<int>();

    private void Awake() // 싱글톤
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }

    public void Start()
    {
        levelUpBtn.onClick.RemoveAllListeners();
        OnClickLevelUpBtn();
        OnClickCloseBtn();
        TextAsset asset = Resources.Load<TextAsset>("data/skills_data");
        string json = asset.text;

        skillDatas = JsonConvert.DeserializeObject<SkillData[]>(json);
    }

    public SkillData GetDataById(int id)
    {
        SkillData foundSkillData = null;
        foreach (SkillData skillData in skillDatas)
        {
            if (skillData.id == id)
            {
                foundSkillData = skillData;
                break;
            }
        }
        return foundSkillData;
    }

    public int GetRandomAtlasImgId(int randomIndex)
    {
        return skillDatas[randomIndex].id;
    }

    public string GetRandomAtlasName(int randomIndex)
    {
        return skillDatas[randomIndex].name;
    }

    public string GetRandomAtlasDesc(int randomIndex)
    {
        return skillDatas[randomIndex].desc;
    }

    public Sprite GetRandomAtlasImg(int randomIndex)
    {
        return skillsAtlas.GetSprite(skillDatas[randomIndex].name);
    }

    public int GetSkillsRandomNum()
    {
        int randomIndex;
        do
        {
            randomIndex = Random.Range(0, skillDatas.Length);
        } while (rememberRandomIndex.Contains(randomIndex));

        rememberRandomIndex.Add(randomIndex);

        Debug.Log("랜덤으로 선택된 스킬 인덱스: " + randomIndex);
        return randomIndex;
    }

    public void OnClickLevelUpBtn()
    {
        levelUpBtn.onClick.AddListener(() =>
        {
            selectSkillPopUp.SetActive(true);

            int randomIndex = GetSkillsRandomNum();

            GetRandomAtlasImg(randomIndex);
            GetRandomAtlasName(randomIndex);
            GetRandomAtlasDesc(randomIndex);
        });
    }

    public void OnClickCloseBtn()
    {
        closeBtn.onClick.AddListener(() =>
        {
            selectSkillPopUp.SetActive(false);
        });
    }
}

해야 할 것

스킬이 중복으로 나오지 않게

그 다음으로 플레이어의 스킬 인벤토리를 만들고

클릭시 순서대로 적용

수정해야할 부분 클릭을 두번해야 색이 변함.

스킬이 중복되게 나오면 안됨

 

 

추가적으로 해야 할 것

유니티를 실행하다 꺼서 다시 시작할 필요 없이

버튼을 클릭 시 스킬이 다시 랜덤으로 생성되게

(이 부분을 계속 시도해보는데 초기화가 안됨)

(RemoveAllListener을 사용해봄)

+ 스킬 2개는 중복이 되면 안된다.

 

 

 

using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI;

public class SkillManager : MonoBehaviour
{
    public static SkillManager instance; //싱글톤

    public SpriteAtlas skillsAtlas;
    public Button levelUpBtn;
    public Button closeBtn;
    public GameObject selectSkillPopUp;
    public SkillData[] skillDatas;
    private int randomSkillIndex;

    private void Awake() //싱글톤
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (instance != null)
        {
            Destroy(this.gameObject);
        }
    }

    // 비모노 일때
    //public static SkillManager Instance 
    //{
    //    get
    //    {
    //        if (null == instance)
    //        {
    //            return null;
    //        }
    //        return instance;
    //    }
    //}


    public void Start()
    {
        levelUpBtn.onClick.RemoveAllListeners();
        OnClickLevelUpBtn();
        OnClickCloseBtn();
        TextAsset asset = Resources.Load<TextAsset>("data/skills_data");
        string json = asset.text;

        Debug.Log(json);

        skillDatas = JsonConvert.DeserializeObject<SkillData[]>(json);
        foreach (SkillData data in skillDatas)
        {
            Debug.Log(data.id);
            //문자열 => 객체 (역직렬화) 각 객체를 돌며 id를 잘 찾는지 확인
        }
    }


    public SkillData GetDataById(int id)
    {
        SkillData foundSkillData = null;
        for (int i = 0; i < skillDatas.Length; i++)
        {
            SkillData skillData = this.skillDatas[i];
            if (skillData.id == id)
            {
                foundSkillData = skillData;
                break;
            }
        }
        return foundSkillData;
    }

    public int GetRandomAtlasImgId()
    {
        int id = skillDatas[randomSkillIndex].id;
        return id;
    }

    public string GetRandomAtlasName()
    {
        string name = skillDatas[randomSkillIndex].name;
        return name;
    }

    public string GetRandomAtlasDesc()
    {
        string desc = skillDatas[randomSkillIndex].desc;
        return desc;
    }


    public Sprite GetRandomAtlasImg()
    {
        //랜덤으로 얻은 배열인 인덱스의 이미지 이름
        Sprite skillSprite = skillsAtlas.GetSprite(skillDatas[randomSkillIndex].name);
        return skillSprite;
    }

    public void GetSkillsRandomNum()
    {
        randomSkillIndex = Random.Range(0, skillDatas.Length);
        //스킬데이터의 인덱스번호로 랜덤하게 출력
        //Debug.Log(randomSkillIndex); 


    }

    public void OnClickLevelUpBtn()
    {
        levelUpBtn.onClick.AddListener(() =>
            {
                selectSkillPopUp.SetActive(true);

                GetSkillsRandomNum();

                GetRandomAtlasImg();
                GetRandomAtlasName();
                GetRandomAtlasDesc();
            });
    }



    public void OnClickCloseBtn()
    {
        closeBtn.onClick.AddListener(() =>
        {
            selectSkillPopUp.SetActive(false);
        });
    }





}

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class SelectSkillPopUp : MonoBehaviour
{
    public Image skillImg1;
    public TMP_Text skillId1;
    public TMP_Text skillName1;
    public TMP_Text skillDesc1;


    public Image skillImg2;
    public TMP_Text skillId2;
    public TMP_Text skillName2;
    public TMP_Text skillDesc2;


    public Button shuffleSkills;


   
    void Start()
    {

        shuffleSkills.onClick.AddListener(() =>
        {
            Debug.Log("클릭");

            SkillManager.instance.OnClickLevelUpBtn();
        });
        ////skillId1.text = SkillManager.instance.GetDataById(105).id.ToString();
        ////skillId2.text = SkillManager.instance.GetDataById(104).id.ToString();

        //skillImg1.sprite = SkillManager.instance.GetRandomAtlasImg();
        //skillImg2.sprite = SkillManager.instance.GetRandomAtlasImg();
        ////skillId1.text = SkillManager.instance.GetDataById().id.ToString();
        //skillId1.text = SkillManager.instance.GetRandomAtlasImgId().ToString();
        //skillId2.text = SkillManager.instance.GetRandomAtlasImgId().ToString();



        skillImg1.sprite = SkillManager.instance.GetRandomAtlasImg();
        skillId1.text = SkillManager.instance.GetRandomAtlasImgId().ToString();
        skillName1.text = SkillManager.instance.GetRandomAtlasName().ToString();
        skillDesc1.text = SkillManager.instance.GetRandomAtlasDesc().ToString();


        SkillManager.instance.GetSkillsRandomNum();

        
        skillImg2.sprite = SkillManager.instance.GetRandomAtlasImg();
        skillId2.text = SkillManager.instance.GetRandomAtlasImgId().ToString();
        skillName2.text = SkillManager.instance.GetRandomAtlasName().ToString();
        skillDesc2.text = SkillManager.instance.GetRandomAtlasDesc().ToString();
    }

}

제이슨의 데이터를 가져오는 것은 성공하고

UI를 만들었으나 TMP_Text에 아이디를 가져오는 와중에

Null이 나왔는데 어찌저찌 만지다 보니 해결은 되었지만,

개운하지 않은 이 찝찝한 기분..

 

using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

public class SkillManager : MonoBehaviour
{
    public static SkillManager instance; //싱글톤
    public Button levelUpBtn;
    public Button closeBtn;
    public GameObject selectSkillPopUp;
    public SkillData[] skillDatas;
    private void Awake() //싱글톤
    {
        if(instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }else if(instance != null)
        {
            Destroy(this.gameObject);
        }
    }

    //public static SkillManager Instance
    //{
    //    get
    //    {
    //        if (null == instance)
    //        {
    //            return null;
    //        }
    //        return instance;
    //    }
    //}


    public void Start()
    {
        OnClickLevelUpBtn();
        OnClickCloseBtn();
        TextAsset asset = Resources.Load<TextAsset>("data/skills_data");
        string json = asset.text;

        Debug.Log(json);

        skillDatas = JsonConvert.DeserializeObject<SkillData[]>(json);
        foreach (SkillData data in skillDatas)
        {
            Debug.Log(data.id);
            //문자열 => 객체 (역직렬화) 각 객체를 돌며 id를 잘 찾는지 확인
        }
    }


    public SkillData GetDataById(int id)
    {
        SkillData foundSkillData = null;
        for(int i = 0; i < skillDatas.Length; i++)
        {
            SkillData skillData = this.skillDatas[i];
            if(skillData.id == id)
            {
                foundSkillData = skillData;
                break;
            }
        }
        return foundSkillData;
    }


    public void OnClickLevelUpBtn()
    {
        levelUpBtn.onClick.AddListener(() =>
        {
            selectSkillPopUp.SetActive(true);
        });

    }


    public void OnClickCloseBtn()
    {
        closeBtn.onClick.AddListener(() =>
        {
            selectSkillPopUp.SetActive(false);
        });
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SkillData
{
    public int id;
    public string name;
    public string sprite_name;
    public string desc;
}

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class SelectSkillPopUp : MonoBehaviour
{
    public TMP_Text skillId;
    void Start()
    {
        skillId.text = SkillManager.instance.GetDataById(103).id.ToString();
    }

}

using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using Unity.VisualScripting;
using Unity.VisualScripting.Antlr3.Runtime.Tree;
using UnityEngine;
using UnityEngine.U2D;
using UnityEngine.UI;

public class Main : MonoBehaviour
{
    private Main() { }
    private static Main instance;
    public static Main Instance
    {
        get
        {
            // 인스턴스가 null인 경우 새로 생성
            if (instance == null)
            {
                instance = new Main();
                // 기존의 Start 메서드 내용을 Init 메서드로 옮김
                instance.Init();
            }
            return instance;
        }
    }

    public SpriteAtlas equipmentAtlas;
    [SerializeField] private Image weapon;
    [SerializeField] private Image armor;
    [SerializeField] private Image helmet;
    [SerializeField] private Image shield;
    [SerializeField] private Image accessaries;

    public EquipmentData[] equipmentDatas;
    private int id;

    void Init()
    {
        TextAsset asset = Resources.Load<TextAsset>("data/equipment_data");
        string json = asset.text;
        //Debug.Log(json);

        //현재 문자열을 객체로 역직렬화
        equipmentDatas = JsonConvert.DeserializeObject < EquipmentData[] >(json);

        EquipmentData foundData = this.GetDataById(1002);
        //foreach (EquipmentData equipment in equipmentDatas)
        //{
        //JSON 데이터에서 해당 필드가 비어있거나 값이 없다면, 해당 필드는 역직렬화될 때 0으로 초기화
        //Debug.LogFormat("{0}, {1}, {2}, {3}, {4}", equipment.id, equipment.name, equipment.type, equipment.damage, equipment.defense);
        //}
        Debug.LogFormat("{0}, {1}, {2}, {3}", foundData.id, foundData.name, foundData.type, foundData.defense);

    }

    public EquipmentData GetDataById(int id)
    {
        EquipmentData foundData = null;
        this.id = id;
        for(int i = 0; i < this.equipmentDatas.Length; i++)
        {
            EquipmentData equipmentData = this.equipmentDatas[i];
            if(equipmentData.id == id)
            {
                foundData = equipmentData;
                break;
            }
        }
        return foundData;
    }

    public Sprite GetSpriteImg(string imgName)
    {
        EquipmentData equipmentData = null;
        foreach (var data in equipmentDatas)
        {
            if (data.name == imgName)
            {
                equipmentData = data;
                break;
            }
        }

        if (equipmentData != null)
        {
            string imagePath = "img/" + equipmentData.name;
            Sprite sprite = Resources.Load<Sprite>(imagePath);
            return sprite;
        }
        else
        {
            Debug.LogError("Equipment data with name " + imgName + " not found.");
            return null;
        }
    }

    public void LoadAndSetImage(Image imageComponent, string imgName)
    {
        Sprite sprite = GetSpriteImg(imgName);
        if (sprite != null)
        {
            imageComponent.sprite = sprite;
        }
    }

}

 

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Weapon : MonoBehaviour
{
    public TMP_Text idText;
    public Image weaponImg;
    private void Start()
    {
        //Sprite weaponSprite = Main.Instance.equipmentAtlas.GetSprite("weaponA");
        //weaponImg.sprite = weaponSprite;

        //Sprite sprite = Resources.Load<Sprite>("img/weaponA");
        //weaponImg.sprite = sprite;

        Main.Instance.LoadAndSetImage(weaponImg, "weaponA");

        //weaponImg = 
        idText.text = Main.Instance.GetDataById(1000).id.ToString();
    }
}

 

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;


public class Shield : MonoBehaviour
{
    public TMP_Text idText;
    public Image shieldImg;

    private void Start()
    {
        Main.Instance.LoadAndSetImage(shieldImg, "shieldA");
        idText.text = Main.Instance.GetDataById(1001).id.ToString();
    }
}

 

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;


public class Armor : MonoBehaviour
{
    public TMP_Text idText;
    public Image armorImg;


    private void Start()
    {
        Main.Instance.LoadAndSetImage(armorImg, "armorA");
        idText.text = Main.Instance.GetDataById(1003).id.ToString();
    }

}

 

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class Accessaries : MonoBehaviour
{
    public TMP_Text idText;
    public Image accessoryImg;

    private void Start()
    {
        Main.Instance.LoadAndSetImage(accessoryImg, "accessoryA");
        idText.text = Main.Instance.GetDataById(1004).id.ToString();
    }
}

 

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class Helmet : MonoBehaviour
{
    public TMP_Text idText;
    public Image helmetImg;
    private void Start()
    {
        Main.Instance.LoadAndSetImage(helmetImg, "helmetA");
        idText.text = Main.Instance.GetDataById(1002).id.ToString();
    }
}

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EquipmentData
{
    public int id;
    public string name;
    public string type;
    public int damage;
    public int defense;
}

+ Recent posts