I am a beginner in unity netcode and multiplayer in general.
trying to make a project where a user can upload image files and those files are then placed on a 3d cube as its texture. I handled loading the image using the NativeGallery package , but it is not syncing over the network.
I have attached NetworkObject and NetworkTransform components to the cube and also added it to the NetworkPrefabList
i tried using serverrpc but im pretty sure i messed it up.
here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
using UnityEngine.Networking;
public class FilePicker : NetworkBehaviour
{
public string finalPath;
public GameObject ImageCube;
Material ImageCubeMat;
Texture2D ImageCubeTexture;
public void PickImage()
{
NativeGallery.Permission permission = NativeGallery.GetImageFromGallery((path) =>
{
Debug.Log("Image path: " + path);
if (path != null)
{
// Create Texture from selected image
Texture2D texture = NativeGallery.LoadImageAtPath(path);
if (texture == null)
{
Debug.Log("Couldn't load texture from " + path);
return;
}
ImageCubeTexture = texture;
Material material = ImageCube.GetComponent<Renderer>().material;
if (!material.shader.isSupported)
material.shader = Shader.Find("Legacy Shaders/Diffuse");
ImageCubeMat = material;
SetImageServerRpc();
}
});
Debug.Log("Permission result: " + permission);
}
[ServerRpc]
public void SetImageServerRpc()
{
ImageCubeMat.mainTexture = ImageCubeTexture;
}
}
Note: the texture is only changing on the user’s side.
please give me suggestions for fixing this and making the texture change sync . :(
You can’t (easily) sync a Texture2D object. Instead you should send the image itself. Use File.ReadAllBytes to load it into a byte[ ] and send that as a parameter in the ServerRPC method.
Note that this may fail depending on the size of the byte[ ]. In earlier versions of NGO this limit was about 30k but I’ve heard this has been raised, but I don’t know by how much. If sending fails you may have to send it in chunks via repeated RPC calls, or use an external webserver or service to upload the image to, then just send the URL with the ServerRPC respectively ClientRPC so every client can download that image by itself.
Essentially it initiates a transfer and sends the expected size, then sends a small chunk and waits for the acknowledgment. Repeat until all bytes are transferred.
Btw, once a file is transferred you should save it locally. That way you can avoid retransmitting existing files by first sending the file’s CRC32 hash to the server, and having the server ask every client to check whether they have a file with the same hash.