This commit is contained in:
2025-06-16 15:14:23 +02:00
committed by devbeni
parent 60fe4620ff
commit 4ff561284f
3174 changed files with 428263 additions and 0 deletions

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2a426b3dc3eb82b40bbe10eb21fd75d1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,233 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Mirror;
namespace Mirror.Examples.Common
{
// Note: EventSystem is needed in your scene for Unitys UI Canvas
public class CanvasNetworkManagerHUD : MonoBehaviour
{
[SerializeField] private GameObject startButtonsGroup;
[SerializeField] private GameObject statusLabelsGroup;
[SerializeField] private Button startHostButton;
[SerializeField] private Button startServerOnlyButton;
[SerializeField] private Button startClientButton;
[SerializeField] private Button mainStopButton;
[SerializeField] private Text mainStopButtonText;
[SerializeField] private Button secondaryStopButton;
[SerializeField] private Text statusText;
[SerializeField] private InputField inputNetworkAddress;
[SerializeField] private InputField inputPort;
private void Start()
{
// Init the input field with Network Manager's network address.
inputNetworkAddress.text = NetworkManager.singleton.networkAddress;
GetPort();
RegisterListeners();
//RegisterClientEvents();
CheckWebGLPlayer();
}
private void RegisterListeners()
{
// Add button listeners. These buttons are already added in the inspector.
startHostButton.onClick.AddListener(OnClickStartHostButton);
startServerOnlyButton.onClick.AddListener(OnClickStartServerButton);
startClientButton.onClick.AddListener(OnClickStartClientButton);
mainStopButton.onClick.AddListener(OnClickMainStopButton);
secondaryStopButton.onClick.AddListener(OnClickSecondaryStopButton);
// Add input field listener to update NetworkManager's Network Address
// when changed.
inputNetworkAddress.onValueChanged.AddListener(delegate { OnNetworkAddressChange(); });
inputPort.onValueChanged.AddListener(delegate { OnPortChange(); });
}
// Not working at the moment. Can't register events.
/*private void RegisterClientEvents()
{
NetworkClient.OnConnectedEvent += OnClientConnect;
NetworkClient.OnDisconnectedEvent += OnClientDisconnect;
}*/
private void CheckWebGLPlayer()
{
// WebGL can't be host or server.
if (Application.platform == RuntimePlatform.WebGLPlayer)
{
startHostButton.interactable = false;
startServerOnlyButton.interactable = false;
}
}
private void RefreshHUD()
{
if (!NetworkServer.active && !NetworkClient.isConnected)
{
StartButtons();
}
else
{
StatusLabelsAndStopButtons();
}
}
private void StartButtons()
{
if (!NetworkClient.active)
{
statusLabelsGroup.SetActive(false);
startButtonsGroup.SetActive(true);
}
else
{
ShowConnectingStatus();
}
}
private void StatusLabelsAndStopButtons()
{
startButtonsGroup.SetActive(false);
statusLabelsGroup.SetActive(true);
// Host
if (NetworkServer.active && NetworkClient.active)
{
statusText.text = $"<b>Host</b>: running via {Transport.active}";
mainStopButtonText.text = "Stop Client";
}
// Server only
else if (NetworkServer.active)
{
statusText.text = $"<b>Server</b>: running via {Transport.active}";
mainStopButtonText.text = "Stop Server";
}
// Client only
else if (NetworkClient.isConnected)
{
statusText.text = $"<b>Client</b>: connected to {NetworkManager.singleton.networkAddress} via {Transport.active}";
mainStopButtonText.text = "Stop Client";
}
// Note secondary button is only used to Stop Host, and is only needed in host mode.
secondaryStopButton.gameObject.SetActive(NetworkServer.active && NetworkClient.active);
}
private void ShowConnectingStatus()
{
startButtonsGroup.SetActive(false);
statusLabelsGroup.SetActive(true);
secondaryStopButton.gameObject.SetActive(false);
statusText.text = "Connecting to " + NetworkManager.singleton.networkAddress + "..";
mainStopButtonText.text = "Cancel Connection Attempt";
}
private void OnClickStartHostButton()
{
NetworkManager.singleton.StartHost();
}
private void OnClickStartServerButton()
{
NetworkManager.singleton.StartServer();
}
private void OnClickStartClientButton()
{
NetworkManager.singleton.StartClient();
//ShowConnectingStatus();
}
private void OnClickMainStopButton()
{
if (NetworkClient.active)
{
NetworkManager.singleton.StopClient();
}
else
{
NetworkManager.singleton.StopServer();
}
}
private void OnClickSecondaryStopButton()
{
NetworkManager.singleton.StopHost();
}
private void OnNetworkAddressChange()
{
NetworkManager.singleton.networkAddress = inputNetworkAddress.text;
}
private void OnPortChange()
{
SetPort(inputPort.text);
}
private void SetPort(string _port)
{
// only show a port field if we have a port transport
// we can't have "IP:PORT" in the address field since this only
// works for IPV4:PORT.
// for IPV6:PORT it would be misleading since IPV6 contains ":":
// 2001:0db8:0000:0000:0000:ff00:0042:8329
if (Transport.active is PortTransport portTransport)
{
// use TryParse in case someone tries to enter non-numeric characters
if (ushort.TryParse(_port, out ushort port))
portTransport.Port = port;
}
}
private void GetPort()
{
if (Transport.active is PortTransport portTransport)
{
inputPort.text = portTransport.Port.ToString();
}
}
private void Update()
{
RefreshHUD();
}
/* This does not work because we can't register the handler.
void OnClientConnect() {}
private void OnClientDisconnect()
{
RefreshHUD();
}
*/
// Do a check for the presence of a Network Manager component when
// you first add this script to a gameobject.
private void Reset()
{
#if UNITY_2022_2_OR_NEWER
if (!FindAnyObjectByType<NetworkManager>())
Debug.LogError("This component requires a NetworkManager component to be present in the scene. Please add!");
#else
// Deprecated in Unity 2023.1
if (!FindObjectOfType<NetworkManager>())
Debug.LogError("This component requires a NetworkManager component to be present in the scene. Please add!");
#endif
}
}
}

View File

@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 280f31d6f8b054f40b424ccf715b4488
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 129321
packageName: Mirror
packageVersion: 96.0.1
assetPath: Assets/Mirror/Examples/_Common/Scripts/CanvasNetworkManagerHUD/CanvasNetworkManagerHUD.cs
uploadId: 736421

View File

@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 481ace15d5c62488e94a119ae14d62b8
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 129321
packageName: Mirror
packageVersion: 96.0.1
assetPath: Assets/Mirror/Examples/_Common/Scripts/CanvasNetworkManagerHUD/CanvasNetworkManagerHUD.prefab
uploadId: 736421

View File

@ -0,0 +1,38 @@
using UnityEngine;
namespace Mirror.Examples.Common
{
[AddComponentMenu("")]
public class FPS : MonoBehaviour
{
// fps accessible to the outside
public int framesPerSecond { get; private set; }
// configuration
public bool showGUI = true;
public bool showLog = false;
// helpers
int count;
double startTime;
protected void Update()
{
++count;
if (Time.time >= startTime + 1)
{
framesPerSecond = count;
startTime = Time.time;
count = 0;
if (showLog) Debug.Log($"FPS: {framesPerSecond}");
}
}
protected void OnGUI()
{
if (!showGUI) return;
GUI.Label(new Rect(Screen.width - 100, 0, 70, 25), $"FPS: {framesPerSecond}");
}
}
}

View File

@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 6635375fbc6be456ea640b75add6378e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 129321
packageName: Mirror
packageVersion: 96.0.1
assetPath: Assets/Mirror/Examples/_Common/Scripts/FPS.cs
uploadId: 736421

View File

@ -0,0 +1,15 @@
// Useful for Text Meshes that should face the camera.
using UnityEngine;
namespace Mirror.Examples.Common
{
[AddComponentMenu("")]
public class FaceCamera : MonoBehaviour
{
// LateUpdate so that all camera updates are finished.
void LateUpdate()
{
transform.forward = Camera.main.transform.forward;
}
}
}

View File

@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: afa2d590c474413d9fc183551385ed85
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 129321
packageName: Mirror
packageVersion: 96.0.1
assetPath: Assets/Mirror/Examples/_Common/Scripts/FaceCamera.cs
uploadId: 736421

View File

@ -0,0 +1,52 @@
using UnityEngine;
using UnityEditor;
namespace Mirror.Examples.Common.Controllers.Player
{
[ExecuteInEditMode]
[AddComponentMenu("")]
public class PerlinNoise : MonoBehaviour
{
public float scale = 20f;
public float heightMultiplier = .03f;
public float offsetX = 5f;
public float offsetY = 5f;
[ContextMenu("Generate Terrain")]
void GenerateTerrain()
{
Terrain terrain = GetComponent<Terrain>();
if (terrain == null)
{
Debug.LogError("No Terrain component found on this GameObject.");
return;
}
#if UNITY_EDITOR
Undo.RecordObject(terrain, "Generate Perlin Noise Terrain");
#endif
terrain.terrainData = GenerateTerrainData(terrain.terrainData);
}
TerrainData GenerateTerrainData(TerrainData terrainData)
{
int width = terrainData.heightmapResolution;
int height = terrainData.heightmapResolution;
float[,] heights = new float[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
float xCoord = (float)x / width * scale + offsetX;
float yCoord = (float)y / height * scale + offsetY;
heights[x, y] = Mathf.PerlinNoise(xCoord, yCoord) * heightMultiplier;
}
}
terrainData.SetHeights(0, 0, heights);
return terrainData;
}
}
}

View File

@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 86898d6de7df85e4aaaaca9663b06602
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 129321
packageName: Mirror
packageVersion: 96.0.1
assetPath: Assets/Mirror/Examples/_Common/Scripts/PerlinNoise.cs
uploadId: 736421

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 884ea91b35a345443a0320cea07aad68
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@ -0,0 +1,40 @@
using UnityEngine;
namespace Mirror.Examples.Common
{
[AddComponentMenu("")]
public class PhysicsSimulator : MonoBehaviour
{
PhysicsScene physicsScene;
PhysicsScene2D physicsScene2D;
bool simulatePhysicsScene;
bool simulatePhysicsScene2D;
void Awake()
{
if (NetworkServer.active)
{
physicsScene = gameObject.scene.GetPhysicsScene();
simulatePhysicsScene = physicsScene.IsValid() && physicsScene != Physics.defaultPhysicsScene;
physicsScene2D = gameObject.scene.GetPhysicsScene2D();
simulatePhysicsScene2D = physicsScene2D.IsValid() && physicsScene2D != Physics2D.defaultPhysicsScene;
}
else
{
enabled = false;
}
}
[ServerCallback]
void FixedUpdate()
{
if (simulatePhysicsScene)
physicsScene.Simulate(Time.fixedDeltaTime);
if (simulatePhysicsScene2D)
physicsScene2D.Simulate(Time.fixedDeltaTime);
}
}
}

View File

@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 78e3051d2c03f27429276d8a55a6d15c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 129321
packageName: Mirror
packageVersion: 96.0.1
assetPath: Assets/Mirror/Examples/_Common/Scripts/PhysicsSimulator/PhysicsSimulator.cs
uploadId: 736421

View File

@ -0,0 +1,45 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!1 &2581897434666803994
GameObject:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
serializedVersion: 6
m_Component:
- component: {fileID: 440985591853936351}
- component: {fileID: 3973927562887465373}
m_Layer: 0
m_Name: PhysicsSimulator
m_TagString: Untagged
m_Icon: {fileID: 0}
m_NavMeshLayer: 0
m_StaticEditorFlags: 0
m_IsActive: 1
--- !u!4 &440985591853936351
Transform:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2581897434666803994}
m_LocalRotation: {x: 0, y: 0, z: 0, w: 1}
m_LocalPosition: {x: 0, y: 0, z: 0}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 0}
m_RootOrder: 0
m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0}
--- !u!114 &3973927562887465373
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2581897434666803994}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 78e3051d2c03f27429276d8a55a6d15c, type: 3}
m_Name:
m_EditorClassIdentifier:

View File

@ -0,0 +1,14 @@
fileFormatVersion: 2
guid: 99d75386017b4ba44ad1482ee7938f5a
PrefabImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 129321
packageName: Mirror
packageVersion: 96.0.1
assetPath: Assets/Mirror/Examples/_Common/Scripts/PhysicsSimulator/PhysicsSimulator.prefab
uploadId: 736421

View File

@ -0,0 +1,77 @@
using UnityEngine;
using UnityEngine.SceneManagement;
// This sets up the scene camera for the local player
namespace Mirror.Examples.Common
{
[AddComponentMenu("")]
[DisallowMultipleComponent]
public class PlayerCamera : NetworkBehaviour
{
Camera mainCam;
public Vector3 offset = new Vector3(0f, 3f, -8f);
public Vector3 rotation = new Vector3(10f, 0f, 0f);
void Awake()
{
mainCam = Camera.main;
}
public override void OnStartLocalPlayer()
{
if (mainCam != null)
{
// configure and make camera a child of player with 3rd person offset
mainCam.orthographic = false;
mainCam.transform.SetParent(transform);
mainCam.transform.localPosition = offset;
mainCam.transform.localEulerAngles = rotation;
}
else
Debug.LogWarning("PlayerCamera: Could not find a camera in scene with 'MainCamera' tag.");
}
void OnApplicationQuit()
{
//Debug.Log("PlayerCamera.OnApplicationQuit");
ReleaseCamera();
}
public override void OnStopLocalPlayer()
{
//Debug.Log("PlayerCamera.OnStopLocalPlayer");
ReleaseCamera();
}
void OnDisable()
{
//Debug.Log("PlayerCamera.OnDisable");
ReleaseCamera();
}
void OnDestroy()
{
//Debug.Log("PlayerCamera.OnDestroy");
ReleaseCamera();
}
void ReleaseCamera()
{
if (mainCam != null && mainCam.transform.parent == transform)
{
//Debug.Log("PlayerCamera.ReleaseCamera");
mainCam.transform.SetParent(null);
mainCam.orthographic = true;
mainCam.orthographicSize = 15f;
mainCam.transform.localPosition = new Vector3(0f, 70f, 0f);
mainCam.transform.localEulerAngles = new Vector3(90f, 0f, 0f);
if (mainCam.gameObject.scene != SceneManager.GetActiveScene())
SceneManager.MoveGameObjectToScene(mainCam.gameObject, SceneManager.GetActiveScene());
}
}
}
}

View File

@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 71ac1e35462ffad469e77d1c2fe6c9f3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 129321
packageName: Mirror
packageVersion: 96.0.1
assetPath: Assets/Mirror/Examples/_Common/Scripts/PlayerCamera.cs
uploadId: 736421

View File

@ -0,0 +1,35 @@
using UnityEngine;
namespace Mirror.Examples.Common
{
[AddComponentMenu("")]
public class RandomColor : NetworkBehaviour
{
// 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;
// Color32 packs to 4 bytes
[SyncVar(hook = nameof(SetColor))]
public Color32 color = Color.black;
void SetColor(Color32 _, Color32 newColor)
{
if (cachedMaterial == null) cachedMaterial = GetComponentInChildren<Renderer>().material;
cachedMaterial.color = newColor;
}
public override void OnStartServer()
{
// Only set the color once. Players / objects may be unspawned and
// respawned and we don't want to keep changing their colors.
if (color == Color.black)
color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
}
void OnDestroy()
{
Destroy(cachedMaterial);
}
}
}

View File

@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: a91a718a70d01b347b75cb768a6f1a92
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 129321
packageName: Mirror
packageVersion: 96.0.1
assetPath: Assets/Mirror/Examples/_Common/Scripts/RandomColor.cs
uploadId: 736421

View File

@ -0,0 +1,47 @@
using System.Collections;
using UnityEngine;
namespace Mirror.Examples.Common
{
public class Respawn
{
public static void RespawnPlayer(bool respawn, byte respawnTime, NetworkConnectionToClient conn)
{
// Use the NetworkManager static singleton to start a coroutine
NetworkManager.singleton.StartCoroutine(DoRespawn(respawn, respawnTime, conn));
}
public static IEnumerator DoRespawn(bool respawn, byte respawnTime, NetworkConnectionToClient conn)
{
//Debug.Log("DoRespawn started");
// Wait for SyncVars to Update
yield return null;
// Remove Player
if (!respawn)
{
NetworkServer.RemovePlayerForConnection(conn, RemovePlayerOptions.Destroy);
//Debug.Log("Player destroyed");
yield break;
}
GameObject playerObject = conn.identity.gameObject;
NetworkServer.RemovePlayerForConnection(conn, RemovePlayerOptions.Unspawn);
//Debug.Log("Player unspawned");
// Wait for respawn Time
yield return new WaitForSeconds(respawnTime);
// Respawn Player - fallback to Vector3.up * 5f to avoid spawning on another player.
Transform spawnPoint = NetworkManager.singleton.GetStartPosition();
Vector3 position = spawnPoint != null ? spawnPoint.position : Vector3.up * 5f;
Quaternion rotation = spawnPoint != null ? spawnPoint.rotation : Quaternion.identity;
playerObject.transform.SetPositionAndRotation(position, rotation);
NetworkServer.AddPlayerForConnection(conn, playerObject);
//Debug.Log("Player respawned");
}
}
}

View File

@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 276ad7fee659190468450542a55f643c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 7453abfe9e8b2c04a8a47eb536fe21eb, type: 3}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 129321
packageName: Mirror
packageVersion: 96.0.1
assetPath: Assets/Mirror/Examples/_Common/Scripts/Respawn.cs
uploadId: 736421