[SKKU DT] 32일차 -유니티 네트워크 -파이어베이스(Firebase) 채팅 시스템 만들기, byte로 Storage에 이미지 올리기

2023. 12. 13. 18:57SKKU DT

728x90
반응형

채팅 UI 만들기

 

 

Content에 [Vertical Layout Group]을 추가하고 ChildForce Expand는 체크 해제 한다.

[Content Size Fitter] - [Vertical Fit]은 Preferred Size로 설정

 

 

messageBox 프리팹 만들기

 

 

 

이전에 썼던 FirebaseController 스크립트에 함수를 추가한다.

public void SendChatMessage()
{
    DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
    string key = chatDB.Push().Key;

    Dictionary<string, string> msgDic = new Dictionary<string, string>();
    msgDic.Add("username", usernameInput.text);
    msgDic.Add("message", messageInput.text);

    Dictionary<string, object> updateMsg = new Dictionary<string, object>();

    updateMsg.Add(key, msgDic);
    chatDB.UpdateChildrenAsync(updateMsg).ContinueWithOnMainThread(task =>
    {
        if (task.IsCompleted)
        {
            Debug.Log("Update Complete");
        }
    });
}

 

 

버튼에 WriteMessage 함수를 매핑하고 실행한다.

 

 

UserName에는 Sam, Text에는 Hello를 넣고 Send를 하면 데이터베이스에 내용이 올라간다.

 

 


 

 

ReadMessage 함수도 사용한다.

public void ReadChatMessage()
{
    DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
    chatDB.GetValueAsync().ContinueWithOnMainThread(task =>
    {
        if (task.IsFaulted)
        {
            Debug.Log("read error");
        }
        if(task.IsCompleted)
        {
            DataSnapshot snapshot = task.Result;
            Debug.Log("" + snapshot.ChildrenCount); //그 밑에 있는 메시지(인덱스1)가 몇 개인가를 센다.
            foreach(var data in snapshot.Children)
            {
            Debug.Log(data.Key + "   " + data.Child("username").Value.ToString() + "   " + data.Child("message").Value.ToString()); //유저 이름과 메시지 내용을 가져온다.
            }
        }
    });
}

Read 버튼에 매핑

 

 

값 바뀔 때, 불러오는 함수.

버튼에 매핑하는 것이 아니고 파이어 베이스 값을 갱신할 때마다 불러온다.

private void FirebaseInit()
{
    auth = FirebaseAuth.DefaultInstance;
    auth.StateChanged += AuthStateChanged; //상태 변화가 있으면 함수를 불러와라

    DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
    chatDB.ValueChanged += ReceiveMessage;
}
public void ReceiveMessage(object sender, ValueChangedEventArgs e)
{
    DataSnapshot snapshot = e.Snapshot;
    Debug.Log("" + snapshot.ChildrenCount);
    foreach(var message in snapshot.Children)
    {
        Debug.Log(message.Key + "   " + message.Child("username").Value.ToString() + "   " + message.Child("message").Value.ToString());
    }
}

 

 


 

 

MessageBox 프리팹 편집을 할 것이다. 메시지가 뜰 때 MessageBox가 생기도록.

 

 

아래의 스크립트를 만들어서 적용하고 InputField 두 개를 연결한다.

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

public class MessageBox : MonoBehaviour
{
    public TextMeshProUGUI usernameLabel;
    public TextMeshProUGUI messageLabel;

    public void SetMessage(string username, string message)
    {
        usernameLabel.text = username;
        messageLabel.text = message;
    }
}

 

 


 

 

채팅 박스를 생성하는 스크립트를 생성한다.

 

 

먼저 멤버 변수를 생성한다.

public MessageBox messageBoxPrefab;
public Transform messageContentTrans;

 

그리고 AddChatBox 함수를 추가해서 Instantiate 기능을 사용한다.

public void AddChatBox(string username, string message)
{
    MessageBox mbox = Instantiate<MessageBox>(messageBoxPrefab, messageContentTrans);
    mbox.SetMessage(username, message);
}

 

 

ReceiveMessage 함수도 업데이트 한다. 방금 만든 AddChatBox 함수를 사용하도록.

public void ReceiveMessage(object sender, ValueChangedEventArgs e)
{
    DataSnapshot snapshot = e.Snapshot;
    Debug.Log("" + snapshot.ChildrenCount);
    foreach(var message in snapshot.Children)
    {
        Debug.Log(message.Key + "   " + message.Child("username").Value.ToString() + "   " + message.Child("message").Value.ToString());
        
        string userName = message.Child("username").Value.ToString();
        string msg = message.Child("message").Value.ToString();
        
        AddChatBox(userName, msg);
    }
}

 

 

전체 FireController 코드

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase.Auth;
using System.Threading.Tasks; //Task문법을 사용할 예정
using TMPro;
using Firebase.Extensions;
using System;
using UnityEngine.SceneManagement;
using Firebase.Database;
using Firebase;

public class FirebaseController : MonoBehaviour
{
    private FirebaseAuth auth;
    private FirebaseUser user;

    public TMP_InputField usernameInput;
    public TMP_InputField messageInput;

    public MessageBox messageBoxPrefab;
    public Transform messageContentTrans;
    void Start()
    {
        Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => //버전이 맞는지 체크
        {
            if(task.Result == Firebase.DependencyStatus.Available) //괜찮으면, 문제 없이 시작된다면,
            {
                FirebaseInit();
            }
            else //괜찮지 않다면
            {
                Debug.LogError("");
            }
        });
    }
    private void FirebaseInit()
    {
        auth = FirebaseAuth.DefaultInstance;
        auth.StateChanged += AuthStateChanged; //상태 변화가 있으면 함수를 불러와라

        DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
        chatDB.ValueChanged += ReceiveMessage;
    }


    private void AuthStateChanged(object sender, EventArgs e)
    {
        FirebaseAuth senderAuth = sender as FirebaseAuth; //무슨 일이 생기면 sender와 EventArgs e가 작용한다.
        if(senderAuth != null) //유저가 있다면
        {
            user = senderAuth.CurrentUser;
            if(user != null) //유저가 무엇을 하려 하면(null이 아니면)
            {
                Debug.Log(user.UserId);
            }
        }
    }

    /*
    public void SignIn()
    {
        SignInAnonymous();
    }
    private Task SignInAnonymous()
    {
        return auth.SignInAnonymouslyAsync().ContinueWithOnMainThread(task =>
        {
            if(task.IsFaulted)
            {
                Debug.Log("SignIn fail");
            }
            else if(task.IsCompleted)
            {
                Debug.Log("SignIn complete");
                SceneManager.LoadScene(1);
            }
        });
    }
    */
    
    public void ReadChatMessage()
    {
        DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
        chatDB.GetValueAsync().ContinueWithOnMainThread(task =>
        {
            if (task.IsFaulted)
            {
                Debug.Log("read error");
            }
            if(task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                Debug.Log("" + snapshot.ChildrenCount); //그 밑에 있는 메시지(인덱스1)가 몇 개인가를 센다.
                foreach(var data in snapshot.Children)
                {
                Debug.Log(data.Key + "   " + data.Child("username").Value.ToString() + "   " + data.Child("message").Value.ToString()); //유저 이름과 메시지 내용을 가져온다.
                }
            }
        });
    }

    public void SendChatMessage()
    {
        DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
        string key = chatDB.Push().Key;

        Dictionary<string, string> msgDic = new Dictionary<string, string>();
        msgDic.Add("username", usernameInput.text);
        msgDic.Add("message", messageInput.text);

        Dictionary<string, object> updateMsg = new Dictionary<string, object>();

        updateMsg.Add(key, msgDic);
        chatDB.UpdateChildrenAsync(updateMsg).ContinueWithOnMainThread(task =>
        {
            if (task.IsCompleted)
            {
                Debug.Log("Update Complete");
            }
        });
    }

    public void ReceiveMessage(object sender, ValueChangedEventArgs e)
    {
        DataSnapshot snapshot = e.Snapshot;
        Debug.Log("" + snapshot.ChildrenCount);
        foreach(var message in snapshot.Children)
        {
            Debug.Log(message.Key + "   " + message.Child("username").Value.ToString() + "   " + message.Child("message").Value.ToString());
            
            string userName = message.Child("username").Value.ToString();
            string msg = message.Child("message").Value.ToString();
            
            AddChatBox(userName, msg);
        }
    }

    public void AddChatBox(string username, string message)
    {
        MessageBox mbox = Instantiate<MessageBox>(messageBoxPrefab, messageContentTrans);
        mbox.SetMessage(username, message);
    }
}

 

 

스크립트를 적용하고 컴포넌트들을 연결하면 

 

 

메시지가 잘 나온다. 하지만 새로 메시지를 넣으면 이전 메시지가 다시 표시되고 새 메시지가 그 밑에 표시되어 중복되는 값이 발생한다.

 

 

중복되는 값을 해결하기 위해서는, FirebaseInit() 함수에서 chatDB.LimitToLast(1)로 가장 최근 데이터만 가져오게 설정하면 된다.

private void FirebaseInit()
{
    auth = FirebaseAuth.DefaultInstance;
    auth.StateChanged += AuthStateChanged; //상태 변화가 있으면 함수를 불러와라

    DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
    chatDB.LimitToLast(1).ValueChanged += ReceiveMessage;
}

 

 

FirebaseController 전체 코드

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase.Auth;
using System.Threading.Tasks; //Task문법을 사용할 예정
using TMPro;
using Firebase.Extensions;
using System;
using UnityEngine.SceneManagement;
using Firebase.Database;
using Firebase;

public class FirebaseController : MonoBehaviour
{
    private FirebaseAuth auth;
    private FirebaseUser user;

    public TMP_InputField usernameInput;
    public TMP_InputField messageInput;

    public MessageBox messageBoxPrefab;
    public Transform messageContentTrans;
    void Start()
    {
        Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => //버전이 맞는지 체크
        {
            if(task.Result == Firebase.DependencyStatus.Available) //괜찮으면, 문제 없이 시작된다면,
            {
                FirebaseInit();
            }
            else //괜찮지 않다면
            {
                Debug.LogError("");
            }
        });
    }
    private void FirebaseInit()
    {
        auth = FirebaseAuth.DefaultInstance;
        auth.StateChanged += AuthStateChanged; //상태 변화가 있으면 함수를 불러와라

        DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
        chatDB.LimitToLast(1).ValueChanged += ReceiveMessage;
    }


    private void AuthStateChanged(object sender, EventArgs e)
    {
        FirebaseAuth senderAuth = sender as FirebaseAuth; //무슨 일이 생기면 sender와 EventArgs e가 작용한다.
        if(senderAuth != null) //유저가 있다면
        {
            user = senderAuth.CurrentUser;
            if(user != null) //유저가 무엇을 하려 하면(null이 아니면)
            {
                Debug.Log(user.UserId);
            }
        }
    }
    
    public void ReadChatMessage()
    {
        DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
        chatDB.GetValueAsync().ContinueWithOnMainThread(task =>
        {
            if (task.IsFaulted)
            {
                Debug.Log("read error");
            }
            if(task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                Debug.Log("" + snapshot.ChildrenCount); //그 밑에 있는 메시지(인덱스1)가 몇 개인가를 센다.
                foreach(var data in snapshot.Children)
                {
                Debug.Log(data.Key + "   " + data.Child("username").Value.ToString() + "   " + data.Child("message").Value.ToString()); //유저 이름과 메시지 내용을 가져온다.
                }
            }
        });
    }

    public void SendChatMessage()
    {
        DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
        string key = chatDB.Push().Key;

        Dictionary<string, string> msgDic = new Dictionary<string, string>();
        msgDic.Add("username", usernameInput.text);
        msgDic.Add("message", messageInput.text);

        Dictionary<string, object> updateMsg = new Dictionary<string, object>();

        updateMsg.Add(key, msgDic);
        chatDB.UpdateChildrenAsync(updateMsg).ContinueWithOnMainThread(task =>
        {
            if (task.IsCompleted)
            {
                Debug.Log("Update Complete");
            }
        });
    }

    public void ReceiveMessage(object sender, ValueChangedEventArgs e)
    {
        DataSnapshot snapshot = e.Snapshot;
        Debug.Log("" + snapshot.ChildrenCount);
        foreach(var message in snapshot.Children)
        {
            Debug.Log(message.Key + "   " + message.Child("username").Value.ToString() + "   " + message.Child("message").Value.ToString());
            
            string userName = message.Child("username").Value.ToString();
            string msg = message.Child("message").Value.ToString();
            
            AddChatBox(userName, msg);
        }
    }

    public void AddChatBox(string username, string message)
    {
        MessageBox mbox = Instantiate<MessageBox>(messageBoxPrefab, messageContentTrans);
        mbox.SetMessage(username, message);
    }
}

 

가장 최근 메시지만 잘 들어온다.

 

 


 

 

가장 최근 메시지가 화면 가운데로 위치하도록 수정

 

멤버 변수  추가

public ScrollRect scrollRect;

 

AddChatBox 함수에 코루틴 추가, 코루틴 함수 추가

public void AddChatBox(string username, string message)
{
    MessageBox mbox = Instantiate<MessageBox>(messageBoxPrefab, messageContentTrans);
    mbox.SetMessage(username, message);

    StartCoroutine(AdjustScrollPosition(mbox.GetComponent<RectTransform>())); //새로운 채팅 박스가 만들어지면 시작 되도록
}

private IEnumerator AdjustScrollPosition(RectTransform newMessagBox)
{
    yield return new WaitForEndOfFrame();

    float newY = -newMessagBox.anchoredPosition.y - (newMessagBox.sizeDelta.y * newMessagBox.pivot.y);
    float contentHeight = messageContentTrans.GetComponent<RectTransform>().sizeDelta.y;
    float ScrollViewHeight = scrollRect.GetComponent<RectTransform>().sizeDelta.y;
    newY = newY - (ScrollViewHeight * 0.5f);

    messageContentTrans.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, newY);
}

Scroll Rect에 Scroll View를 넣는다.

 

 

전체 코드

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Firebase.Auth;
using System.Threading.Tasks; //Task문법을 사용할 예정
using TMPro;
using Firebase.Extensions;
using System;
using UnityEngine.SceneManagement;
using Firebase.Database;
using Firebase;
using UnityEngine.UI;

public class FirebaseController : MonoBehaviour
{
    private FirebaseAuth auth;
    private FirebaseUser user;

    public TMP_InputField usernameInput;
    public TMP_InputField messageInput;

    public MessageBox messageBoxPrefab;
    public Transform messageContentTrans;

    public ScrollRect scrollRect;
    void Start()
    {
        Firebase.FirebaseApp.CheckAndFixDependenciesAsync().ContinueWithOnMainThread(task => //버전이 맞는지 체크
        {
            if(task.Result == Firebase.DependencyStatus.Available) //괜찮으면, 문제 없이 시작된다면,
            {
                FirebaseInit();
            }
            else //괜찮지 않다면
            {
                Debug.LogError("");
            }
        });
    }
    private void FirebaseInit()
    {
        auth = FirebaseAuth.DefaultInstance;
        auth.StateChanged += AuthStateChanged; //상태 변화가 있으면 함수를 불러와라

        DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
        chatDB.LimitToLast(1).ValueChanged += ReceiveMessage;
    }


    private void AuthStateChanged(object sender, EventArgs e)
    {
        FirebaseAuth senderAuth = sender as FirebaseAuth; //무슨 일이 생기면 sender와 EventArgs e가 작용한다.
        if(senderAuth != null) //유저가 있다면
        {
            user = senderAuth.CurrentUser;
            if(user != null) //유저가 무엇을 하려 하면(null이 아니면)
            {
                Debug.Log(user.UserId);
            }
        }
    }

    /*
    public void SignIn()
    {
        SignInAnonymous();
    }
    private Task SignInAnonymous()
    {
        return auth.SignInAnonymouslyAsync().ContinueWithOnMainThread(task =>
        {
            if(task.IsFaulted)
            {
                Debug.Log("SignIn fail");
            }
            else if(task.IsCompleted)
            {
                Debug.Log("SignIn complete");
                SceneManager.LoadScene(1);
            }
        });
    }
    */
    
    public void ReadChatMessage()
    {
        DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
        chatDB.GetValueAsync().ContinueWithOnMainThread(task =>
        {
            if (task.IsFaulted)
            {
                Debug.Log("read error");
            }
            if(task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                Debug.Log("" + snapshot.ChildrenCount); //그 밑에 있는 메시지(인덱스1)가 몇 개인가를 센다.
                foreach(var data in snapshot.Children)
                {
                Debug.Log(data.Key + "   " + data.Child("username").Value.ToString() + "   " + data.Child("message").Value.ToString()); //유저 이름과 메시지 내용을 가져온다.
                }
            }
        });
    }

    public void SendChatMessage()
    {
        DatabaseReference chatDB = FirebaseDatabase.DefaultInstance.GetReference("ChatMessage");
        string key = chatDB.Push().Key;

        Dictionary<string, string> msgDic = new Dictionary<string, string>();
        msgDic.Add("username", usernameInput.text);
        msgDic.Add("message", messageInput.text);

        Dictionary<string, object> updateMsg = new Dictionary<string, object>();

        updateMsg.Add(key, msgDic);
        chatDB.UpdateChildrenAsync(updateMsg).ContinueWithOnMainThread(task =>
        {
            if (task.IsCompleted)
            {
                Debug.Log("Update Complete");
            }
        });
    }

    public void ReceiveMessage(object sender, ValueChangedEventArgs e)
    {
        DataSnapshot snapshot = e.Snapshot;
        Debug.Log("" + snapshot.ChildrenCount);
        foreach(var message in snapshot.Children)
        {
            Debug.Log(message.Key + "   " + message.Child("username").Value.ToString() + "   " + message.Child("message").Value.ToString());
            
            string userName = message.Child("username").Value.ToString();
            string msg = message.Child("message").Value.ToString();
            
            AddChatBox(userName, msg);
        }
    }

    public void AddChatBox(string username, string message)
    {
        MessageBox mbox = Instantiate<MessageBox>(messageBoxPrefab, messageContentTrans);
        mbox.SetMessage(username, message);

        StartCoroutine(AdjustScrollPosition(mbox.GetComponent<RectTransform>())); //새로운 채팅 박스가 만들어지면 시작 되도록
    }

    private IEnumerator AdjustScrollPosition(RectTransform newMessagBox)
    {
        yield return new WaitForEndOfFrame();

        float newY = -newMessagBox.anchoredPosition.y - (newMessagBox.sizeDelta.y * newMessagBox.pivot.y);
        float contentHeight = messageContentTrans.GetComponent<RectTransform>().sizeDelta.y;
        float ScrollViewHeight = scrollRect.GetComponent<RectTransform>().sizeDelta.y;
        newY = newY - (ScrollViewHeight * 0.5f);

        messageContentTrans.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, newY);
    }
}

 

 

새로운 메시지를 Send할 때마다 새로운 메시지가 올라온다.

 

 


 

 

프로젝트 빌드

 

작동은 잘 된다.

 

 

만든 프로젝트를 공유하기 위해서는 _Data 폴더와 exe 파일을 압축해서 보내면 된다.

같은 빌드 파일을 가지고 있다면 다른 사람들과 채팅이 가능하다.

많이 치다보면 글씨가 이상해지는 버그가 있는 것 같다.

 

 

핸드폰 화면에 맞춘다면 해당 해상도로 바꾸고 UI의 크기도 거기에 맞추면 된다.

 

 

WebGL 빌드도 시도한다.

[Firebase] - [Plugins] 폴더의 퍼즐 모양 dll을 전부 선택한 후 WebGL을 체크한다.

 

 


 

 

FirebaseStorage 이미지 업로드 다운로드

using Firebase;
using Firebase.Firestore;
using Firebase.Storage;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.IO;
using Firebase.Extensions;

public class ImageUploadAndDownload : MonoBehaviour
{
    public RawImage rawImage;
    public TMP_InputField imageNameInputField;

    private FirebaseStorage storage;
    private StorageReference storageReference;
    private FirebaseFirestore firestore;

    private string uploadedImageUrl;

    // Start is called before the first frame update
    void Start()
    {
        FirebaseApp app = FirebaseApp.DefaultInstance;
        storage = FirebaseStorage.DefaultInstance;
        storageReference = storage.GetReference("");
        firestore = FirebaseFirestore.GetInstance(app);
    }

    public void UploadImage()
    {
        string imageName = imageNameInputField.name;
        if(string.IsNullOrEmpty(imageName))
        {
            Debug.Log("No Image Selected");
            return;
        }

        // 파일 선택 다이얼로그 열기
        string imagePath = UnityEditor.EditorUtility.OpenFilePanel("Select Image", "", "png, jpg, jpeg");
        if(string.IsNullOrEmpty(imagePath))
        {
            Debug.Log("No Image Selected");
            return;
        }
        byte[] imageBytes = File.ReadAllBytes(imagePath);

        // Firebase Storage에 이미지 업로드
        StorageReference imageRef = storageReference.Child(imagePath);

        imageRef.PutBytesAsync(imageBytes).ContinueWith(task => 
        {
            if (task.IsCompleted && task.IsFaulted && task.IsFaulted)
            {
                Debug.Log("Image Upload!");
            }

            // 업로드된 이미지의 다운로드 URL을 가져와 Firstore에 정보 저장
            imageRef.GetDownloadUrlAsync().ContinueWithOnMainThread(downloadTask => 
            { 
                if(downloadTask.IsCompleted && downloadTask.IsFaulted && downloadTask.IsCanceled)
                {
                    uploadedImageUrl = downloadTask.Result.ToString();

                    // Firestore에 이미지 정보 저장
                    DocumentReference imageInfoRef = firestore.Collection("image").Document(imageName);
                    var data = new Dictionary<string, object>
                    {
                        {"imageName", imageName }, 
                        {"imageURL", uploadedImageUrl}
                    };
                    imageInfoRef.SetAsync(data).ContinueWithOnMainThread(setTask => 
                    { 
                        if (setTask.IsCanceled && setTask.IsFaulted && setTask.IsCompleted)
                        {
                            Debug.Log("Image info addede to Firestore");
                        }
                        else
                        {
                            Debug.LogError("Failed to get download URL: " + downloadTask.Exception);
                        }
                    });
                }
                else
                {
                    Debug.LogError("Image upload failed");
                }
            });
            
        });
    }
}

Canvas에서 Raw Image하나, InputField 하나 만들어서 넣는다. 버튼에 UploadImage 함수를 연결하고 실행하면,

 

버튼을 눌렀을 때 이미지 선택이 가능하다.

이미지 선택 팝업까지 뜨는 데는 성공. 하지만 이미지를 넣으려면 Fail...

 

 

 


 

 

새로운 스크립트 생성... 이번에는 byte를 이용해서 Firebase Storage에 이미지를 올리는 스크립트이다.

using Firebase.Storage;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;

public class FireBaseManager : MonoBehaviour
{
    FirebaseStorage storage;
    StorageReference storageRef;

    private void Start()
    {
        storage = FirebaseStorage.DefaultInstance;
        storageRef = storage.RootReference;
    }

    public void UploadFiles()
    {
        var customBytes = new byte[] { };

        StorageReference riversRef = storageRef.Child("C:/tmp/low_city.png");

        riversRef.PutBytesAsync(customBytes).ContinueWith((Task<StorageMetadata> task) =>
        {
            if(task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
            }
            else
            {
                StorageMetadata metadata = task.Result;
                string md5Hash = metadata.Md5Hash;
                Debug.Log("Finished uploading...");
                Debug.Log("md5 hash = " + md5Hash);
            }
        });
    }
}

Firebase Storage에 같은 폴더 경로로 파일이 들어가있다.

 

 

위의 스크립트 중 Upload Files() 함수 부분을 수정하면,

public void UploadFiles() // 파이어베이스 업로드
{
    var customBytes = System.IO.File.ReadAllBytes("c:/tmp/low_city.png");

    // Create a reference to the file you want to upload
    StorageReference riversRef = FirebaseStorage.DefaultInstance.GetReference("").Child("c:/tmp/low_city.png");

    // Upload the file to the path
    riversRef.PutBytesAsync(customBytes).ContinueWith((Task<StorageMetadata> task) =>
    {
        if (task.IsFaulted || task.IsCanceled)
        {
            Debug.Log(task.Exception.ToString());
        }
        else
        {
            StorageMetadata metadata = task.Result;
            string md5hash = metadata.Md5Hash;
            Debug.Log("finished file uploading...");
            Debug.Log($"md5hash: {md5hash}");
        }
    });
}

 

using Firebase.Storage;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;

public class FireBaseManager : MonoBehaviour
{
    FirebaseStorage storage;
    StorageReference storageRef;

    private void Start()
    {
        storage = FirebaseStorage.DefaultInstance;
        storageRef = storage.RootReference;
    }

    public void UploadFiles() // 파이어베이스 업로드
    {
        var customBytes = System.IO.File.ReadAllBytes("c:/tmp/low_city.png");

        // Create a reference to the file you want to upload
        StorageReference riversRef = FirebaseStorage.DefaultInstance.GetReference("").Child("c:/tmp/low_city.png");

        // Upload the file to the path
        riversRef.PutBytesAsync(customBytes).ContinueWith((Task<StorageMetadata> task) =>
        {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
            }
            else
            {
                StorageMetadata metadata = task.Result;
                string md5hash = metadata.Md5Hash;
                Debug.Log("finished file uploading...");
                Debug.Log($"md5hash: {md5hash}");
            }
        });
    }
}

 

콘솔 창에 Debug도 잘 찍히며 Storage에도 파일이 경로와 같이 잘 올라간 것을 볼 수 있다.

728x90
반응형