ClientRPC running on host, not client. Please help! (Code Included)
Ok so I am working on a game that will have a StorageBox that will have random loot in it. The box works just fine, meaning loot is spawned, populated, etc. Where I got stuck for days is I'm trying to set a variable isBusy on the box so that if a player has it open, other players cannot open it. I'm afraid I may be going about this all wrong, surely it cannot be this hard!
StorageBox is a prefab that has StorageInventory.cs script on it. Player has PlayerMove.cs on it.
Here is the code used: PlayerMove:
void Update () {
if (!isLocalPlayer)
return;
var x = Input.GetAxis("Horizontal")*0.1f;
var z = Input.GetAxis("Vertical")*0.1f;
transform.Translate(x, 0, z);
RaycastHit hit;
float theDistance;
Vector3 forward = transform.TransformDirection (Vector3.forward) * 10;
// E Key Handler
if (Input.GetKeyDown (inputManagerDatabase.StorageKeyCode)) {
if (Physics.Raycast (transform.position, (forward), out hit)) {
theDistance = hit.distance;
if (theDistance <= 1.6f && hit.collider.gameObject.tag == "StorageBoxGeneric") {
CmdStorageBoxGenericBusy(hit.collider.gameObject);
}
}
}
// End E Key Handler
}
[Command]
void CmdStorageBoxGenericBusy(GameObject g) {
STI = g.GetComponent<StorageInventory> ();
if (STI.isBusy == true) {
STI.CmdSetBusy (false);
STI.RpcOpenInventoryWithTimer();
} else {
STI.CmdSetBusy (true);
STI.RpcOpenInventoryWithTimer();
}
}
StorageInventory:
public void CmdSetBusy(bool b) {
isBusy = b;
showStorage = b;
}
[ClientRpc]
public void RpcOpenInventoryWithTimer() {
if (showStorage == true && isBusy == true) {
Debug.Log ("Opening");
//startTimer = Time.time;
//showTimer = true;
//yield return new WaitForSeconds (timeToOpenStorage);
inv.ItemsInInventory.Clear ();
inventory.SetActive (true);
addItemsToInventory ();
//showTimer = false;
//if (timer != null)
//timer.SetActive (false);
} else {
Debug.Log ("Closing");
storageItems.Clear ();
setListofStorage ();
inventory.SetActive (false);
inv.deleteAllItems ();
tooltip.deactivateTooltip ();
}
}
The problem is when player2 (A client) opens the box, it opens on player1 (The host) screen only. The host can open it fine, but the player cannot.
So I guess the question I have specifically is this: When any player (From the PlayerMove.cs script) sends a [Command] to run code on the server, how can I have that code [ClientRPC] run ONLY on the player that called it? Again I may be going about this all wrong, but I need help please! Thank you!
Also even though CmdSetBusy is named that way, it is NOT a [Command]. It was when i was trying something else, but is not now. I just never removed the Cmd in the routine name.
Your answer
