Why does the host get random colors to generate but the joining players dont get the random colors,How to Sync 2 ball's colors in unity?
im using Mirror to make a multiplayer game and i cant get the server to send out the color information to the players joining
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class PlayerConnectionObject : NetworkBehaviour {
public GameObject PlayerUnitPrefab;
[SyncVar(hook = nameof(OnPlayerNameChanged))]
public string PlayerName = "Anonymous";
void Start () {
if( isLocalPlayer == false )
{
return;
}
CmdSpawnMyUnit();
string n = "Player" + Random.Range(1, 100);
CmdChangePlayerName(n);
}
void Update () {
if( isLocalPlayer == false )
{
return;
}
}
void OnPlayerNameChanged(string oldName, string newName)
{
Debug.Log("OnPlayerNameChanged: OldName: "+PlayerName+" NewName: " + newName);
PlayerName = newName;
gameObject.name = "PlayerConnectionObject ["+newName+"]";
}
[Command]
void CmdSpawnMyUnit()
{
GameObject go = Instantiate(PlayerUnitPrefab);
go.GetComponentInChildren<Renderer>().material.color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f));
NetworkServer.Spawn(go, connectionToClient);
}
[Command]
void CmdChangePlayerName(string n)
{
Debug.Log("CmdChangePlayerName: " + n);
PlayerName = n;
}
}
,Im trying to have the spheres spawn in as a random color and they do fine for the host player, but when the other players join all the balls are the basic material color (red)
Answer by Sercon · Oct 14, 2020 at 10:52 PM
I am quite new to mirror but from what I understand, and did myself for my spawnsystem, you do not want the spawning to happen on the server side with the [Command] attribute. You want to make a prefab which will be spawned by your networkmanager and that has a script on it which manages the spawning of the PlayerUnitPrefab.
Example:
public void SpawnPlayer(NetworkConnection conn)
{
Transform spawnPoint = spawnPoints.ElementAtOrDefault(nextSpawnPoint);
GameObject playerInstance = Instantiate(PlayerPrefab, spawnPoints[nextSpawnPoint].position, spawnPoints[nextSpawnPoint].rotation);
NetworkServer.Spawn(playerInstance, conn);
nextSpawnPoint++;
}
This function is called by instantiating the playerSpawnSystem in the networkmanager when the game starts:
GameObject playerSpawnSystemInstance = Instantiate(playerSpawnSystem);
NetworkServer.Spawn(playerSpawnSystemInstance);
Hope it helps :)
PS: I would recommend against using isLocalPlayer, instead use hasAuthority. Also quick tip, if you want to say:
if ( isLocalPlayer == false){}
You can write it as:
if (!isLocalPlayer){}
For checking if something is "true":
if (isLocalPlayer){}
But that's just preference I guess.