RaZ
RaZ

Reputation: 265

ClientRpc Function not being carried out on all clients in Unity3d c#

Currently I am working on a networked 2d platformer game. I have a script that is supposed to instantiate the players jetpack called JetpackManager. However when the player is spawned into the scene the code only spawns a jetpack into the hosts scene and not into the clients' scenes. This results in only the hosts scene working properly while all the players in the clients' scenes have no jetpacks. This is my code for the JetpackManager:

using UnityEngine;
using UnityEngine.Networking;

public class JetpackManager : NetworkBehaviour {

[SerializeField]
private Jetpack[] jetpacks;

[SerializeField]
private Transform jetPackHold;

private PlayerController playerController;

private Jetpack currentJetpack;

void Start(){
    playerController = GetComponent<PlayerController> ();

    if (isLocalPlayer) {
        CmdEquipJetpack (0);
    }
}

[Command]
void CmdEquipJetpack(int jetpackNumber){
    RpcEquipJetpack (jetpackNumber);
}

[ClientRpc]
void RpcEquipJetpack(int jetpackNumber){

    if (currentJetpack != null) {
        Destroy (currentJetpack.gameObject);
    }

    currentJetpack = Instantiate (jetpacks[jetpackNumber], jetPackHold.position, jetPackHold.rotation);
    currentJetpack.transform.SetParent (jetPackHold);

    playerController.InitialiseJetpackVariables (currentJetpack);
}

}

So essentially my problem is that the code within the RpcEquipJetpack Function is for some reason only being called on the host and not on any of the clients.

Upvotes: 0

Views: 827

Answers (1)

Muhammad Faizan Khan
Muhammad Faizan Khan

Reputation: 10551

You should instantiate Network object with network class

Network.Instantiate

Network instantiate a prefab.

The given prefab will be instanted on all clients in the game. Synchronization is automatically set up so there is no extra work involved. The position, rotation and network group number are given as parameters. Note that in the example below there must be something set to the playerPrefab in the Editor. You can read more about instantiations in the object reference Object.Instantiate.

Upvotes: 1

Related Questions