I am trying to find a way to have a “generic” player prefab as the player (empty with a character controller and movement script) and then attach and parent other prefabs to the player once it’s spawned on the network so each player has a unique character but this seems extremely difficult to do as I’ve been hammering on this problem for a week now.
I have a method to instantiate and parent the character prefab to the player prefab and it appears to work on the server (just a server, not a host) and a client. However as soon as a second client connects, the first client appears to lose it’s parenting and leaves the character prefab at it’s last location but the player prefab continues to move around and stays in sync. On the server (in the editor) I can see that the character prefab is still parented and moving with the player prefab, it just doesn’t seem to be syncing this with all other clients.
I don’t know how else to have unique characters and I will need to be able to parent prefabs like armor, weapons, etc. to the player prefab, surely other people are trying to accomplish this same goal. Below is the simple code attached to the player prefab. Any help is appreciated!
void Start() { if (!isLocalPlayer) { return; }
baseModelLocation = GameObject.Find("LoginSystem").GetComponent<LoginMenu>().baseModelLocation; // assign the directory of the base model
CmdSpawnItem(baseModelLocation);
}
[Command]
void CmdSpawnItem(string itemLocation){
var itemPrefab = Resources.Load(itemLocation) as GameObject;
var itemGameObject = (GameObject)Instantiate(itemPrefab, transform.position, Quaternion.identity);
NetworkServer.Spawn(itemGameObject);
itemGameObject.transform.SetParent(transform); // this parents it on the server.
GetComponent<MyPlayerController>().playerAnim = itemGameObject.GetComponent<Animator>(); // this assigns the animator on the server.
RpcSetParent(itemGameObject); // parents on client, doesn't seem to update on new client when it connects but updates on server when moving.
RpcSetAnim(itemGameObject);
}
// This parents the player model to the player spawn prefab:
[ClientRpc]
void RpcSetParent(GameObject item) { item.transform.SetParent(transform); }
// This assigns the animator to the controller script in the spawn prefab:
[ClientRpc]
void RpcSetAnim(GameObject item) { GetComponent<MyPlayerController>().playerAnim = item.GetComponent<Animator>(); }