Answer the question
In order to leave comments, you need to log in
Synchronization of the selected weapon for each of the players in a multiplayer shooter on Unity?
Hello everybody!
There is a code for synchronizing the position, rotation of the players, and it also has a code for synchronizing the selected weapon for each of the players:
/*
*
* Скрипт SyncPlayer отвечает за синхранизацию игроков
*
*/
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class SyncPlayer : NetworkBehaviour
{
[SyncVar] Vector3 syncPosition; // Позиция всех клиентов кроме самого игрока
[SyncVar] Quaternion syncRotation; // Поворот всех игроков кроме самого игрока
[SyncVar] SyncListBool syncWeapon = new SyncListBool();
public float lerpSpeed = 20; // Скорость сглаживания
/// <summary>
/// Фиксированый вызов метода TransmitPosition для синхронизации позиции
/// </summary>
void FixedUpdate ()
{
LerPosition();
TransmitTransform();
}
/// <summary>
/// Метод для сглаживания позиции всех клиентов но кроме самого игрока
/// </summary>
void LerPosition()
{
if (!isLocalPlayer)
{
transform.position = Vector3.Lerp(transform.position, syncPosition, Time.deltaTime * lerpSpeed);
transform.rotation = Quaternion.Lerp(transform.rotation, syncRotation, Time.deltaTime * lerpSpeed);
for(int i = 0; i < syncWeapon.Count; i++)
{
gameObject.GetComponent<PlayerScrolWeapon>().weapon[i].SetActive(syncWeapon[i]);
}
}
}
/// <summary>
/// Отправка позиции локального игрока на сервер в переменную syncPosition
/// </summary>
[Client]
void TransmitTransform()
{
if (isLocalPlayer)
{
List<GameObject> weapon = gameObject.GetComponent<PlayerScrolWeapon>().weapon;
GameObject[] _weapon = new GameObject[4];
int i = 0;
foreach (GameObject goGun in weapon)
{
_weapon[i] = goGun;
i++;
}
CmdSendTransform(transform.position, transform.rotation, _weapon);
}
}
/// <summary>
/// Запись позиции локального игрока в переменную syncPosition
/// </summary>
[Command]
void CmdSendTransform(Vector3 position, Quaternion rotation, GameObject[] _weapon)
{
syncPosition = position;
syncRotation = rotation;
syncWeapon.Clear();
foreach (GameObject weap in _weapon)
{
syncWeapon.Add(weap.activeSelf);
}
}
}
using System.Collections.Generic;
using UnityEngine;
public class PlayerScrolWeapon : MonoBehaviour
{
[SerializeField] private GameObject[] weapons; // Массив всех оружий
private string[] nameSelectedWeapons = new string[4]; // Массив названий всех выбранных оружий
public List<GameObject> weapon = new List<GameObject>(); // Список всех выбранных оружий для переключения между ними
private int scrolInt = 0; // Индекс выбранного оружия(скрола)
private int lastScrolInt = 0; // Индекс старого значения
private Animator anim;
void Start ()
{
anim = GetComponent<Animator>();
nameSelectedWeapons[0] = "Cube Gun";
nameSelectedWeapons[1] = "Sphere Gun";
nameSelectedWeapons[2] = "Cylinder Gun";
nameSelectedWeapons[3] = "Capsule Gun";
// Переносим в список выбранных оружий из массива всех оружий по названиям оружий в массиве названий
foreach (GameObject goWeapon in weapons)
{
foreach(string nameSelectedWeapon in nameSelectedWeapons)
{
if (nameSelectedWeapon == goWeapon.name)
weapon.Add(goWeapon);
}
}
weapon[scrolInt].SetActive(true);
}
void Update ()
{
lastScrolInt = scrolInt;
// Изменение значения индекса выбранного оружия при прокрутке колесиком мыши
if (Input.GetAxis("Mouse ScrollWheel") > 0f)
scrolInt++;
else if(Input.GetAxis("Mouse ScrollWheel") < 0f)
scrolInt--;
// Не даем выйти индексу за пределы допустимого
if (scrolInt > weapon.Count - 1)
scrolInt = 0;
else if(scrolInt < 0)
scrolInt = weapon.Count - 1;
// Переключение между разными оружиями
if (lastScrolInt != scrolInt)
{
//Debug.Log(scrolInt);
for (int i = 0; i < weapon.Count; i++)
{
if (i == scrolInt)
weapon[i].SetActive(true);
else
weapon[i].SetActive(false);
}
}
}
}
Answer the question
In order to leave comments, you need to log in
The problem was solved, this was due to the fact that 2 client and server applications were launched on 1pc, after the server and client were launched on different PCs, almost everything worked, but for some reason the client sees how the server changes weapons, but the server does not see how the client changes weapons. Does anyone have a solution to this problem?
That no one knows how to do it? I've already searched the entire Internet about changing weapons in multiplayer and synchronizing them, but it's empty !!! Help -_- please)
Solution:
using UnityEngine;
using UnityEngine.Networking;
public class PlayerScrolWeapon : NetworkBehaviour
{
public GameObject[] weapon;
[SyncVar] int syncWeaponIndex;
private int weaponIndex = 0;
[Client]
void FixedUpdate()
{
ScrolWeapon();
if(isLocalPlayer)
CmdSendToServerSyncWeapon(weaponIndex);
SendToClientSyncWeapon();
}
void ScrolWeapon()
{
if(isLocalPlayer)
{
if(Input.GetAxisRaw("Mouse ScrollWheel") > 0f)
{
if (weaponIndex > 3)
weaponIndex = 0;
else
weaponIndex++;
}
else if(Input.GetAxisRaw("Mouse ScrollWheel") < 0f)
{
if (weaponIndex < 0)
weaponIndex = 3;
else
weaponIndex--;
}
for (int i = 0; i < 4; i++)
if (i == weaponIndex)
weapon[i].SetActive(true);
else
weapon[i].SetActive(false);
}
}
void SendToClientSyncWeapon()
{
if(!isLocalPlayer)
{
for (int i = 0; i < 4; i++)
if (i == syncWeaponIndex)
weapon[i].SetActive(true);
else
weapon[i].SetActive(false);
}
}
[Command]
void CmdSendToServerSyncWeapon(int _weaponIndex)
{
syncWeaponIndex = _weaponIndex;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question