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,63 +1,63 @@
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Mirror.Examples.Additive
{
[AddComponentMenu("")]
public class AdditiveNetworkManager : NetworkManager
{
[Tooltip("Trigger Zone Prefab")]
public GameObject Zone;
[Scene]
[Tooltip("Add all sub-scenes to this list")]
public string[] subScenes;
public override void OnStartServer()
{
base.OnStartServer();
// load all subscenes on the server only
StartCoroutine(LoadSubScenes());
// Instantiate Zone Handler on server only
Instantiate(Zone);
}
IEnumerator LoadSubScenes()
{
Debug.Log("Loading Scenes");
foreach (string sceneName in subScenes)
{
yield return SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
// Debug.Log($"Loaded {sceneName}");
}
}
public override void OnStopServer()
{
StartCoroutine(UnloadScenes());
}
public override void OnStopClient()
{
StartCoroutine(UnloadScenes());
}
IEnumerator UnloadScenes()
{
Debug.Log("Unloading Subscenes");
foreach (string sceneName in subScenes)
if (SceneManager.GetSceneByName(sceneName).IsValid() || SceneManager.GetSceneByPath(sceneName).IsValid())
{
yield return SceneManager.UnloadSceneAsync(sceneName);
// Debug.Log($"Unloaded {sceneName}");
}
yield return Resources.UnloadUnusedAssets();
}
}
}
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Mirror.Examples.Additive
{
[AddComponentMenu("")]
public class AdditiveNetworkManager : NetworkManager
{
[Tooltip("Trigger Zone Prefab")]
public GameObject Zone;
[Scene]
[Tooltip("Add all sub-scenes to this list")]
public string[] subScenes;
public override void OnStartServer()
{
base.OnStartServer();
// load all subscenes on the server only
StartCoroutine(LoadSubScenes());
// Instantiate Zone Handler on server only
Instantiate(Zone);
}
public override void OnStopServer()
{
StartCoroutine(UnloadScenes());
}
public override void OnStopClient()
{
StartCoroutine(UnloadScenes());
}
IEnumerator LoadSubScenes()
{
Debug.Log("Loading Scenes");
foreach (string sceneName in subScenes)
{
yield return SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
// Debug.Log($"Loaded {sceneName}");
}
}
IEnumerator UnloadScenes()
{
Debug.Log("Unloading Subscenes");
foreach (string sceneName in subScenes)
if (SceneManager.GetSceneByName(sceneName).IsValid() || SceneManager.GetSceneByPath(sceneName).IsValid())
{
yield return SceneManager.UnloadSceneAsync(sceneName);
// Debug.Log($"Unloaded {sceneName}");
}
yield return Resources.UnloadUnusedAssets();
}
}
}

View File

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

View File

@@ -1,110 +1,110 @@
using UnityEngine;
namespace Mirror.Examples.Additive
{
[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 || !characterController.enabled)
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.Additive
{
[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 || !characterController.enabled)
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: e8f68561248aaca4fb96847ce24742ee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: e8f68561248aaca4fb96847ce24742ee
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: ''
assetBundleName: ''
assetBundleVariant: ''

View File

@@ -1,32 +1,32 @@
using UnityEngine;
namespace Mirror.Examples.Additive
{
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.Additive
{
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: 42d1f80407105ee4f960f0b51e89452d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 42d1f80407105ee4f960f0b51e89452d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: ''
assetBundleName: ''
assetBundleVariant: ''

View File

@@ -1,59 +1,59 @@
using UnityEngine;
namespace Mirror.Examples.Additive
{
// This script demonstrates the NetworkAnimator and how to leverage
// the built-in observers system to track players.
// Note that all ProximityCheckers should be restricted to the Player layer.
public class ShootingTankBehaviour : NetworkBehaviour
{
[SyncVar]
public Quaternion rotation;
NetworkAnimator networkAnimator;
[ServerCallback]
void Start()
{
networkAnimator = GetComponent<NetworkAnimator>();
}
[Range(0, 1)]
public float turnSpeed = 0.1f;
void Update()
{
if (isServer && netIdentity.observers.Count > 0)
ShootNearestPlayer();
if (isClient)
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, turnSpeed);
}
[Server]
void ShootNearestPlayer()
{
GameObject target = null;
float distance = 100f;
foreach (NetworkConnection networkConnection in netIdentity.observers.Values)
{
GameObject tempTarget = networkConnection.identity.gameObject;
float tempDistance = Vector3.Distance(tempTarget.transform.position, transform.position);
if (target == null || distance > tempDistance)
{
target = tempTarget;
distance = tempDistance;
}
}
if (target != null)
{
transform.LookAt(target.transform.position + Vector3.down);
rotation = transform.rotation;
networkAnimator.SetTrigger("Fire");
}
}
}
}
using UnityEngine;
namespace Mirror.Examples.Additive
{
// This script demonstrates the NetworkAnimator and how to leverage
// the built-in observers system to track players.
// Note that all ProximityCheckers should be restricted to the Player layer.
public class ShootingTankBehaviour : NetworkBehaviour
{
[SyncVar]
public Quaternion rotation;
NetworkAnimator networkAnimator;
[ServerCallback]
void Start()
{
networkAnimator = GetComponent<NetworkAnimator>();
}
[Range(0, 1)]
public float turnSpeed = 0.1f;
void Update()
{
if (isServer && netIdentity.observers.Count > 0)
ShootNearestPlayer();
if (isClient)
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, turnSpeed);
}
[Server]
void ShootNearestPlayer()
{
GameObject target = null;
float distance = 100f;
foreach (NetworkConnection networkConnection in netIdentity.observers.Values)
{
GameObject tempTarget = networkConnection.identity.gameObject;
float tempDistance = Vector3.Distance(tempTarget.transform.position, transform.position);
if (target == null || distance > tempDistance)
{
target = tempTarget;
distance = tempDistance;
}
}
if (target != null)
{
transform.LookAt(target.transform.position + Vector3.down);
rotation = transform.rotation;
networkAnimator.SetTrigger("Fire");
}
}
}
}

View File

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

View File

@@ -1,39 +1,37 @@
using UnityEngine;
namespace Mirror.Examples.Additive
{
// This script is attached to a prefab called Zone that is on the Player layer
// AdditiveNetworkManager, in OnStartServer, instantiates the prefab only on the server.
// It never exists for clients (other than host client if there is one).
// The prefab has a Sphere Collider with isTrigger = true.
// These OnTrigger events only run on the server and will only send a message to the
// client that entered the Zone to load the subscene assigned to the subscene property.
public class ZoneHandler : MonoBehaviour
{
[Scene]
[Tooltip("Assign the sub-scene to load for this zone")]
public string subScene;
void OnTriggerEnter(Collider other)
{
if (!NetworkServer.active) return;
// Debug.LogFormat(LogType.Log, "Loading {0}", subScene);
NetworkIdentity networkIdentity = other.gameObject.GetComponent<NetworkIdentity>();
SceneMessage message = new SceneMessage{ sceneName = subScene, sceneOperation = SceneOperation.LoadAdditive };
networkIdentity.connectionToClient.Send(message);
}
void OnTriggerExit(Collider other)
{
if (!NetworkServer.active) return;
// Debug.LogFormat(LogType.Log, "Unloading {0}", subScene);
NetworkIdentity networkIdentity = other.gameObject.GetComponent<NetworkIdentity>();
SceneMessage message = new SceneMessage{ sceneName = subScene, sceneOperation = SceneOperation.UnloadAdditive };
networkIdentity.connectionToClient.Send(message);
}
}
}
using UnityEngine;
namespace Mirror.Examples.Additive
{
// This script is attached to a prefab called Zone that is on the Player layer
// AdditiveNetworkManager, in OnStartServer, instantiates the prefab only on the server.
// It never exists for clients (other than host client if there is one).
// The prefab has a Sphere Collider with isTrigger = true.
// These OnTrigger events only run on the server and will only send a message to the
// client that entered the Zone to load the subscene assigned to the subscene property.
public class ZoneHandler : MonoBehaviour
{
[Scene]
[Tooltip("Assign the sub-scene to load for this zone")]
public string subScene;
[ServerCallback]
void OnTriggerEnter(Collider other)
{
// Debug.Log($"Loading {subScene}");
NetworkIdentity networkIdentity = other.gameObject.GetComponent<NetworkIdentity>();
SceneMessage message = new SceneMessage{ sceneName = subScene, sceneOperation = SceneOperation.LoadAdditive };
networkIdentity.connectionToClient.Send(message);
}
[ServerCallback]
void OnTriggerExit(Collider other)
{
// Debug.Log($"Unloading {subScene}");
NetworkIdentity networkIdentity = other.gameObject.GetComponent<NetworkIdentity>();
SceneMessage message = new SceneMessage{ sceneName = subScene, sceneOperation = SceneOperation.UnloadAdditive };
networkIdentity.connectionToClient.Send(message);
}
}
}

View File

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