카드를 획득할 때 인벤토리에서 원하는 위치에서 생성되게 할 것이고,

하이어라이키 관점에서 봤을때는 부모와 같은 위치에서 생성되어야 Canvas 안에 적용이 될 것이다.

 

https://docs.unity3d.com/ScriptReference/Object.Instantiate.html

 

Unity - Scripting API: Object.Instantiate

This function makes a copy of an object in a similar way to the Duplicate command in the editor. If you are cloning a GameObject you can specify its position and rotation (these default to the original GameObject's position and rotation otherwise). If you

docs.unity3d.com

 

 

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

public class PreparedCard : MonoBehaviour
{
    private Button btn;
    private float spacing = 11.8f;

    void Start()
    {
        btn = GetComponent<Button>();

        btn.onClick.AddListener(() =>
        {
            Debug.Log("버튼이 눌림");

            // 새로운 오브젝트를 생성하고, 원본의 부모에 붙이기
            GameObject newObject = Instantiate(gameObject, transform.parent);

            // 새로운 오브젝트의 로컬 위치 조정
            newObject.transform.localPosition += new Vector3(spacing, 0, 0);
        });
    }
}

 

하지만 그리드 레이아웃을 설정할 때 이 spacing을 조절하였으므로

따로 spacing을 조절하지 않아도 되서 주석처리하였다.

 

시작을 하면 플레이어의 카드 인포를 찾아서 값을 가져올 수 있도록 변경

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

public class PreparedCard : MonoBehaviour
{
    private Button btn;
    //private float spacing = 11.8f;
    public TMP_Text value;

    void Start()
    {
        PlayerManager.Instance.LoadPreparedCardData();
        PlayerManager.Instance.LoadPreparedCardInfo();
        this.value.text = PlayerManager.Instance.dicPreparedCardInfo[2000].value.ToString();

        btn = GetComponent<Button>();

        btn.onClick.AddListener(() =>
        {
            Debug.Log("버튼이 눌림");

            // 새로운 오브젝트를 생성하고, 원본의 부모에 붙이기
            GameObject newObject = Instantiate(gameObject, transform.parent);

            // 새로운 오브젝트의 로컬 위치 조정
            //newObject.transform.localPosition += new Vector3(spacing, 0, 0);
            Debug.Log(value.text);

        });


    }

}

 

 

https://console.firebase.google.com/?hl=ko

 

로그인 - Google 계정

이메일 또는 휴대전화

accounts.google.com

 

 

다운로드 하면 이렇게 제이슨 파일이 만들어지고 이것을 프로젝트에 넣어주면 된다.

 

Firebase SDK도 설치

압축을 풀면 이렇게 생긴다.

여기서 필요한 것을 가져다가 쓰면 된다.

현재는 FirebaseDatabase를 사용할 것이다.

가장 가까운 싱가포르 선택

 

IOS Build 선택 후 다운로드

설치 후 다시 프로젝트로 들어간다.

 

창이 나오면 Yes만 클릭하면 된다.

 

이름으로 추가 를 선택 후

com.unity.nuget.newtonsoft-json를 넣는다.

 

스크립트 를 만든후 빈 오브젝트에 할당

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

public class DBManager : MonoBehaviour
{
    [SerializeField] private string databaseUrl;

    private void Start()
    {
       FirebaseApp.DefaultInstance.Options.DatabaseUrl
            = new System.Uri(databaseUrl);
    }

}

게임정보

유저 아이디

점수

GameInfo

userId

score

이 주소를 복사 한후

여기에 넣어주면 된다.

 

새 스크립트 생성 및 수정

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

public class GameMain : MonoBehaviour
{
    [SerializeField] private string userId;
    [SerializeField] private int score;

    void Start()
    {
        SaveGame();
    }

    public void SaveGame()
    {
        Debug.Log("SaveGame");

        GameInfo gameInfo = new GameInfo(userId, score);    //저장 객체 만들기 
        string json = JsonConvert.SerializeObject(gameInfo);  //직렬화 

        Debug.Log($"{json}");

        //저장 
        DBManager.instance.SaveData(json);
    }
}

 

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

public class GameInfo
{
    public string userId;
    public int score;

    //생성자 
    public GameInfo(string userId, int score) {
        this.userId = userId;
        this.score = score;
    }
}

 

using Firebase;
using Firebase.Database;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DBManager : MonoBehaviour
{
    [SerializeField] private string databaseUrl;

    public static DBManager instance;

    private void Awake()
    {
        instance = this;    //싱글톤 
    }

    void Start()
    {
        FirebaseApp.DefaultInstance.Options.DatabaseUrl
            = new System.Uri(databaseUrl);
    }

    public async void SaveData(string json)
    {
        Debug.Log("SaveData");

        //DB의 최상단 디렉토리를 참조 
        DatabaseReference dbRef = FirebaseDatabase.DefaultInstance.RootReference;

        Debug.Log($"dbRef: {dbRef}");

        //비동기 메서드때문에 완료 될때까지 대기
        await dbRef.SetRawJsonValueAsync(json);

        Debug.Log("데이터 저장 완료");
    }
}

 

------------------------- 오류가 계속 나서 다시 시작 ------------------------

이 세개를 빼고 library, obj 같이 생성시 생기는 파일들을 모두 삭제하였다.

Firebase 폴더가 삭제되지 않으면 오픈 윈도우로 들어가서 삭제해보고

그래도 관리자 권한때문에 삭제되지 않으면 재부팅하면 된다.

 

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

public class User
{
    public string username;
    public string email;

    public User()
    {
    }

    public User(string username, string email)
    {
        this.username = username;
        this.email = email;
    }
}

 

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

public class GameInfo
{
    public string userId;
    public int score;

    //생성자 
    public GameInfo(string userId, int score)
    {
        this.userId = userId;
        this.score = score;
    }
}

 

using Firebase.Database;
using Firebase.Extensions;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class GameMain : MonoBehaviour
{
    DatabaseReference mDatabaseRef;
    void Start()
    {
        Debug.Log($"Firebase.FirebaseApp.DefaultInstance: {Firebase.FirebaseApp.DefaultInstance}");
        // Get the root reference location of the database.

        mDatabaseRef = FirebaseDatabase.DefaultInstance.RootReference;

        Debug.Log($"reference : {mDatabaseRef}");

        writeNewUser("hong", "홍길동", "hong@gmail.com");


    }

    private void writeNewUser(string userId, string name, string email)
    {
        User user = new User(name, email);
        string json = JsonUtility.ToJson(user);

        mDatabaseRef.Child("Users").SetRawJsonValueAsync(json);
        CheckAndFixDependenciesAsync();
    }

    private void CheckAndFixDependenciesAsync()
    {
        Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => {
            var dependencyStatus = task.Result;
            if (dependencyStatus == Firebase.DependencyStatus.Available)
            {
                // Create and hold a reference to your FirebaseApp,
                // where app is a Firebase.FirebaseApp property of your application class.
                var app = Firebase.FirebaseApp.DefaultInstance;
                Debug.Log($"app : {app}");


                // Set a flag here to indicate whether Firebase is ready to use by your app.
            }
            else
            {
                UnityEngine.Debug.LogError(System.String.Format(
                  "Could not resolve all Firebase dependencies: {0}", dependencyStatus));
                // Firebase Unity SDK is not safe to use here.
            }
        });
    }

}

 

using Firebase;
using Firebase.Database;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DBManager : MonoBehaviour
{
    [SerializeField] private string databaseUrl;

    public static DBManager instance;

    private void Awake()
    {
        instance = this;    //싱글톤 
    }


    public void Init()
    {
        FirebaseApp.DefaultInstance.Options.DatabaseUrl
            = new System.Uri(databaseUrl);

        FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task => {

            FirebaseApp app = FirebaseApp.DefaultInstance;

            if (app != null)
            {
                Debug.Log("DefaultInstance를 찾을수 없습니다.");
            }
            else
            {
                Debug.Log("초기화가 정상적으로 되었습니다.");
            }
        });
    }

    public async void SaveData(string json)
    {
        Debug.Log("SaveData");

        //DB의 최상단 디렉토리를 참조 
        DatabaseReference dbRef = FirebaseDatabase.DefaultInstance.RootReference;

        Debug.Log($"dbRef: {dbRef}");

        //비동기 메서드때문에 완료 될때까지 대기
        await dbRef.SetRawJsonValueAsync(json);

        Debug.Log("데이터 저장 완료");
    }
}

 

 

 

지정된 파이어베이스 주소로 데이터가 잘 들어옴을 확인할 수 있다.

 

 

 

 

'산대특' 카테고리의 다른 글

2D 3Matchpuzzle - 빈공간 찾기  (0) 2024.05.14
Download Python  (0) 2024.05.08
2D Vertical Shooting Game 모작 최종  (0) 2024.04.08
팬텀로즈스칼렛 모작 최종  (0) 2024.04.08
2D Airplane - 원근감있는 무한 배경 만들  (0) 2024.03.17

실행을 하면 json에 저장된 정보를

역직렬화와 직렬화 가정을 거쳐

info파일에 있는 수치들을 가져온다.

 

 

 

카드 창을 클릭하면 팝업이 나오고 각각의 카드는 클릭을 입력 받을 수 있게 하며,

x버튼을 누르면 팝업이 닫힌다.

 

+ Recent posts