Gonna move to server authority

This commit is contained in:
2022-01-31 17:27:38 +05:30
parent f3d21f4ec6
commit 7368968176
1354 changed files with 107808 additions and 80043 deletions

View File

@@ -1,84 +1,82 @@
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
[AddComponentMenu("")]
public class NetworkRoomManagerExt : NetworkRoomManager
{
[Header("Spawner Setup")]
[Tooltip("Reward Prefab for the Spawner")]
public GameObject rewardPrefab;
/// <summary>
/// This is called on the server when a networked scene finishes loading.
/// </summary>
/// <param name="sceneName">Name of the new scene.</param>
public override void OnRoomServerSceneChanged(string sceneName)
{
// spawn the initial batch of Rewards
if (sceneName == GameplayScene)
{
Spawner.InitialSpawn();
}
}
/// <summary>
/// Called just after GamePlayer object is instantiated and just before it replaces RoomPlayer object.
/// This is the ideal point to pass any data like player name, credentials, tokens, colors, etc.
/// into the GamePlayer object as it is about to enter the Online scene.
/// </summary>
/// <param name="roomPlayer"></param>
/// <param name="gamePlayer"></param>
/// <returns>true unless some code in here decides it needs to abort the replacement</returns>
public override bool OnRoomServerSceneLoadedForPlayer(NetworkConnection conn, GameObject roomPlayer, GameObject gamePlayer)
{
PlayerScore playerScore = gamePlayer.GetComponent<PlayerScore>();
playerScore.index = roomPlayer.GetComponent<NetworkRoomPlayer>().index;
return true;
}
public override void OnRoomStopClient()
{
base.OnRoomStopClient();
}
public override void OnRoomStopServer()
{
base.OnRoomStopServer();
}
/*
This code below is to demonstrate how to do a Start button that only appears for the Host player
showStartButton is a local bool that's needed because OnRoomServerPlayersReady is only fired when
all players are ready, but if a player cancels their ready state there's no callback to set it back to false
Therefore, allPlayersReady is used in combination with showStartButton to show/hide the Start button correctly.
Setting showStartButton false when the button is pressed hides it in the game scene since NetworkRoomManager
is set as DontDestroyOnLoad = true.
*/
bool showStartButton;
public override void OnRoomServerPlayersReady()
{
// calling the base method calls ServerChangeScene as soon as all players are in Ready state.
#if UNITY_SERVER
base.OnRoomServerPlayersReady();
#else
showStartButton = true;
#endif
}
public override void OnGUI()
{
base.OnGUI();
if (allPlayersReady && showStartButton && GUI.Button(new Rect(150, 300, 120, 20), "START GAME"))
{
// set to false to hide it in the game scene
showStartButton = false;
ServerChangeScene(GameplayScene);
}
}
}
}
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
[AddComponentMenu("")]
public class NetworkRoomManagerExt : NetworkRoomManager
{
[Header("Spawner Setup")]
[Tooltip("Reward Prefab for the Spawner")]
public GameObject rewardPrefab;
/// <summary>
/// This is called on the server when a networked scene finishes loading.
/// </summary>
/// <param name="sceneName">Name of the new scene.</param>
public override void OnRoomServerSceneChanged(string sceneName)
{
// spawn the initial batch of Rewards
if (sceneName == GameplayScene)
Spawner.InitialSpawn();
}
/// <summary>
/// Called just after GamePlayer object is instantiated and just before it replaces RoomPlayer object.
/// This is the ideal point to pass any data like player name, credentials, tokens, colors, etc.
/// into the GamePlayer object as it is about to enter the Online scene.
/// </summary>
/// <param name="roomPlayer"></param>
/// <param name="gamePlayer"></param>
/// <returns>true unless some code in here decides it needs to abort the replacement</returns>
public override bool OnRoomServerSceneLoadedForPlayer(NetworkConnection conn, GameObject roomPlayer, GameObject gamePlayer)
{
PlayerScore playerScore = gamePlayer.GetComponent<PlayerScore>();
playerScore.index = roomPlayer.GetComponent<NetworkRoomPlayer>().index;
return true;
}
public override void OnRoomStopClient()
{
base.OnRoomStopClient();
}
public override void OnRoomStopServer()
{
base.OnRoomStopServer();
}
/*
This code below is to demonstrate how to do a Start button that only appears for the Host player
showStartButton is a local bool that's needed because OnRoomServerPlayersReady is only fired when
all players are ready, but if a player cancels their ready state there's no callback to set it back to false
Therefore, allPlayersReady is used in combination with showStartButton to show/hide the Start button correctly.
Setting showStartButton false when the button is pressed hides it in the game scene since NetworkRoomManager
is set as DontDestroyOnLoad = true.
*/
bool showStartButton;
public override void OnRoomServerPlayersReady()
{
// calling the base method calls ServerChangeScene as soon as all players are in Ready state.
#if UNITY_SERVER
base.OnRoomServerPlayersReady();
#else
showStartButton = true;
#endif
}
public override void OnGUI()
{
base.OnGUI();
if (allPlayersReady && showStartButton && GUI.Button(new Rect(150, 300, 120, 20), "START GAME"))
{
// set to false to hide it in the game scene
showStartButton = false;
ServerChangeScene(GameplayScene);
}
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: e7d8650c751710349bb9546d1697b9cb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: e7d8650c751710349bb9546d1697b9cb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: ''
assetBundleName: ''
assetBundleVariant: ''

View File

@@ -1,30 +1,39 @@
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
[AddComponentMenu("")]
public class NetworkRoomPlayerExt : NetworkRoomPlayer
{
public override void OnStartClient()
{
// Debug.LogFormat(LogType.Log, "OnStartClient {0}", SceneManager.GetActiveScene().path);
base.OnStartClient();
}
public override void OnClientEnterRoom()
{
// Debug.LogFormat(LogType.Log, "OnClientEnterRoom {0}", SceneManager.GetActiveScene().path);
}
public override void OnClientExitRoom()
{
// Debug.LogFormat(LogType.Log, "OnClientExitRoom {0}", SceneManager.GetActiveScene().path);
}
public override void ReadyStateChanged(bool oldReadyState, bool newReadyState)
{
// Debug.LogFormat(LogType.Log, "ReadyStateChanged {0}", newReadyState);
}
}
}
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Mirror.Examples.NetworkRoom
{
[AddComponentMenu("")]
public class NetworkRoomPlayerExt : NetworkRoomPlayer
{
public override void OnStartClient()
{
//Debug.Log($"OnStartClient {gameObject}");
}
public override void OnClientEnterRoom()
{
//Debug.Log($"OnClientEnterRoom {SceneManager.GetActiveScene().path}");
}
public override void OnClientExitRoom()
{
//Debug.Log($"OnClientExitRoom {SceneManager.GetActiveScene().path}");
}
public override void IndexChanged(int oldIndex, int newIndex)
{
//Debug.Log($"IndexChanged {newIndex}");
}
public override void ReadyStateChanged(bool oldReadyState, bool newReadyState)
{
//Debug.Log($"ReadyStateChanged {newReadyState}");
}
public override void OnGUI()
{
base.OnGUI();
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 41fc608223969754e817c29908fdb1d3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 41fc608223969754e817c29908fdb1d3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: ''
assetBundleName: ''
assetBundleVariant: ''

View File

@@ -1,110 +1,110 @@
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
[RequireComponent(typeof(CapsuleCollider))]
[RequireComponent(typeof(CharacterController))]
[RequireComponent(typeof(NetworkTransform))]
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : NetworkBehaviour
{
public CharacterController characterController;
void OnValidate()
{
if (characterController == null)
characterController = GetComponent<CharacterController>();
}
void Start()
{
characterController.enabled = isLocalPlayer;
}
public override void OnStartLocalPlayer()
{
Camera.main.orthographic = false;
Camera.main.transform.SetParent(transform);
Camera.main.transform.localPosition = new Vector3(0f, 3f, -8f);
Camera.main.transform.localEulerAngles = new Vector3(10f, 0f, 0f);
}
void OnDisable()
{
if (isLocalPlayer && Camera.main != null)
{
Camera.main.orthographic = true;
Camera.main.transform.SetParent(null);
Camera.main.transform.localPosition = new Vector3(0f, 70f, 0f);
Camera.main.transform.localEulerAngles = new Vector3(90f, 0f, 0f);
}
}
[Header("Movement Settings")]
public float moveSpeed = 8f;
public float turnSensitivity = 5f;
public float maxTurnSpeed = 150f;
[Header("Diagnostics")]
public float horizontal;
public float vertical;
public float turn;
public float jumpSpeed;
public bool isGrounded = true;
public bool isFalling;
public Vector3 velocity;
void Update()
{
if (!isLocalPlayer)
return;
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
// Q and E cancel each other out, reducing the turn to zero
if (Input.GetKey(KeyCode.Q))
turn = Mathf.MoveTowards(turn, -maxTurnSpeed, turnSensitivity);
if (Input.GetKey(KeyCode.E))
turn = Mathf.MoveTowards(turn, maxTurnSpeed, turnSensitivity);
if (Input.GetKey(KeyCode.Q) && Input.GetKey(KeyCode.E))
turn = Mathf.MoveTowards(turn, 0, turnSensitivity);
if (!Input.GetKey(KeyCode.Q) && !Input.GetKey(KeyCode.E))
turn = Mathf.MoveTowards(turn, 0, turnSensitivity);
if (isGrounded)
isFalling = false;
if ((isGrounded || !isFalling) && jumpSpeed < 1f && Input.GetKey(KeyCode.Space))
{
jumpSpeed = Mathf.Lerp(jumpSpeed, 1f, 0.5f);
}
else if (!isGrounded)
{
isFalling = true;
jumpSpeed = 0;
}
}
void FixedUpdate()
{
if (!isLocalPlayer || characterController == null)
return;
transform.Rotate(0f, turn * Time.fixedDeltaTime, 0f);
Vector3 direction = new Vector3(horizontal, jumpSpeed, vertical);
direction = Vector3.ClampMagnitude(direction, 1f);
direction = transform.TransformDirection(direction);
direction *= moveSpeed;
if (jumpSpeed > 0)
characterController.Move(direction * Time.fixedDeltaTime);
else
characterController.SimpleMove(direction);
isGrounded = characterController.isGrounded;
velocity = characterController.velocity;
}
}
}
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
[RequireComponent(typeof(CapsuleCollider))]
[RequireComponent(typeof(CharacterController))]
[RequireComponent(typeof(NetworkTransform))]
[RequireComponent(typeof(Rigidbody))]
public class PlayerController : NetworkBehaviour
{
public CharacterController characterController;
void OnValidate()
{
if (characterController == null)
characterController = GetComponent<CharacterController>();
}
void Start()
{
characterController.enabled = isLocalPlayer;
}
public override void OnStartLocalPlayer()
{
Camera.main.orthographic = false;
Camera.main.transform.SetParent(transform);
Camera.main.transform.localPosition = new Vector3(0f, 3f, -8f);
Camera.main.transform.localEulerAngles = new Vector3(10f, 0f, 0f);
}
void OnDisable()
{
if (isLocalPlayer && Camera.main != null)
{
Camera.main.orthographic = true;
Camera.main.transform.SetParent(null);
Camera.main.transform.localPosition = new Vector3(0f, 70f, 0f);
Camera.main.transform.localEulerAngles = new Vector3(90f, 0f, 0f);
}
}
[Header("Movement Settings")]
public float moveSpeed = 8f;
public float turnSensitivity = 5f;
public float maxTurnSpeed = 150f;
[Header("Diagnostics")]
public float horizontal;
public float vertical;
public float turn;
public float jumpSpeed;
public bool isGrounded = true;
public bool isFalling;
public Vector3 velocity;
void Update()
{
if (!isLocalPlayer)
return;
horizontal = Input.GetAxis("Horizontal");
vertical = Input.GetAxis("Vertical");
// Q and E cancel each other out, reducing the turn to zero
if (Input.GetKey(KeyCode.Q))
turn = Mathf.MoveTowards(turn, -maxTurnSpeed, turnSensitivity);
if (Input.GetKey(KeyCode.E))
turn = Mathf.MoveTowards(turn, maxTurnSpeed, turnSensitivity);
if (Input.GetKey(KeyCode.Q) && Input.GetKey(KeyCode.E))
turn = Mathf.MoveTowards(turn, 0, turnSensitivity);
if (!Input.GetKey(KeyCode.Q) && !Input.GetKey(KeyCode.E))
turn = Mathf.MoveTowards(turn, 0, turnSensitivity);
if (isGrounded)
isFalling = false;
if ((isGrounded || !isFalling) && jumpSpeed < 1f && Input.GetKey(KeyCode.Space))
{
jumpSpeed = Mathf.Lerp(jumpSpeed, 1f, 0.5f);
}
else if (!isGrounded)
{
isFalling = true;
jumpSpeed = 0;
}
}
void FixedUpdate()
{
if (!isLocalPlayer || characterController == null)
return;
transform.Rotate(0f, turn * Time.fixedDeltaTime, 0f);
Vector3 direction = new Vector3(horizontal, jumpSpeed, vertical);
direction = Vector3.ClampMagnitude(direction, 1f);
direction = transform.TransformDirection(direction);
direction *= moveSpeed;
if (jumpSpeed > 0)
characterController.Move(direction * Time.fixedDeltaTime);
else
characterController.SimpleMove(direction);
isGrounded = characterController.isGrounded;
velocity = characterController.velocity;
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 24fd13686a451ad498101a604d134e39
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 24fd13686a451ad498101a604d134e39
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: ''
assetBundleName: ''
assetBundleVariant: ''

View File

@@ -1,18 +1,18 @@
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
public class PlayerScore : NetworkBehaviour
{
[SyncVar]
public int index;
[SyncVar]
public uint score;
void OnGUI()
{
GUI.Box(new Rect(10f + (index * 110), 10f, 100f, 25f), $"P{index}: {score.ToString("0000000")}");
}
}
}
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
public class PlayerScore : NetworkBehaviour
{
[SyncVar]
public int index;
[SyncVar]
public uint score;
void OnGUI()
{
GUI.Box(new Rect(10f + (index * 110), 10f, 100f, 25f), $"P{index}: {score:0000000}");
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 1ba998ee2eff92a419f4377519caf095
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 1ba998ee2eff92a419f4377519caf095
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: ''
assetBundleName: ''
assetBundleVariant: ''

View File

@@ -1,32 +1,32 @@
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
public class RandomColor : NetworkBehaviour
{
public override void OnStartServer()
{
base.OnStartServer();
color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
}
// Color32 packs to 4 bytes
[SyncVar(hook = nameof(SetColor))]
public Color32 color = Color.black;
// Unity clones the material when GetComponent<Renderer>().material is called
// Cache it here and destroy it in OnDestroy to prevent a memory leak
Material cachedMaterial;
void SetColor(Color32 _, Color32 newColor)
{
if (cachedMaterial == null) cachedMaterial = GetComponentInChildren<Renderer>().material;
cachedMaterial.color = newColor;
}
void OnDestroy()
{
Destroy(cachedMaterial);
}
}
}
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
public class RandomColor : NetworkBehaviour
{
public override void OnStartServer()
{
base.OnStartServer();
color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
}
// Color32 packs to 4 bytes
[SyncVar(hook = nameof(SetColor))]
public Color32 color = Color.black;
// Unity clones the material when GetComponent<Renderer>().material is called
// Cache it here and destroy it in OnDestroy to prevent a memory leak
Material cachedMaterial;
void SetColor(Color32 _, Color32 newColor)
{
if (cachedMaterial == null) cachedMaterial = GetComponentInChildren<Renderer>().material;
cachedMaterial.color = newColor;
}
void OnDestroy()
{
Destroy(cachedMaterial);
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 1e6a8bf08f02e254aa9a52ef0aaa1553
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 1e6a8bf08f02e254aa9a52ef0aaa1553
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: ''
assetBundleName: ''
assetBundleVariant: ''

View File

@@ -1,54 +1,54 @@
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
[RequireComponent(typeof(RandomColor))]
public class Reward : NetworkBehaviour
{
public bool available = true;
public RandomColor randomColor;
void OnValidate()
{
if (randomColor == null)
randomColor = GetComponent<RandomColor>();
}
[ServerCallback]
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
ClaimPrize(other.gameObject);
}
}
// This is called from PlayerController.CmdClaimPrize which is invoked by PlayerController.OnControllerColliderHit
// This only runs on the server
public void ClaimPrize(GameObject player)
{
if (available)
{
// This is a fast switch to prevent two players claiming the prize in a bang-bang close contest for it.
// First hit turns it off, pending the object being destroyed a few frames later.
available = false;
Color32 color = randomColor.color;
// calculate the points from the color ... lighter scores higher as the average approaches 255
// UnityEngine.Color RGB values are float fractions of 255
uint points = (uint)(((color.r) + (color.g) + (color.b)) / 3);
// Debug.LogFormat(LogType.Log, "Scored {0} points R:{1} G:{2} B:{3}", points, color.r, color.g, color.b);
// award the points via SyncVar on the PlayerController
player.GetComponent<PlayerScore>().score += points;
// spawn a replacement
Spawner.SpawnReward();
// destroy this one
NetworkServer.Destroy(gameObject);
}
}
}
}
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
[RequireComponent(typeof(RandomColor))]
public class Reward : NetworkBehaviour
{
public bool available = true;
public RandomColor randomColor;
void OnValidate()
{
if (randomColor == null)
randomColor = GetComponent<RandomColor>();
}
[ServerCallback]
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
ClaimPrize(other.gameObject);
}
}
// This is called from PlayerController.CmdClaimPrize which is invoked by PlayerController.OnControllerColliderHit
// This only runs on the server
public void ClaimPrize(GameObject player)
{
if (available)
{
// This is a fast switch to prevent two players claiming the prize in a bang-bang close contest for it.
// First hit turns it off, pending the object being destroyed a few frames later.
available = false;
Color32 color = randomColor.color;
// calculate the points from the color ... lighter scores higher as the average approaches 255
// UnityEngine.Color RGB values are float fractions of 255
uint points = (uint)(((color.r) + (color.g) + (color.b)) / 3);
// Debug.LogFormat(LogType.Log, "Scored {0} points R:{1} G:{2} B:{3}", points, color.r, color.g, color.b);
// award the points via SyncVar on the PlayerController
player.GetComponent<PlayerScore>().score += points;
// spawn a replacement
Spawner.SpawnReward();
// destroy this one
NetworkServer.Destroy(gameObject);
}
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: a22f9eb8ebad79e47babf4c051a714ee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: a22f9eb8ebad79e47babf4c051a714ee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: ''
assetBundleName: ''
assetBundleVariant: ''

View File

@@ -1,23 +1,23 @@
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
internal class Spawner
{
internal static void InitialSpawn()
{
if (!NetworkServer.active) return;
for (int i = 0; i < 10; i++)
SpawnReward();
}
internal static void SpawnReward()
{
if (!NetworkServer.active) return;
Vector3 spawnPosition = new Vector3(Random.Range(-19, 20), 1, Random.Range(-19, 20));
NetworkServer.Spawn(Object.Instantiate(((NetworkRoomManagerExt)NetworkManager.singleton).rewardPrefab, spawnPosition, Quaternion.identity));
}
}
}
using UnityEngine;
namespace Mirror.Examples.NetworkRoom
{
internal class Spawner
{
internal static void InitialSpawn()
{
if (!NetworkServer.active) return;
for (int i = 0; i < 10; i++)
SpawnReward();
}
internal static void SpawnReward()
{
if (!NetworkServer.active) return;
Vector3 spawnPosition = new Vector3(Random.Range(-19, 20), 1, Random.Range(-19, 20));
NetworkServer.Spawn(Object.Instantiate(((NetworkRoomManagerExt)NetworkManager.singleton).rewardPrefab, spawnPosition, Quaternion.identity));
}
}
}

View File

@@ -1,11 +1,11 @@
fileFormatVersion: 2
guid: 0bf5c082d04f7ea459fcd30e60b5bd70
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 0bf5c082d04f7ea459fcd30e60b5bd70
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: ''
assetBundleName: ''
assetBundleVariant: ''