Skip to content

Instantly share code, notes, and snippets.

@luffy-yu
Created October 11, 2022 21:39
Show Gist options
  • Save luffy-yu/96baa6850d16e00f4b82353542671571 to your computer and use it in GitHub Desktop.
Save luffy-yu/96baa6850d16e00f4b82353542671571 to your computer and use it in GitHub Desktop.
Unity File Syncer Demo Based On Pun2
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