Astrydax
Astrydax

Reputation: 465

Sync random colors for players across network with PUN2 unity

I'm using PUN2, When a player connects, I want their sprite render to be a random color, and for that color to be synced for all other players.

For some reason the following code prevents the other players from appearing on the screen however I can still see the player objects in the inspector. If I remove the RPC call, I can see the other players fine, but their colors don't sync.

public class Player : MonoBehaviour
{
 private PhotonView myPV;
 public string nickname;
 public Color color;    
 // Start is called before the first frame update
 void Start()
 {
     myPV = GetComponent<PhotonView>();
     if (myPV.IsMine)
     {
         gameObject.GetComponentInChildren<Camera>().enabled = true;
         gameObject.GetComponentInChildren<TopDownCharacter>().enabled = true;
         color = Random.ColorHSV();
         myPV.RPC("RPC_SendColor", RpcTarget.AllBuffered);
     }
 }


 [PunRPC]
 void RPC_SendColor()
 {
     gameObject.GetComponentInChildren<SpriteRenderer>().color = color;
 }

}

Upvotes: 2

Views: 2498

Answers (2)

Pok&#233;mon master
Pok&#233;mon master

Reputation: 11

Use ColorUtility to convert it to HTML String and retrieve it back like so... DO NOT MISS THE "#"

ColorUtility.ToHtmlStringRGBA(color)
Color newColor;
if (ColorUtility.TryParseHtmlString("#" + color, out newColor))
{
    print("New Color " +  newColor.ToString());
}

Upvotes: 0

JohnTube
JohnTube

Reputation: 1812

Thank you for choosing Photon!

For some reason the following code prevents the other players from appearing on the screen however I can still see the player objects in the inspector.

I think enabling Camera for the local player is the culprit here. Try commenting out the line:

//gameObject.GetComponentInChildren<Camera>().enabled = true;

If I remove the RPC call, I can see the other players fine, but their colors don't sync.

Having the Color as a field of the RPC script is not enough to synchronize it as this is not how it should be done. You should send the Color values (RGB float values) or send Color object after registering Color as custom Photon type.

        color = Random.ColorHSV();
        this.photonView.RPC("RPC_SendColor", RpcTarget.All, new Vector3(color.r, color.g, color.b));

 // [...]

    [PunRPC]
    private void RPC_SendColor(Vector3 randomColor)
    {
         Color color = new Color(randomColor.x, randomColor.y, randomColor.z);
         gameObject.GetComponentInChildren<SpriteRenderer>().color = color;
    }

Upvotes: 2

Related Questions