Created
October 11, 2022 21:39
-
-
Save luffy-yu/96baa6850d16e00f4b82353542671571 to your computer and use it in GitHub Desktop.
Unity File Syncer Demo Based On Pun2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.IO; | |
using UnityEngine; | |
using Photon.Pun; | |
using Photon.Realtime; | |
public class PunFileSyncer : MonoBehaviour | |
{ | |
public PhotonView photonView; | |
public string fileNameToSend; // local filename to send | |
public string fileNameToSave; // remote filename to save | |
// Start is called before the first frame update | |
void Start() | |
{ | |
Debug.LogWarning($"Local View ID: {photonView.ViewID}"); | |
if (fileNameToSave == null || fileNameToSend == null) | |
{ | |
Debug.LogError("Please set fileNameToSend and fileNameToSave first"); | |
return; | |
} | |
if (PhotonNetwork.IsMasterClient) | |
{ | |
Debug.LogError("Master Sends file."); | |
SendFile(fileNameToSave, ReadFile(fileNameToSend)); | |
} | |
} | |
byte[] ReadFile(string filename) | |
{ | |
if (System.IO.File.Exists(filename)) | |
{ | |
return File.ReadAllBytes(filename); | |
} | |
else | |
{ | |
Debug.LogError($"Can't find file {filename}"); | |
return new byte[] { }; | |
} | |
} | |
// Update is called once per frame | |
void Update() | |
{ | |
} | |
[PunRPC] | |
void ChatMessage(string fileName, byte[] content) | |
{ | |
if (!PhotonNetwork.IsMasterClient) | |
{ | |
string path = Path.Combine(Application.persistentDataPath, fileName); | |
Debug.LogWarning($"File was saved to {path}"); | |
File.WriteAllBytes(path, content); | |
} | |
} | |
public void SendFile(string fileName, byte[] content) | |
{ | |
Debug.LogError($"Content length: {content.Length}"); | |
photonView.RPC(nameof(ChatMessage), RpcTarget.Others, fileName, content); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment