- Home /
Switching weapons in PhotonNetwork
Can someone please help me? I have simple script which is disabled and when I spawn player, it will be enabled. But still, when I switch weapon, other players still see the old one. Can someone please help me?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TPKnifePistol : MonoBehaviour {
public GameObject gun;
public GameObject knife;
public GameObject pistol;
// Use this for initialization
void Start () {
gun.SetActive (true);
knife.SetActive (false);
pistol.SetActive (false);
}
// Update is called once per frame
void Update () {
if (Input.GetKey ("2")) {
gun.SetActive (false);
knife.SetActive (false);
pistol.SetActive (true);
}
if (Input.GetKey ("3")) {
gun.SetActive (false);
knife.SetActive (true);
pistol.SetActive (false);
}
}
public void LoadByIndex()
{
gun.SetActive (true);
knife.SetActive (false);
pistol.SetActive (false);
}
}
Answer by ChristianSimon · Apr 17, 2018 at 10:29 AM
Hi,
you have to synchronize the selected weapon. you can do this for example by using a RPC call. Firstly you will need a reference to the attached PhotonView component of the game object. Therefore add private PhotonView pView;
to the class. Then in your Start (or Awake) function get the reference to the component by using pView = GetComponent<PhotonView>();
. Having this reference is important for the Update function as well. Here you have to add the if (!pView.isMine) { return; }
condition at the beginning. This helps avoiding handling the Input on objects that are not owned by the local client (otherwise a client will switch the weapon for each other client as well). Whenever a client has selected a new weapon, he can send the 'index' by using a RPC, for example pView.RPC("SwitchWeapon", PhotonTargets.All, 2);
. This tells every client to call the function "SwitchWeapon" with index 2 on the certain game object. To handle this RPC call you will need a [PunRPC] marked function named "SwitchWeapon" which accepts one int (or byte) value as parameter, for example:
[PunRPC]
private void SwitchWeapon(int weaponIndex) { }
Based on the weapon index the client received you can enable or disable certain weapons.
If you want to read more about RPCs you can do this here.
Your answer
Follow this Question
Related Questions
Photon wont sync for the masterclient. 1 Answer
Photon Network instantiate problem when Master changes 0 Answers
Photon Unity Networking Score Issue 1 Answer
This is giving an error for the other client and cannot hit other client. 1 Answer
[UNET] Only spawn certain server objects on local client? 0 Answers