diff --git a/README.md b/README.md index 188b5c3d2..35e91187d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ ![Mirror Logo](https://i.imgur.com/we6li1x.png) [![Download](https://img.shields.io/badge/asset_store-brightgreen.svg)](https://assetstore.unity.com/packages/tools/network/mirror-129321) -[![Documentation](https://img.shields.io/badge/docs-brightgreen.svg)](https://mirror-networking.com/docs) +[![Documentation](https://img.shields.io/badge/docs-brightgreen.svg)](https://mirror-networking.gitbook.io/) [![Showcase](https://img.shields.io/badge/showcase-brightgreen.svg)](https://mirror-networking.com/showcase/) [![Video Tutorial](https://img.shields.io/badge/video_tutorial-brightgreen.svg)](https://www.youtube.com/playlist?list=PLkx8oFug638oBYF5EOwsSS-gOVBXj1dkP) [![Forum](https://img.shields.io/badge/forum-brightgreen.svg)](https://forum.unity.com/threads/mirror-networking-for-unity-aka-hlapi-community-edition.425437/) @@ -18,7 +18,7 @@ Mirror is a **high level** Networking library for Unity, compatible with differe Mirror is for small indie games & large scale [MMOs](https://www.youtube.com/watch?v=mDCNff1S9ZU), made by the developers of [uMMORPG](https://assetstore.unity.com/packages/templates/systems/ummorpg-components-edition-159401) and [Cubica](https://www.youtube.com/watch?v=D_f_MntrLVE). -Mirror is optimized for **ease of use** & **probability of success**. +Mirror is optimized for **ease of use** & **probability of success**. We needed a networking library that allows us to **[launch our games](https://mirror-networking.com/showcase/)** and **survive the next decade**. @@ -47,9 +47,9 @@ _Note: Mirror is based on Unity's abandoned UNET Networking system. We fixed it ## Getting Started Get **Unity 2018/2019 LTS**, download [Mirror on the Asset Store](https://assetstore.unity.com/packages/tools/network/mirror-129321), open one of the examples & press Play! -Check out our [Documentation](https://mirror-networking.com/docs/) to learn how it all works. +Check out our [Documentation](https://mirror-networking.gitbook.io/) to learn how it all works. -If you are migrating from UNET, then please check out our [Migration Guide](https://mirror-networking.com/docs/Articles/General/Migration.html). +If you are migrating from UNET, then please check out our [Migration Guide](https://mirror-networking.gitbook.io/docs/general/migration-guide). ## Made with Mirror ![Population: ONE](https://steamcdn-a.akamaihd.net/steam/apps/691260/header.jpg?t=1603846067)
@@ -68,7 +68,7 @@ If you are migrating from UNET, then please check out our [Migration Guide](http [Laurum Online](https://laurum.online/)
## Funding -Mirror is free & open source software funded by Donations. If you love it, please consider supporting [Mirror on GitHub](https://github.com/sponsors/vis2k). As reward, you'll receive our [Network Profiler](https://mirror-networking.com/docs/Articles/Guides/Profiler.html?q=Profiler), priority support and more :) +Mirror is free & open source software funded by Donations. If you love it, please consider supporting [Mirror on GitHub](https://github.com/sponsors/vis2k). As reward, you'll receive our [Network Profiler](https://mirror-networking.gitbook.io/docs/guides/network-profiler), priority support and more :) ## Benchmarks * [uMMORPG 480 CCU worst case test](https://youtu.be/mDCNff1S9ZU) (everyone broadcasting to everyone else) diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--000.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--000.jpg deleted file mode 100644 index d23aa27e6..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--000.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--001.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--001.jpg deleted file mode 100644 index 4cc9fba8c..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--001.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--002.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--002.jpg deleted file mode 100644 index dd648ad48..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--002.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--003.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--003.jpg deleted file mode 100644 index 8b4af612a..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--003.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--004.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--004.jpg deleted file mode 100644 index 44065ed55..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--004.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--005.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--005.jpg deleted file mode 100644 index 4df316f9b..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--005.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--006.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--006.jpg deleted file mode 100644 index b566ff72c..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--006.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--007.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--007.jpg deleted file mode 100644 index ab29cd981..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--007.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--008.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--008.jpg deleted file mode 100644 index 6a896a06c..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--008.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--009.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--009.jpg deleted file mode 100644 index 7a7ae73b6..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--009.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--010.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--010.jpg deleted file mode 100644 index 8a1fe2adf..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--010.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--011.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--011.jpg deleted file mode 100644 index dc752178c..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--011.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--012.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--012.jpg deleted file mode 100644 index 421fc3132..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--012.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--013.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--013.jpg deleted file mode 100644 index 0883cb33d..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--013.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--014.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--014.jpg deleted file mode 100644 index 9ce78f0ad..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--014.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--015.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--015.jpg deleted file mode 100644 index a092e9cae..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--015.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--016.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--016.jpg deleted file mode 100644 index 0053f42b9..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--016.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--017.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--017.jpg deleted file mode 100644 index 2321f5068..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--017.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--018.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--018.jpg deleted file mode 100644 index a66ecbcf8..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--018.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--019.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--019.jpg deleted file mode 100644 index f9cc2b330..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--019.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--020.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--020.jpg deleted file mode 100644 index 9d9696afb..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--020.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--021.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--021.jpg deleted file mode 100644 index 85c6baf04..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--021.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--022.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--022.jpg deleted file mode 100644 index 4f22610f2..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--022.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--023.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--023.jpg deleted file mode 100644 index 14ac31cd3..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--023.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--024.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--024.jpg deleted file mode 100644 index 81417c595..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--024.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--025.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--025.jpg deleted file mode 100644 index 1c0409e1c..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--025.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--026.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--026.jpg deleted file mode 100644 index 7659d5577..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--026.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--027.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--027.jpg deleted file mode 100644 index d7becbdd4..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--027.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--028.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--028.jpg deleted file mode 100644 index bef825e0f..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--028.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--029.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--029.jpg deleted file mode 100644 index ac6e36e1b..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--029.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--030.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--030.jpg deleted file mode 100644 index e5c8c709a..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--030.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--031.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--031.jpg deleted file mode 100644 index 85541d90f..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--031.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--032.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--032.jpg deleted file mode 100644 index 8175c6e53..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--032.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--033.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--033.jpg deleted file mode 100644 index f9217a036..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--033.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--034.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--034.jpg deleted file mode 100644 index 83110dd01..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--034.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--035.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--035.jpg deleted file mode 100644 index 9b66da99b..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--035.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--036.jpg b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--036.jpg deleted file mode 100644 index ad5e3bcb7..000000000 Binary files a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/image--036.jpg and /dev/null differ diff --git a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/index.md b/doc/Articles/CommunityGuides/MirrorQuickStartGuide/index.md deleted file mode 100644 index 4027cc063..000000000 --- a/doc/Articles/CommunityGuides/MirrorQuickStartGuide/index.md +++ /dev/null @@ -1,737 +0,0 @@ -# Mirror Quick Start Guide -Written by [StephenAllenGames.co.uk](http://stephenallengames.co.uk/)
-Edited by [James Frowen](https://github.com/James-Frowen) -*** -This guide currently shows you: -- [Basic scene setup](#part-1) -- [Player movement](#part-4) -- [Names and colours](#part-8) -- [Scene script with canvas buttons](#part-11) -- [Weapon switching](#part-12) -- [Networked scene objects tweak](#part-15) -- [Menu and scene switching](#part-16) -- [Weapon firing](#part-20) - -It is best to first make a mini practice game before converting your single player game, or creating your ideal brand new multiplayer. - -The Pre-made Mirror examples are great for using as reference, it is recommend to use them regarding connection setup, with ports and firewalls. This can be a huge topic that changes from person to person, and is not covered in this guide, here we will use localHost (multiple games on same PC). - - - -## Part 1 - -Blank Project, import Mirror from [Asset Store](https://assetstore.unity.com/packages/tools/network/mirror-129321). - - - -## Part 2 - -- Create new scene, save it, and add it to build settings -- Create a new GameObject, name it NetworkManager in the scene, and add these 3 components - - NetworkManager - - TelepathyTransport - - NetworkManagerHUD -- On the NetworkManager component, drag your Offline and Online scene into the slots, we have only one scene -for now, so put your scene in both - - The scene must be in the build settings before dragging it to the field - -![](./image--000.jpg) - -![](./image--001.jpg) - - - -## Part 3 - -Setup the scene -- Add a simple Plane floor with: - - positions (0, -1, 0) - - scale (2, 2, 2) -- (optional) add a material to this, I added one called dirt that is used one of mirrors examples -- Next we add a GameObject, name does not matter -- Add `NetworkStartPosition` component to this GameObject -- Duplicate the GameObject a few times, and scatter around your scene floor so that you have multiple spawn points. I did 4, one near each corner - -![](./image--002.jpg) - - -## Part 4 - -Creating the player -- Create a capsule using the menus as shown in the image -- Attached a NetworkTransform component, this will auto add a Network Identity -- Tick Client Authority on the NetworkTransform - -![](./image--003.jpg) - -- Rename that object Player -- Add an empty PlayerScript -- Drag into Project to create a prefab -- Then delete Player from scene - -![](./image--004.jpg) - -- Drag your player prefab into Network manager, -- Set spawn method to Round Robin. - -![](./image--005.jpg) - - - -## Part 5 - -Add the following to your PlayerScript. -```cs -using Mirror; -using UnityEngine; - -namespace QuickStart -{ - public class PlayerScript : NetworkBehaviour - { - public override void OnStartLocalPlayer() - { - Camera.main.transform.SetParent(transform); - Camera.main.transform.localPosition = new Vector3(0, 0, 0); - } - - void Update() - { - if (!isLocalPlayer) { return; } - - float moveX = Input.GetAxis("Horizontal") * Time.deltaTime * 110.0f; - float moveZ = Input.GetAxis("Vertical") * Time.deltaTime * 4f; - - transform.Rotate(0, moveX, 0); - transform.Translate(0, 0, moveZ); - } - } -} -``` - - -## Part 6 - -Press play in Unity editor, and then Host (server + client) button in the game window. You should be able to move around with a first person view capsule. - -![](./image--006.jpg) - - - -## Part 7 - -Build and run your scene, open it, host on one, and press the Client button on the other. Congrats you made a mini multiplayer game! - -![](./image--007.jpg) - - - -## Part 8 - -Player name above heads -- Inside your player Prefab, create an empty GameObject -- name it something like `FloatingInfo` - - position Y to 1.5 - - scale X to -1 -- Inside that `FloatingInfo`, create a 3D text using Unity menu (GameObject - 3D Object - 3D Text), -- Set it up as shown in the picture below - -![](./image--008.jpg) - - - -## Part 9 - -Update your PlayerScript.cs with this: -```cs -using Mirror; -using UnityEngine; - -namespace QuickStart -{ - public class PlayerScript : NetworkBehaviour - { - public TextMesh playerNameText; - public GameObject floatingInfo; - - private Material playerMaterialClone; - - [SyncVar(hook = nameof(OnNameChanged))] - public string playerName; - - [SyncVar(hook = nameof(OnColorChanged))] - public Color playerColor = Color.white; - - void OnNameChanged(string _Old, string _New) - { - playerNameText.text = playerName; - } - - void OnColorChanged(Color _Old, Color _New) - { - playerNameText.color = _New; - playerMaterialClone = new Material(GetComponent().material); - playerMaterialClone.color = _New; - GetComponent().material = playerMaterialClone; - } - - public override void OnStartLocalPlayer() - { - Camera.main.transform.SetParent(transform); - Camera.main.transform.localPosition = new Vector3(0, 0, 0); - - floatingInfo.transform.localPosition = new Vector3(0, -0.3f, 0.6f); - floatingInfo.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); - - string name = "Player" + Random.Range(100, 999); - Color color = new Color(Random.Range(0f, 1f), Random.Range(0f, 1f), Random.Range(0f, 1f)) - CmdSetupPlayer(name, color); - } - - [Command] - public void CmdSetupPlayer(string _name, Color _col) - { - // player info sent to server, then server updates sync vars which handles it on all clients - playerName = _name; - playerColor = _col; - } - - void Update() - { - if (!isLocalPlayer) - { - // make non-local players run this - floatingInfo.transform.LookAt(Camera.main.transform); - return; - } - - float moveX = Input.GetAxis("Horizontal") * Time.deltaTime * 110.0f; - float moveZ = Input.GetAxis("Vertical") * Time.deltaTime * 4f; - - transform.Rotate(0, moveX, 0); - transform.Translate(0, 0, moveZ); - } - } -} -``` - - - -## Part 10 - -Add the `PlayerNameText` and `FloatingInfo` objects into the script on the player prefab, as shown below. - -![](./image--009.jpg) - -Now if you build and run, host on one, join on the other, you will see player names and colors synced across the network! - -Well done, 5 stars to you! - -![](./image--010.jpg) - - - -## Part 11 - -A scene networked object all can access and adjust. - -Create a SceneScript.cs, add it onto an empty GameObject in the scene called SceneScript. - -Then create a Canvas with text and button, similar to below. - -![](./image--011.jpg) - -Add the sceneScript variable, Awake function, and CmdSendPlayerMessage to PlayerScript.cs -Also add the new playerName joined line to CmdSetupPlayer(); -```cs -private SceneScript sceneScript; - -void Awake() -{ - //allow all players to run this - sceneScript = GameObject.FindObjectOfType(); -} -[Command] -public void CmdSendPlayerMessage() -{ - if (sceneScript) - { - sceneScript.statusText = $"{playerName} says hello {Random.Range(10, 99)}"; - } -} -[Command] -public void CmdSetupPlayer(string _name, Color _col) -{ - //player info sent to server, then server updates sync vars which handles it on all clients - playerName = _name; - playerColor = _col; - sceneScript.statusText = $"{playerName} joined."; -} -public override void OnStartLocalPlayer() -{ - sceneScript.playerScript = this; - //. . . . ^ new line to add here -``` - -Add this code to SceneScript.cs - -```cs -using Mirror; -using UnityEngine; -using UnityEngine.UI; - -namespace QuickStart -{ - public class SceneScript : NetworkBehaviour - { - public Text canvasStatusText; - public PlayerScript playerScript; - - [SyncVar(hook = nameof(OnStatusTextChanged))] - public string statusText; - - void OnStatusTextChanged(string _Old, string _New) - { - //called from sync var hook, to update info on screen for all players - canvasStatusText.text = statusText; - } - - public void ButtonSendMessage() - { - if (playerScript != null) - { - playerScript.CmdSendPlayerMessage(); - } - } - } -} -``` - - -- Attach the ButtonSendMessage function to your Canvas Button. -- Attach Canvas Scene Text to SceneScript variable. - - ignore SceneScript’s, playerScript variable, it automatically sets this! -- Attach a NetworkIdentity component to the SceneScript gameobject, if it has not automatically done so. - -![](./image--012.jpg) -![](./image--013.jpg) - -Now if you build and run, host and join, you can send messages, and have a text log for actions! - -Wahooo! - -![](./image--014.jpg) -![](./image--015.jpg) - -Experiment and adjust, have fun! - -![](./image--016.jpg) - - -## Part 12 - -Weapon switching! The code bits. - -Add the following to your PlayerScript.cs -```cs -private int selectedWeaponLocal = 1; -public GameObject[] weaponArray; - -[SyncVar(hook = nameof(OnWeaponChanged))] -public int activeWeaponSynced = 1; - -void OnWeaponChanged(int _Old, int _New) -{ - // disable old weapon - // in range and not null - if (0 < _Old && _Old < weaponArray.Length && weaponArray[_Old] != null) - { - weaponArray[_Old].SetActive(false); - } - - // enable new weapon - // in range and not null - if (0 < _New && _New < weaponArray.Length && weaponArray[_New] != null) - { - weaponArray[_New].SetActive(true); - } -} - -[Command] -public void CmdChangeActiveWeapon(int newIndex) -{ - activeWeaponSynced = newIndex; -} - -void Awake() -{ - // disable all weapons - foreach (var item in weaponArray) - { - if (item != null) - { - item.SetActive(false); - } - } -} -``` -Add the weapon switch button in update. Only local player switches its own weapon, so it goes below the `!isLocalPlayer` check. -```cs -void Update() -{ - if (!isLocalPlayer) - { - // make non-local players run this - floatingInfo.transform.LookAt(Camera.main.transform); - return; - } - - float moveX = Input.GetAxis("Horizontal") * Time.deltaTime * 110.0f; - float moveZ = Input.GetAxis("Vertical") * Time.deltaTime * 4f; - - transform.Rotate(0, moveX, 0); - transform.Translate(0, 0, moveZ); - - if (Input.GetButtonDown("Fire2")) //Fire2 is mouse 2nd click and left alt - { - selectedWeaponLocal += 1; - - if (selectedWeaponLocal > weaponArray.Length) - { - selectedWeaponLocal = 1; - } - - CmdChangeActiveWeapon(selectedWeaponLocal); - } -} -``` - - - -## Part 13 - -Weapon models - -Add the basic cube weapons first, change these later. - -- Double click your player prefab to enter it -- Add a "WeaponsHolder" empty GameObject, with position and rotation at 0,0,0. -- Inside that GameObject, create a cube from unity menu, (GameObject, 3D object, cube)- Remove the box colliders. -- Rename this `Weapon1`, change position and scale to match the below pictures. - -![](./image--017.jpg) - -Duplicate weapon 1 for a Weapon 2, and change its scale and position, now you should have 2 different looking ‘weapons’! - -![](./image--018.jpg) - - -## Part 14 - -Weapon switch finale. - -- Add these 2 GameObjects to your PlayerScript.cs weapons array. -- Disable weapon 2, so only weapon 1 shows when spawning. - -![](./image--019.jpg) - -Build and run! - -You should see each player switching weapons, and whatever your player has equipped, will auto show on new joining players (sync var and hook magic!) - -![](./image--020.jpg) - - - - -## Part 15 - -Here we will make a small adjustment, as using a GameObject.Find() may not guarantee Network Identity scene objects are found. -In the image below you can see our NetworkIdentity scene object gets disabled, as they are disabled until a player is in ‘ready’ status (ready status is usually set when player spawns). - -![](./image--021.jpg) - -So our chosen workaround is to have our GameObject.Find() get the non-networked scene object, which will have those Network Identity scene object as pre-set variables. - -Create a new script called SceneReference.cs, and add this one variable. - -```cs -using UnityEngine; - -namespace QuickStart -{ - public class SceneReference : MonoBehaviour - { - public SceneScript sceneScript; - } -} -``` - -Open up SceneScript.cs and add the following variable. - -```cs -public SceneReference sceneReference; -``` - -Now in your Unity scene create a gameobject, name it SceneReference, and add the new script. -On both Scene gameobjects, set the reference to each other. -So SceneReference can speak to SceneScript, and SceneScript to SceneReference. - -![](./image--022.jpg) - -Open up PlayerScript.cs and overwrite the Awake function to this: - -```cs -void Awake() -{ - //allows all players to run this - sceneScript = GameObject.Find(“SceneReference”).GetComponent().sceneScript; -} -``` - - - -## Part 16 - -Menu and Scene switching, here we will go from an offline Menu, with a play button, to a Games List with a back button and the Host/Join HUD, to your online map, and then a second map for host to switch to. - -Open up SceneScript.cs and add the following function. - -```cs -public void ButtonChangeScene() -{ - if (isServer) - { - Scene scene = SceneManager.GetActiveScene(); - if (scene.name == "MyScene") { NetworkManager.singleton.ServerChangeScene("MyOtherScene"); }
 - else { NetworkManager.singleton.ServerChangeScene("MyScene"); } - } - else { Debug.Log("You are not Host."); } -} -``` - -![](./image--023.jpg) - -Duplicate your previous Canvas button, rename it and reposition it, then setup the OnClick() to point to SceneScript.ButtonChangeScene, like in the image. - -Then drag your NetworkManager into your Project, to make it a Prefab, this way any changes we make later will apply to them all. -If you haven’t already, you can sort out your project into folders, one for scripts, prefabs, scenes, textures etc. :) - -![](./image--024.jpg) - -## Part 17 - -Save, and then Duplicate your MyScene, rename to make a Menu, GamesList and MyOtherScene, then add them to the build settings, with Menu being first. - -![](./image--025.jpg) - -Open up the Menu scene, remove the spawn points, SceneScript, SceneReference, Network Manager and Plane, so it looks like the below. -Adjust the canvas button to say Play, centre it. -Here is where you could add the Scores scene, Contact section, News, etc - -Create a Menu.cs script, add it onto a Menu gameObject. - -![](./image--026.jpg) - -Add the code to Menu.cs, then in the Button, drag the Menu gameobject into the On Click () and set it to Menu.LoadScene, like in the picture. - -```cs -using UnityEngine; -using UnityEngine.SceneManagement; - -namespace QuickStart -{ - public class Menu : MonoBehaviour - { - public void LoadScene() - { - SceneManager.LoadScene("GamesList"); - } - } -} -``` - -![](./image--027.jpg) - -## Part 18 - -Open up GamesList scene, do similar to Menu but KEEP NetworkManager prefab. - -Create a GamesList.cs, add the code, and add it onto a GamesList gameobject in the scene. -Adjust a canvas button to say Menu (this is our back button). It should look like the image below. - -- The games list is where you can add List server contents, or matchmaker, or just the host and join buttons, similar to the default NetworkManagerHud, for now leave this. :) - -```cs -using UnityEngine; -using UnityEngine.SceneManagement; - -namespace QuickStart -{ - public class GamesList : MonoBehaviour - { - public void LoadScene() - { - SceneManager.LoadScene("Menu"); - } - } -} -``` - -![](./image--028.jpg) - -## Part 19 - -Open MyOtherScene, this is our second map. -Change the camera background colour and floor material (or anything, just so you can see both scenes are different. -To summarise, MyScene is map 1 and MyOtherScene is map 2. - -![](./image--029.jpg) - -In your NetworkManager prefab in PROJECT (not the one in scenes), add Menu to offline, and MyScene to Online variables. This should change all the NetworkManager prefabs to have these settings. - -![](./image--030.jpg) - -Build and Run, press Play on the Menu to go to GamesList, then click Host (for player 1). -For player 2, press Play on Menu, then client connect on GamesList. - -Now the host can change scenes between map 1 and map 2, and if anyone disconnects or stops the game, Menu scene is load to start again. -This whole process can be tidied up, but should provide a good scene switch template to your Mirror game :) - - - -## Part 20 - -Here we will add basic weapon firing, using rigidbody prefabs. -Raycasts with a representation of the fired object is usually better to do this, and keep phycisal objects for things like Grenades and Cannon balls. -This section will also lack a lot of security and ant-cheat techniques in order to keep the guide simple, but anyway, here we go! - -Double click the Player Prefab to open it, create empty gameobjects and line them up with the end of your weapon, add them as child to each weapon. -Some weapons may be short pistols, others long rifles, so the place where objects spawn will be different. - -![](./image--031.jpg) - -Create a Weapon.cs script, add it to the Weapon1 and Weapon 2 gameObjects inside the player prefab. - -```cs -using UnityEngine; - -namespace QuickStart -{ - public class Weapon : MonoBehaviour - { - public float weaponSpeed = 15.0f; - public float weaponLife = 3.0f; - public float weaponCooldown = 1.0f; - public int weaponAmmo = 15; - - public GameObject weaponBullet; - public Transform weaponFirePosition; - } -} -``` - -## Part 21 - -Now back in your scene we shall make 2 bullets, in Unitys menu, go to GameObject, 3D Object, Sphere. -Add rigidbody to this sphere, make the scale 0.2, 0.2, 0.2, then save it as a Prefab in the Project.
Do the same with a cube, so you have two different looking bullets. - -![](./image--032.jpg) - -Inside your player prefab again, select a weapon, and set the variables on weapon script. - -![](./image--033.jpg) -![](./image--034.jpg) - -## Part 22 -In SceneScript.cs, add this variable and function. - -```cs -public Text canvasAmmoText; - -public void UIAmmo(int _value) -{ - canvasAmmoText.text = "Ammo: " + _value; -} -``` - -Enter MyScene (map 1). -Duplicate the Canvas StatusText, rename to Ammo, then drag that Ammo text UI into SceneScript gameobject, canvasAmmoText variable. -Do this on BOTH MyScene (map 1) and MyOtherScene (map 2), as we have not yet linked or prefabbed our canvas and scene scripts to auto update changes on each map. - -![](./image--035.jpg) - -Open up PlayerScript.cs, add these two variables: - -```cs -private Weapon activeWeapon; -private float weaponCooldownTime; -``` - -In the ‘OnWeaponChanged’ function, update it with the new line, so it should look like this.
 - -```cs -void OnWeaponChanged(int _Old, int _New) -{ - // disable old weapon - // in range and not null - if (0 < _Old && _Old < weaponArray.Length && weaponArray[_Old] != null) - { - weaponArray[_Old].SetActive(false); - } - - // enable new weapon - // in range and not null - if (0 < _New && _New < weaponArray.Length && weaponArray[_New] != null) - { - weaponArray[_New].SetActive(true); - activeWeapon = weaponArray[activeWeaponSynced].GetComponent(); - if( isLocalPlayer ) { sceneScript.UIAmmo(activeWeapon.weaponAmmo); } - } -} -``` - -In Awake(), add this at the end: - -```cs -if (selectedWeaponLocal < weaponArray.Length && weaponArray[selectedWeaponLocal] != null) -{ activeWeapon = weaponArray[selectedWeaponLocal].GetComponent(); sceneScript.UIAmmo(activeWeapon.weaponAmmo); } -``` - -In Update(), add this at the end: - -```cs -if (Input.GetButtonDown("Fire1") ) //Fire1 is mouse 1st click -{ - if (activeWeapon && Time.time > weaponCooldownTime && activeWeapon.weaponAmmo > 0) - { - weaponCooldownTime = Time.time + activeWeapon.weaponCooldown; - activeWeapon.weaponAmmo -= 1; - sceneScript.UIAmmo(activeWeapon.weaponAmmo); - CmdShootRay(); - } -} -``` - -Add these two functions after the Update() {} function finishes. - -```cs -[Command] -void CmdShootRay() -{ - RpcFireWeapon(); -} - -[ClientRpc] -void RpcFireWeapon() -{ - //bulletAudio.Play(); muzzleflash etc - var bullet = (GameObject)Instantiate(activeWeapon.weaponBullet, activeWeapon.weaponFirePosition.position, activeWeapon.weaponFirePosition.rotation); - bullet.GetComponent().velocity = bullet.transform.forward * activeWeapon.weaponSpeed; - if (bullet) { Destroy(bullet, activeWeapon.weaponLife); } -} -``` - -Build and Run, you should have firing, with different speeds and cooldowns on all players :) - -![](./image--036.jpg) diff --git a/doc/Articles/CommunityGuides/index.md b/doc/Articles/CommunityGuides/index.md deleted file mode 100644 index 65b3682c4..000000000 --- a/doc/Articles/CommunityGuides/index.md +++ /dev/null @@ -1,8 +0,0 @@ -# Community Guides - -This section contains guides written by the community rather than by the developers themselves - -- [Mirror Quick Start Guide](./MirrorQuickStartGuide/index.md) by [StephenAllenGames.co.uk](http://stephenallengames.co.uk/) - - -> If you want to submit a guide either create a [Pull request](https://github.com/vis2k/Mirror/pulls) or ask in the discord diff --git a/doc/Articles/CommunityGuides/toc.yml b/doc/Articles/CommunityGuides/toc.yml deleted file mode 100644 index 27adb7f39..000000000 --- a/doc/Articles/CommunityGuides/toc.yml +++ /dev/null @@ -1,4 +0,0 @@ -- name: Overview - href: index.md -- name: Mirror Quick Start Guide - href: MirrorQuickStartGuide/index.md diff --git a/doc/Articles/Components/Authenticators/Basic.md b/doc/Articles/Components/Authenticators/Basic.md deleted file mode 100644 index 243e4311c..000000000 --- a/doc/Articles/Components/Authenticators/Basic.md +++ /dev/null @@ -1,11 +0,0 @@ -# Basic Authenticator - -Mirror includes a Basic Authenticator in the Mirror / Authenticators folder which just uses a simple username and password. -- Drag the Basic Authenticator script to the inspector of the object in your scene that has Network Manager -- The Basic Authenticator component will automatically be assigned to the Authenticator field in Network Manager - -When you're done, it should look like this: - -![Inspector showing Basic Authenticator component](Basic.png) - -> **Note:** You don't need to assign anything to the event lists unless you want to subscribe to the events in your own code for your own purposes. Mirror has internal listeners for both events. diff --git a/doc/Articles/Components/Authenticators/Basic.png b/doc/Articles/Components/Authenticators/Basic.png deleted file mode 100644 index 735912cdc..000000000 Binary files a/doc/Articles/Components/Authenticators/Basic.png and /dev/null differ diff --git a/doc/Articles/Components/Authenticators/index.md b/doc/Articles/Components/Authenticators/index.md deleted file mode 100644 index 973a7d771..000000000 --- a/doc/Articles/Components/Authenticators/index.md +++ /dev/null @@ -1,66 +0,0 @@ -# Authentication - -When you have a multiplayer game, often you need to store information about your player for later games, keep game stats or communicate with your friends. For all these use cases, you often need a way to uniquely identify a user. Being able to tell users apart is called authentication. There are several methods available, some examples include: -- Ask the user for username and password -- Use a third party OAuth2 or OpenID identity provider, such as Facebook, Twitter, Google -- Use a third party service such as PlayFab, GameLift or Steam -- Use the device id, very popular method in mobile -- Use Google Play in Android -- Use Game Center in IOS -- Use a web service in your website - -## Encryption Notice - -By default Mirror uses Kcp Transport, which is not encrypted, so if you want to do authentication through Mirror, we highly recommend you use a transport that supports encryption. - -## Basic Authenticator - -- [Basic Authenticator](Basic.md) - Mirror includes a Basic Authenticator in the Mirror / Authenticators folder which just uses a simple username and password. - -## Custom Authenticators - -Authenticators are derived from an `Authenticator` abstract class that allows you to implement any authentication scheme you need. - -From the Assets menu, click Create > Mirror > Network Authenticator to make your own custom Authenticator from our [Script Templates](../../General/ScriptTemplates.md), -and just fill in the messages and validation code to suit your needs. -When a client is successfully authenticated, call `ServerAccept(conn);` on the server and `ClientAccept(conn);` on the client. -To reject a client call `ServerReject(conn);` on the server and `ClientReject(conn);` on the client. -Mirror will responde to these method calls to proceed accordingly with completing the connection (or disconnecting) the client. -Subscribe to OnServerAuthenticated and OnClientAuthenticated events if you wish to perform additional steps after authentication. - -## Message Registration - -By default all messages registered to `NetworkServer` and `NetworkClient` require authentication unless explicitly indicated otherwise. To register messages to bypass authentication, you need to specify `false` for a bool parameter to the `RegisterMessage` method: - -``` -NetworkServer.RegisterHandler(OnAuthRequestMessage, false); -``` - -Certain internal messages already have been set to bypass authentication: - -- Server - - `ConnectMessage` - - `DisconnectMessage` - - `ErrorMessage` - - `NetworkPingMessage` -- Client - - `ConnectMessage` - - `DisconnectMessage` - - `ErrorMessage` - - `SceneMessage` - - `NetworkPongMessage` - -### Tips - -- Register handlers for messages in `OnStartServer` and `OnStartClient`. They're called from StartServer/StartHost, and StartClient, respectively. -- Send a message to the client if authentication fails, especially if there's some issue they can resolve. -- Call the `Disconnect()` method of the `NetworkConnection` on the server and client when authentication fails. If you want to give the user a few tries to get their credentials right, you certainly can, but Mirror will not do the disconnect for you. - - Remember to put a small delay on the Disconnect call on the server if you send a failure message so that it has a chance to be delivered before the connection is dropped. -- `NetworkConnection` has an `authenticationData` object where you can drop any data you need to persist on the server related to the authentication, such as account id's, tokens, character selection, etc. - -Now that you have the foundation of a custom Authenticator component, the rest is up to you. You can exchange any number of custom messages between the server and client as necessary to complete your authentication process before approving the client. - -Authentication can also be extended to character selection and customization, just by crafting additional messages and exchanging them with the client before completing the authentication process. This means this process takes place before the client player actually enters the game or changes to the Online scene. - -If you write a good authenticator, consider sharing it with other users or donating it to the Mirror project. diff --git a/doc/Articles/Components/Authenticators/toc.yml b/doc/Articles/Components/Authenticators/toc.yml deleted file mode 100644 index 725e55455..000000000 --- a/doc/Articles/Components/Authenticators/toc.yml +++ /dev/null @@ -1,4 +0,0 @@ -- name: Overview - href: index.md -- name: Basic Authenticator - href: Basic.md diff --git a/doc/Articles/Components/LogLevelWindow.png b/doc/Articles/Components/LogLevelWindow.png deleted file mode 100644 index 9499206cf..000000000 Binary files a/doc/Articles/Components/LogLevelWindow.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkAddressAndPortSettings.png b/doc/Articles/Components/NetworkAddressAndPortSettings.png deleted file mode 100644 index 9900aca15..000000000 Binary files a/doc/Articles/Components/NetworkAddressAndPortSettings.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkAnimator.md b/doc/Articles/Components/NetworkAnimator.md deleted file mode 100644 index cb318b197..000000000 --- a/doc/Articles/Components/NetworkAnimator.md +++ /dev/null @@ -1,26 +0,0 @@ -# Network Animator - -The Network Animator component allows you to synchronize animation states for networked objects. It synchronizes state and parameters from an Animator Controller. - -Note that if you create a Network Animator component on an empty game object, Mirror also creates a Network Identity component and an Animator component on that game object. - -![The Network Animator component in the Inspector window](NetworkAnimatorComponent.png) - -- **Client Authority** - Enable this to have changes to animation parameters sent from client to server. - -- **Animator** - Use this field to define the Animator component you want the Network Animator to synchronize with. - -Normally, changes are sent to all observers of the object this component is on. Setting **Sync Mode** to Owner Only makes the changes private between the server and the client owner of the object. - -You can use the **Sync Interval** to specify how often it syncs (in seconds). - -## Details - -The Network Animator ensures the synchronization of game object animation across the network, meaning that all players see the animation happen at the same. There are two kinds of authority for networked animation (see documentation on [network authority](../Guides/Authority.md)): - -> **NOTE:** Animator Triggers are not synced directly. Call `NetworkAnimator.SetTrigger` instead. A game object with authority can use the SetTrigger function to fire an animation trigger on other clients. - -- If the game object has authority on the client, you should animate it locally on the client that owns the game object. That client sends the animation state information to the server, which broadcasts it to all the other clients. For example, this may be suitable for player characters with client authority. -- If the game object has authority on the server, then you should animate it on the server. The server then sends state information to all clients. This is common for animated game objects that are not related to a specific client, such as scene objects and non-player characters, or server-authoritative clients. diff --git a/doc/Articles/Components/NetworkAnimatorComponent.png b/doc/Articles/Components/NetworkAnimatorComponent.png deleted file mode 100644 index 55d99e8a4..000000000 Binary files a/doc/Articles/Components/NetworkAnimatorComponent.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkDiscovery.md b/doc/Articles/Components/NetworkDiscovery.md deleted file mode 100644 index 52d692ce9..000000000 --- a/doc/Articles/Components/NetworkDiscovery.md +++ /dev/null @@ -1,119 +0,0 @@ -# Network Discovery - -Suppose your are next to a friend. He starts a game in host mode and you want to join him. How will your phone locate his? Finding out his IP address is not exactly intuitive or something kids can do. - -To solve this problem you can use Network Discovery. When your game starts, it sends a message in your current network asking "Is there any server available?". Any server within the same network will reply and provide information about how to connect to it. - -Mirror comes with a simple implementation of Network Discovery you can simply use in your game. It also provides a way for you to extend it so that you can pass additional data during the discovery phase. - -![Inspector](NetworkDiscovery.png) - -NetworkDiscovery and NetworkDiscoveryHUD components are included, or you can make your own from a [ScriptTemplate](../General/ScriptTemplates.md). - -Network Discovery uses a UDP broadcast on the LAN enabling clients to find the running server and connect to it. - -When a server is started, it listens on the UDP Broadcast Listen Port for requests from clients and returns a connection URI that clients apply to their transport. - -You can adjust how often the clients send their requests out to find a server in seconds with the Active Discovery Interval. - -The Server Found event must be assigned to a handler method, e.g. the OnDiscoveredServer method of NetworkDiscoveryHUD. - -In the NetworkDiscoveryHUD, the NetworkDiscovery component should be assigned automatically. - -## Quick Start - -To use Network Discovery follow these steps: - -1. Create a gameobject with a NetworkManager if you have not done so already -2. Do not add a NetworkManagerHUD. Discovery has a different UI component. -3. Add a NetworkDiscoveryHUD component to the NetworkManager gameobject. - A NetworkDiscovery component will be automatically added and wired up to your HUD. -4. Add a player to the NetworkManager if you have not done so. -5. Build and run a standalone version -6. Click on Start Host -7. Start play mode in the editor and click on Find Servers -8. The editor should find the standalone version and display a button -9. Click on the button to connect to it. - -The NetworkDiscoveryHUD is provided as a simple and quick way to get started, but you will probably want to replace it with your own user interface. - -## Custom Network Discovery - -You can completely replace the user interface by adding your own interface (typically Unity UI based) instead of the default NetworkDiscoveryHUD. You do still need the NetworkDiscovery component to do the heavy lifting. - -Sometimes you want to provide more information in the discovery messages. Some use cases could include: - -- The client can show if the server is in PvP or PvE mode -- The client can show how full the servers are. -- The client can show the ping to each server so the player can chose the fastest server -- The client can show the language -- The client can show if the server is password protected - -To do this, we've provided a [Template](../General/ScriptTemplates.md), so from the Assets menu, click Create > Mirror > Network Discovery. - -This will create a script in your project with 2 empty message classes and a custom NetworkDiscovery class that inherits from NetworkDiscoveryBase and has all the override methods included and documented for you. - -The message classes define what is sent between the client and server. As long as you keep your messages simple using the [data types](../Guides/DataTypes.md) that Mirror can serialize, you won't need to write custom serializers for them. - -```cs -public struct DiscoveryRequest : NetworkMessage -{ - public string language; - - // Add properties for whatever information you want sent by clients - // in their broadcast messages that servers will consume. -} - -enum GameMode {PvP, PvE}; - -public struct DiscoveryResponse : NetworkMessage -{ - // you probably want uri so clients know how to connect to the server - public Uri uri; - - public GameMode GameMode; - public int TotalPlayers; - public int HostPlayerName; - - // Add properties for whatever information you want the server to return to - // clients for them to display or consume for establishing a connection. -} -``` - -The custom NetworkDiscovery class contains the overrides for handling the messages above. - -You may want to refer to the NetworkDiscovery.cs script in the Components/Discovery folder to see how these should be implemented. - -```cs -public class NewNetworkDiscovery: NetworkDiscoveryBase -{ - #region Server - - protected override void ProcessClientRequest(DiscoveryRequest request, IPEndPoint endpoint) - { - base.ProcessClientRequest(request, endpoint); - } - - protected override DiscoveryResponse ProcessRequest(DiscoveryRequest request, IPEndPoint endpoint) - { - // TODO: Create your response and return it - return new DiscoveryResponse(); - } - - #endregion - - #region Client - - protected override DiscoveryRequest GetRequest() - { - return new DiscoveryRequest(); - } - - protected override void ProcessResponse(DiscoveryResponse response, IPEndPoint endpoint) - { - // TODO: a server replied, do something with the response such as invoking a unityevent - } - - #endregion -} -``` diff --git a/doc/Articles/Components/NetworkDiscovery.png b/doc/Articles/Components/NetworkDiscovery.png deleted file mode 100644 index 5adbc166b..000000000 Binary files a/doc/Articles/Components/NetworkDiscovery.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkGame3Instances.jpg b/doc/Articles/Components/NetworkGame3Instances.jpg deleted file mode 100644 index e5cf1fd7e..000000000 Binary files a/doc/Articles/Components/NetworkGame3Instances.jpg and /dev/null differ diff --git a/doc/Articles/Components/NetworkHeadlessLogger.md b/doc/Articles/Components/NetworkHeadlessLogger.md deleted file mode 100644 index 0a61dc2ba..000000000 --- a/doc/Articles/Components/NetworkHeadlessLogger.md +++ /dev/null @@ -1,9 +0,0 @@ -# Network Headless Logger - -Network Headless Logger replaces the the default log handler with one that set `Console.ForegroundColor`. - -Only replaces the handler when running in headless mode. - -![Inspector](NetworkHeadlessLogger.png) - -`showExceptionStackTrace` will log the stack trace of any exceptions sent to the handler. \ No newline at end of file diff --git a/doc/Articles/Components/NetworkHeadlessLogger.png b/doc/Articles/Components/NetworkHeadlessLogger.png deleted file mode 100644 index 53bd4d0a3..000000000 Binary files a/doc/Articles/Components/NetworkHeadlessLogger.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkIdentity.PNG b/doc/Articles/Components/NetworkIdentity.PNG deleted file mode 100644 index eb79948b6..000000000 Binary files a/doc/Articles/Components/NetworkIdentity.PNG and /dev/null differ diff --git a/doc/Articles/Components/NetworkIdentity.md b/doc/Articles/Components/NetworkIdentity.md deleted file mode 100644 index a37402afb..000000000 --- a/doc/Articles/Components/NetworkIdentity.md +++ /dev/null @@ -1,31 +0,0 @@ -# Network Identity - -**See also in the API Reference.** - -The Network Identity component is at the heart of the Unity networking high-level API. It controls a game object’s unique identity on the network, and it uses that identity to make the networking system aware of the game object. It offers two different options for configuration and they are mutually exclusive, which means either one of the options or none can be checked. -- **Server Only** - Tick this checkbox to ensure that Unity only spawns the game object on the server, and not on clients. - -![Inspector](NetworkIdentity.PNG) - -## Instantiated Network Game Objects - -With the Mirror’s server-authoritative networking system, the server must spawn networked game objects with network identities, using `NetworkServer.Spawn`. This automatically creates them on clients that are connected to the server, and assigns them a `netId`. - -You must put a Network Identity component on any Prefabs that spawn at runtime for the network system to use them. See [Object Spawning](../Guides/GameObjects/SpawnObject.md) for more information. - -## Scene-based Network Game Objects - -You can also network game objects that are saved as part of your Scene (for example, environmental props). Networking game objects makes them behave slightly differently, because you need to have them spawn across the network. - -When building your game, Unity disables all Scene-based game objects with Network Identity components. When a client connects to the server, the server sends spawn messages to tell the client which Scene game objects to enable and what their most up-to-date state information is. This ensures the client’s game does not contain game objects at incorrect locations when they start playing, or that Unity does not spawn and immediately destroy game objects on connection (for example, if an event removed the game object before that client connected). See [Networked Scene Game Objects](../Guides/GameObjects/SceneObjects.md) for more information. - -## Preview Pane Information - -This component contains network tracking information, and displays that information in the preview pane. For example, the scene ID, network ID and asset ID the object has been assigned. This allows you to inspect the information which can be useful for investigation and debugging. - -![Preview](NetworkIdentityPreview.png) - -At runtime there is more information to display here (a disabled NetworkBehaviour is displayed non-bold): - -![Runtime Preview](NetworkIdentityPreviewRuntime.png) diff --git a/doc/Articles/Components/NetworkIdentityPreview.png b/doc/Articles/Components/NetworkIdentityPreview.png deleted file mode 100644 index 56fe7f7c2..000000000 Binary files a/doc/Articles/Components/NetworkIdentityPreview.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkIdentityPreviewRuntime.png b/doc/Articles/Components/NetworkIdentityPreviewRuntime.png deleted file mode 100644 index 84cd84483..000000000 Binary files a/doc/Articles/Components/NetworkIdentityPreviewRuntime.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkLerpRigidbody.md b/doc/Articles/Components/NetworkLerpRigidbody.md deleted file mode 100644 index 29aa104ef..000000000 --- a/doc/Articles/Components/NetworkLerpRigidbody.md +++ /dev/null @@ -1,15 +0,0 @@ -# Network Lerp Rigidbody - -> The Network Lerp Rigidbody classed as "Experimental" for now so please share any problems or bugs you find with it and use at your own risk if production builds. - -The Network Lerp Rigidbody component synchronizes position and velocity of a rigidbody across the network. This component is useful when you have a non-kinematic rigidbody that have constant forces applied to them, like gravity, but also want to apply forces or change velocity to that rigidbody or server or client with authority. For example, objects that move and jump using rigidbody using gravity. - -A game object with a Network Rigidbody component must also have a Network Identity component. When you add a Network Rigidbody component to a game object, Mirror also adds a Network Identity component on that game object if it does not already have one. - -When using the Network Lerp Rigidbody you should NOT have NetworkTransform on the same object as the Network Lerp Rigidbody will handle syncing the position - -By default, Network Lerp Rigidbody is server-authoritative unless you check the box for **Client Authority**. Client Authority applies to player objects as well as non-player objects that have been specifically assigned to a client, but only for this component. With this enabled, value changes are send from the client to the server. - -Normally, changes are sent to all observers of the object this component is on. Setting **Sync Mode** to Owner Only makes the changes private between the server and the client owner of the object. - -You can use the **Sync Interval** to specify how often it syncs (in seconds). This applies both to Client Authority and Server Authority. diff --git a/doc/Articles/Components/NetworkManager.md b/doc/Articles/Components/NetworkManager.md deleted file mode 100644 index d94b6a673..000000000 --- a/doc/Articles/Components/NetworkManager.md +++ /dev/null @@ -1,93 +0,0 @@ -# Network Manager - -The Network Manager is a component for managing the networking aspects of a multiplayer game. - -The Network Manager features include: -- Game state management -- Spawn management -- Scene management -- Debugging information -- Customization - -**See also in the API Reference.** - -## Getting Started with the Network Manager - -The Network Manager is the core controlling component of a multiplayer game. To get started, create an empty game object in your starting Scene, and add the Network Manager component. The newly added Network Manager component looks like this: - -![The Network Manager as seen in the inspector window](NetworkManagerInspector.png) - -The Inspector for the Network Manager in the Editor allows you to configure and control many things related to networking. - -**Note**: You can only ever have one active Network Manager in each scene because it's a singleton. Do not place the Network Manager component on a networked game object (one which has a Network Identity component), because Mirror disables these when the Scene loads. - -If you are already familiar with multiplayer game development, you might find it useful to know that the Network Manager component is implemented entirely using the API, so everything it does is also available to you through scripting. For advanced users, if you find that you need to expand on the Network Manager component’s features, you can use scripting to derive your own class from Network Manager and customize its behavior by overriding any of the virtual function hooks that it provides. However, the Network Manager component wraps up a lot of useful functionality into a single place, and makes creating, running and debugging multiplayer games as simple as possible. - -## Transports - -Mirror uses a separate component (derived from the Transport class) to connect across the network. By default, it is Kcp Transport. This design choice of separating the transport into its own component allows game developers to choose the transport that best fits their game needs. Changing transports is as simple as swapping out the component on the Network Manager object and assigning it to the Transport field. - -Transports are available for TCP, UDP, WebGL, and Steam. Additionally, there's a Multiplex transport that allows for using two transports together on the server, e.g. Telepathy and WebSockets, so that desktop and browser players can play together on the same server seamlessly. See [Transports](../Transports/index.md) for more information. - -## Game State Management - -A Networking multiplayer game can run in three modes - as a client, as a dedicated server, or as a host which is both a client and a server at the same time. - -If you’re using the Network Manager HUD, it automatically tells the Network Manager which mode to start in, based on which button the player clicks. If you’re writing your own UI that allows the player to start the game, you’ll need to call these from your own code. These methods are: -- NetworkManager.StartClient -- NetworkManager.StartServer -- NetworkManager.StartHost - -![The network address and port settings in the Network Manager and Telepathy components](NetworkAddressAndPortSettings.png) - -Whichever mode the game starts in (client, server, or host), the Network Address and Transport Port properties are used. -- In client mode, the game attempts to connect to the address and port specified. A fully-qualified domain name (FQDN) can also be used for the Network Address, e.g. "game.example.com". -- In server or host mode, the game listens for incoming connections on the port specified, but does not bind to any specific IP address (it listens on all available). - -## Spawn Management - -Use the Network Manager to manage the spawning (networked instantiation) of networked game objects from Prefabs. - -![The “Spawn Info” section of the Network Manager component](NetworkManagerSpawnInfo.png) - -Most games have a Prefab which represents the player, so the Network Manager has a Player Prefab slot. You should assign this slot with your player Prefab. When you have a player Prefab set, a player game object is automatically spawned from that Prefab for each user in the game. This applies to the local player on a hosted server, and remote players on remote clients. You must attach a Network Identity component to the Player Prefab before assigning it to this field. - -Once you have assigned a Player Prefab, you can start the game as a host and see the player game object spawn. Stopping the game destroys the player game object . If you build and run another copy of the game and connect it as a client to *localhost*, the Network Manager makes another player game object appear. When you stop that client, it destroys that player’s game object. - -In addition to the Player Prefab, you must also register other prefabs that you want to dynamically spawn during game play with the Network Manager. - -You can add prefabs to the list shown in the inspector labelled Registered Spawnable Prefabs. You can also register prefabs via code, with the `ClientScene.RegisterPrefab` method. - -If you have one Network Manager that is persisted through scenes via Don't Destroy On Load (DDOL), you need to register all prefabs to it which might be spawned in any scene. If you have a separate Network Manager in each scene, you only need to register the prefabs relevant for that scene. - -## Start Positions - -The Network Manager will spawn Player Prefab at their defined transform position and rotation by default, however the Player Spawn Method property allows you to control how start positions are chosen in conjunction with [Network Start Position](NetworkStartPosition.md) components. -- Choose Random to spawn players at randomly chosen startPosition options. -- Choose Round Robin to cycle through startPosition options in a set list. - -If the Random or Round Robin modes don’t suit your game, you can customize how the start positions are selected by using code. You can access the available Network Start Position components by the list `NetworkManager.startPositions`, and you can use the helper method `GetStartPosition` on the Network Manager that can be used in an implementation of `OnServerAddPlayer` to find a start position. - -## Scene Management - -Most games have more than one scene. At the very least, there is usually a title screen or starting menu scene in addition to the scene where the game is actually played. The Network Manager is designed to automatically manage scene state and scene transitions in a way that works for a multiplayer game. - -There are two slots on the Network Manager inspector for scenes: the Offline Scene and the Online Scene. Dragging scene assets into these slots activates networked Scene Management. - -When a server or host is started, the Online Scene is loaded. This then becomes the current network scene. Any clients that connect to that server are instructed to also load that scene. The name of this scene is stored in the `networkSceneName` property. - -When the network is stopped, by stopping the server or host or by a client disconnecting, the offline Scene is loaded. This allows the game to automatically return to a menu scene when disconnected from a multiplayer game. - -You can also change scenes while the game is active by calling `ServerChangeScene`. This makes all the currently connected clients change Scene too, and updates `networkSceneName` so that new clients also load the new Scene. - -While networked Scene management is active, any calls to game state management functions such as `StartHost` or `StopClient` can cause scene changes. This applies to the runtime control UI. By setting up scenes and calling these methods, you can control the flow of your multiplayer game. - -Note that scene change causes all the game objects in the previous scene to be destroyed. - -You should normally make sure the Network Manager persists between Scenes, otherwise the network connection is broken upon a scene change. To do this, ensure the Don’t Destroy On Load checkbox is ticked in the inspector. However it is also possible to have a separate Network Manager in each scene with different settings, which may be helpful if you wish to control incremental prefab loading, or different scene transitions. - -## Customization - -There are virtual functions on the `NetworkManager` class that you can customize by creating your own derived class that inherits from `NetworkManager`. When implementing these functions, be sure to take care of the functionality that the default implementations provide. For example, in `OnServerAddPlayer`, the function `NetworkServer.AddPlayer` must be called to activate the player game object for the connection. - -To make this easier, we've made a set of [Script Templates](../General/ScriptTemplates.md) that have all the overrides stubbed out for you. diff --git a/doc/Articles/Components/NetworkManagerHUD.md b/doc/Articles/Components/NetworkManagerHUD.md deleted file mode 100644 index a17b45aec..000000000 --- a/doc/Articles/Components/NetworkManagerHUD.md +++ /dev/null @@ -1,65 +0,0 @@ -# Network Manager HUD - -The Network Manager HUD (“heads-up display”) is a quick-start tool to help you start building your multiplayer game straight away, without first having to build a user interface for game creation/connection/joining. It allows you to jump straight into your game play programming, and means you can build your own version of these controls later in your development schedule. - -It is not, however, intended to be included in finished games. The idea is that these controls are useful to get you started, but you should create your own UI later on, to allow your players to find and join games in a way that suits your game. For example, you might want to stylize the design of the screens, buttons and list of available games to match the overall style of your game. - -To start using the Network Manager HUD, either add the component to the same scene object that has the Network Manager component, or create an empty game object in your scene (menu: game object \> Create Empty) and add the Network Manager HUD component to the new game object. - -![The Network Manager HUD component, as viewed in the inspector](NetworkManagerHUDComponent.png) -- **Show GUI** - Tick this checkbox to show the HUD GUI at run time. This allows you to reveal or hide it for quick debugging. -- **Offset X** - Set the horizontal **pixel** offset of the HUD GUI, measured from the left edge of the screen. -- **Offset Y** - Set the vertical pixel offset of the HUD GUI, measured from the top edge of the screen. - -The Network Manager HUD provides the basic functions so that people playing your game can start hosting a networked game, or find and join an existing networked game. Unity displays the Network Manager HUD as a collection of simple UI buttons in the Game view. - -![The Network Manager HUD GUI, as viewed in the Game view](NetworkManagerHUDUI.png) - -## Using the HUD - -The Network Manager HUD starts in Server + Client mode, and displays buttons relating to hosting and joining a multiplayer game. - -### Host (Server + Client) - -Click the Host (Server + Client) button to start a game as a host on the local network. This client is both the host *and* one of the players in the game. It uses the information from the Network Info section in the inspector to host the game. - -When you click this button, the HUD switches to a simple display of network details, and a Stop button which allows you to stop hosting the game and return to the main HUD menu. - -![The Network Manager HUD GUI when hosting a game.](NetworkManagerHUDHostingLAN.png) - -When you have started a game as a host, other players of the game can then connect to the host to join the game. - -Click the Stop button to disconnect from the host. Clicking Stop also returns to the main HUD menu. - -### Client - -To connect to a host on the internet use the text field to the right of the Client button to specify the address of the host. The default host address is “localhost”, which means the client looks on its own computer for the game host. In addition to *localhost*, you can specify an IPv4 address, and IPv6 address, or a fully-qualified domain name (FQDN), e.g. *game.example.com*, and the transport with resolve the name using DNS. Click Client to attempt to connect to the host address you have specified. - -Use the default “localhost” in this field if you are running multiple instances of your game on one computer, to test multiplayer interactivity. To do this, you can create a standalone build of your game, and then launch it multiple times on your computer. This is a common way to quickly test that your networked game interactions are functioning as you expect, without you needing to deploy your game to multiple computers or devices. - -![An example of three instances of a networked game running on the same desktop PC. This is useful for quick tests to ensure networked interactions are behaving as you intended. One is running as Host, and two are running as Client.](NetworkGame3Instances.jpg) - -When you want to test your game on multiple machines you need to put the address of the computer acting as host into the address text field. - -The computer acting as the host needs to tell their IP address to everyone running clients, so that you can type this into the box. For local clients on a LAN, that's the local IP address. For remote clients, that's the WAN IP address of the router of the host. Firewall rules and port-forwarding are generally required for a computer to act as host and accept connections from other computers, whether they're on the LAN or the internet. - -Enter the IP address (or leave it as “localhost” if you are testing it on your own machine), then click Client to attempt to connect to the host. - -When the client is attempting to connect, the HUD displays a Cancel Connection Attempt button. Click this if you want to stop trying to connect to the host. - -![The HUD GUI while attempting a connection](NetworkManagerHUDConnectionAttempt.png) - -If the connection is successful, the HUD displays the Stop button. Click this if you want to stop the game on the client and disconnect from the host: - -![The HUD GUI after a successful connection](NetworkManagerHUDConnected.png) - -### Server Only - -Click Server Only to start a game which acts as a server that other clients can connect to, but which does not act as a client to the game itself. This type of game is often called a “dedicated server”. A user cannot play the game on this particular instance of your game. All players must connect as clients, and nobody plays on the instance that is running as the server. - -A dedicated server results in better performance for all connected players, because the server doesn’t need to process a local player’s game play in addition to acting as server. - -You might also choose this option if you want to host a game that can be played over the internet (rather than just within a local network), but want to maintain control of the server yourself - for example, to prevent cheating by one of the clients, because only the server has authority over the game. To do this, you would need to run the game in Server Only mode on a computer with a public IP address. diff --git a/doc/Articles/Components/NetworkManagerHUDComponent.png b/doc/Articles/Components/NetworkManagerHUDComponent.png deleted file mode 100644 index b5ad9a1b0..000000000 Binary files a/doc/Articles/Components/NetworkManagerHUDComponent.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkManagerHUDConnected.png b/doc/Articles/Components/NetworkManagerHUDConnected.png deleted file mode 100644 index bf536e1a1..000000000 Binary files a/doc/Articles/Components/NetworkManagerHUDConnected.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkManagerHUDConnectionAttempt.png b/doc/Articles/Components/NetworkManagerHUDConnectionAttempt.png deleted file mode 100644 index 1d4ece210..000000000 Binary files a/doc/Articles/Components/NetworkManagerHUDConnectionAttempt.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkManagerHUDHostingLAN.png b/doc/Articles/Components/NetworkManagerHUDHostingLAN.png deleted file mode 100644 index 8d0405a33..000000000 Binary files a/doc/Articles/Components/NetworkManagerHUDHostingLAN.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkManagerHUDUI.png b/doc/Articles/Components/NetworkManagerHUDUI.png deleted file mode 100644 index b2a50d91b..000000000 Binary files a/doc/Articles/Components/NetworkManagerHUDUI.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkManagerInspector.png b/doc/Articles/Components/NetworkManagerInspector.png deleted file mode 100644 index 32c692ff7..000000000 Binary files a/doc/Articles/Components/NetworkManagerInspector.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkManagerSpawnInfo.png b/doc/Articles/Components/NetworkManagerSpawnInfo.png deleted file mode 100644 index fd5a94eee..000000000 Binary files a/doc/Articles/Components/NetworkManagerSpawnInfo.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkMatchChecker.md b/doc/Articles/Components/NetworkMatchChecker.md deleted file mode 100644 index 70814fd05..000000000 --- a/doc/Articles/Components/NetworkMatchChecker.md +++ /dev/null @@ -1,13 +0,0 @@ -# Network Match Checker - -The Network Match Checker component controls visibility of networked objects based on match id. - -![Network Scene Checker component](NetworkMatchChecker.png) - -Any object with this component on it will only be visible to other objects in the same match. - -This would be used to isolate players to their respective matches within a single game server instance. - -When you create a match, generate and store, in a List for example, a new match id with `System.Guid.NewGuid();` and assign the same match id to the Network Match Checker via `GetComponent().matchId`. - -Mirror's built-in Observers system will isolate SyncVar's and ClientRpc's on networked objects to only send updates to clients with the same match id. diff --git a/doc/Articles/Components/NetworkMatchChecker.png b/doc/Articles/Components/NetworkMatchChecker.png deleted file mode 100644 index c2d67ef08..000000000 Binary files a/doc/Articles/Components/NetworkMatchChecker.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkOwnerChecker.md b/doc/Articles/Components/NetworkOwnerChecker.md deleted file mode 100644 index 8eb21eda2..000000000 --- a/doc/Articles/Components/NetworkOwnerChecker.md +++ /dev/null @@ -1,8 +0,0 @@ -# Network Owner Checker - -The Network Owner Checker component controls visibility of networked objects based on owner client. - -Any object with this component on it will only be visible to the client that has authority ownership of it. - -This can be used when you want to spawn a network object with client authority and only have it appear for the owner, e.g. an interactive UI or NPC. -Since clients can call commands on objects they have authority over, such objects can have Network Behaviors with commands in them that can be called directly by the client. diff --git a/doc/Articles/Components/NetworkPingDisplay.md b/doc/Articles/Components/NetworkPingDisplay.md deleted file mode 100644 index 4a3e0eca3..000000000 --- a/doc/Articles/Components/NetworkPingDisplay.md +++ /dev/null @@ -1,9 +0,0 @@ -# Network Ping Display - -Network Ping Display shows the Ping time for clients using OnGUI. - -The Ping time is the moving average of the (RTT) Round-trip delay time. RTT is calculated by the PingMessage/PongMessage between the client and server. - -![Inspector](NetworkPingDisplay.png) - -See [Clock Synchronization](../Guides/ClockSync.md) for more info. diff --git a/doc/Articles/Components/NetworkPingDisplay.png b/doc/Articles/Components/NetworkPingDisplay.png deleted file mode 100644 index a1acc8bc4..000000000 Binary files a/doc/Articles/Components/NetworkPingDisplay.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkProximityCheck.png b/doc/Articles/Components/NetworkProximityCheck.png deleted file mode 100644 index 586e66b9a..000000000 Binary files a/doc/Articles/Components/NetworkProximityCheck.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkProximityChecker.md b/doc/Articles/Components/NetworkProximityChecker.md deleted file mode 100644 index 3dc484038..000000000 --- a/doc/Articles/Components/NetworkProximityChecker.md +++ /dev/null @@ -1,21 +0,0 @@ -# Network Proximity Checker - -The Network Proximity Checker component controls the visibility of game objects for network clients, based on proximity to players. - -![Network Proximity Checker component](NetworkProximityCheck.png) -- **Vis Range** - Define the range that the game object should be visible to observers. -- **Vis Update Interval** - Define how often (in seconds) the game object should check for observers entering its visible range. -- **Check Method** - Define which type of physics (2D or 3D) to use for proximity checking. -- **Force Hidden** - Tick this checkbox to hide this object from all players. - -With the Network Proximity Checker, a game running on a client doesn’t have information about game objects that are not visible. This has two main benefits: it reduces the amount of data sent across the network, and it makes your game more secure against hacking. - -This component relies on physics to calculate visibility, so observer game objects must also have a collider component on it. - -A game object with a Network Proximity Checker component must also have a Network Identity component. When you create a Network Proximity Checker component on a game object, Mirror also creates a Network Identity component on that game object if it does not already have one. - -Scene objects with a Network Proximity Checker component are disabled when they're out of range, and spawned objects are destroyed when they're out of range. diff --git a/doc/Articles/Components/NetworkRigidbody.md b/doc/Articles/Components/NetworkRigidbody.md deleted file mode 100644 index 7a67d4d63..000000000 --- a/doc/Articles/Components/NetworkRigidbody.md +++ /dev/null @@ -1,21 +0,0 @@ -# Network Rigidbody - -> The Network Rigidbody classed as "Experimental" for now so please share any problems or bugs you find with it and use at your own risk if production builds. - -The Network Rigidbody component synchronizes velocity and other properties of a rigidbody across the network. This component is useful when you have a non-kinematic rigidbody that have constant forces applied to them, like gravity, but also want to apply forces or change velocity to that rigidbody or server or client with authority. For example, objects that move and jump using rigidbody using gravity. - -A game object with a Network Rigidbody component must also have a Network Identity component. When you add a Network Rigidbody component to a game object, Mirror also adds a Network Identity component on that game object if it does not already have one. - -Network Rigidbody works best when there is also a NetworkTransform for the object to keep position as well as velocity in sync. - -![Network Rigidbody inspector](NetworkRigidbody.png) - -By default, Network Rigidbody is server-authoritative unless you check the box for **Client Authority**. Client Authority applies to player objects as well as non-player objects that have been specifically assigned to a client, but only for this component. With this enabled, value changes are send from the client to the server. - -The **Sensitivity** options allow you to set a minimum thresholds before values are send over network. This helps minimize network traffic for very small changes. - -For some object you may not want them to rotate but don't need to sync the Angular Velocity. The **Clear Angular Velocity** will set the Angular Velocity to zero each frame causing the minimizing when objects rotation. If **Sync Angular Velocity** is enabled then clear is ignored. The same can apply to **Clear Velocity**. - -Normally, changes are sent to all observers of the object this component is on. Setting **Sync Mode** to Owner Only makes the changes private between the server and the client owner of the object. - -You can use the **Sync Interval** to specify how often it syncs (in seconds). This applies both to Client Authority and Server Authority. diff --git a/doc/Articles/Components/NetworkRigidbody.png b/doc/Articles/Components/NetworkRigidbody.png deleted file mode 100644 index 241e9b1b1..000000000 Binary files a/doc/Articles/Components/NetworkRigidbody.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkRoomManager.md b/doc/Articles/Components/NetworkRoomManager.md deleted file mode 100644 index 69849aebb..000000000 --- a/doc/Articles/Components/NetworkRoomManager.md +++ /dev/null @@ -1,103 +0,0 @@ -# Network Room Manager - -\*\*Please see the Room example in the Examples folder in your Mirror folder - -The Network Room Manager is a specialized type of [Network Manager](NetworkManager.md) that provides a multiplayer room before entering the main play scene of the game. It allows you to set up a network with: -- A maximum player limit -- Automatic start when all players are ready -- Option to prevent players from joining a game in progress -- Customizable ways for players to choose options while in room   - -There are two types of player objects with the Network Room Manager: - -**Room Player Prefab** -- One for each player -- Created when client connects, or player is added -- Persists until client disconnects -- Holds ready flag and configuration data -- Handles commands in the room -- Must use the [Network Room Player](NetworkRoomPlayer.md) component - -**Player Prefab** -- One for each player -- Created when game scene is started -- Destroyed when leaving game scene -- Handles commands in the game   - -![Network Room Manager](NetworkRoomManager.png) - -## Properties -- **Show Room GUI** - Show the default OnGUI controls for the room. -- **Min Players** - Minimum number of players needed to start a game. -- **Room Player Prefab** - The prefab to create for players when they enter the room (requires Network Room Player component). -- **Room Scene** - The scene to use for the room. -- **Gameplay Scene** - The scene to use for main game play. -- **pendingPlayers** - List\ that holds players that are ready to start playing. -- **roomSlots** - List\ that manages the slots for connected clients in the room. -- **allPlayersReady** - Bool indicating if all players are ready to start playing. This value changes as players invoke `CmdChangeReadyState` indicating true or false, and will be set false when a new client connects. - -## Methods - -### Server Virtual Methods - -```cs -public virtual void OnRoomStartHost() {} - -public virtual void OnRoomStopHost() {} - -public virtual void OnRoomStartServer() {} - -public virtual void OnRoomServerConnect(NetworkConnection conn) {} - -public virtual void OnRoomServerDisconnect(NetworkConnection conn) {} - -public virtual void OnRoomServerSceneChanged(string sceneName) {} - -public virtual GameObject OnRoomServerCreateRoomPlayer(NetworkConnection conn) -{ - return null; -} - -public virtual GameObject OnRoomServerCreateGamePlayer(NetworkConnection conn) -{ - return null; -} - -public virtual bool OnRoomServerSceneLoadedForPlayer(GameObject roomPlayer, GameObject gamePlayer) -{ - return true; -} - -public virtual void OnRoomServerPlayersReady() -{ - ServerChangeScene(GameplayScene); -} -``` - -### Client Virtual Methods - -```cs -public virtual void OnRoomClientEnter() {} - -public virtual void OnRoomClientExit() {} - -public virtual void OnRoomClientConnect(NetworkConnection conn) {} - -public virtual void OnRoomClientDisconnect(NetworkConnection conn) {} - -public virtual void OnRoomStartClient() {} - -public virtual void OnRoomStopClient() {} - -public virtual void OnRoomClientSceneChanged(NetworkConnection conn) {} - -public virtual void OnRoomClientAddPlayerFailed() {} -``` diff --git a/doc/Articles/Components/NetworkRoomManager.png b/doc/Articles/Components/NetworkRoomManager.png deleted file mode 100644 index 2eba94e11..000000000 Binary files a/doc/Articles/Components/NetworkRoomManager.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkRoomPlayer.md b/doc/Articles/Components/NetworkRoomPlayer.md deleted file mode 100644 index fda3f6fb6..000000000 --- a/doc/Articles/Components/NetworkRoomPlayer.md +++ /dev/null @@ -1,27 +0,0 @@ -# Network Room Player - -The Network Room Player stores per-player state for the [Network Room Manager](NetworkRoomManager.md) while in the room. When using this component, you need to write a script which allows players to indicate they are ready to begin playing, which sets the ReadyToBegin property. - -A game object with a Network Room Player component must also have a Network Identity component. When you create a Network Room Player component on a game object, Unity also creates a Network Identity component on that game object if it does not already have one. - -![Network Room Player](NetworkRoomPlayer.png) -- **Show Room GUI** - Enable this to show the developer GUI for players in the room. This UI is only intended to be used for ease of development. This is enabled by default. -- **Ready To Begin** - Diagnostic indicator that a player is Ready. -- **Index** - Diagnostic index of the player, e.g. Player 1, Player 2, etc. -- **Network Sync Interval** - The rate at which information is sent from the Network Room Player to the server. - -## Methods - -### Client Virtual Methods - -```cs -public virtual void OnClientEnterRoom() {} - -public virtual void OnClientExitRoom() {} - -public virtual void OnClientReady(bool readyState) {} -``` diff --git a/doc/Articles/Components/NetworkRoomPlayer.png b/doc/Articles/Components/NetworkRoomPlayer.png deleted file mode 100644 index 74f709c2b..000000000 Binary files a/doc/Articles/Components/NetworkRoomPlayer.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkSceneChecker.md b/doc/Articles/Components/NetworkSceneChecker.md deleted file mode 100644 index bce57d5c8..000000000 --- a/doc/Articles/Components/NetworkSceneChecker.md +++ /dev/null @@ -1,55 +0,0 @@ -# Network Scene Checker - -The Network Scene Checker component controls the visibility of game objects for network clients, based on which scene they're in. - -![Network Scene Checker component](NetworkSceneChecker.png) - -- **Force Hidden** - Tick this checkbox to hide this object from all players. - -With the Network Scene Checker, a game running on a client doesn’t have information about game objects that are not visible. This has two main benefits: it reduces the amount of data sent across the network, and it makes your game more secure against hacking. - -This component would typically be used when the server has several subscenes loaded and needs to isolate networked objects to the subscene they're in. - -A game object with a Network Scene Checker component must also have a Network Identity component. When you create a Network Scene Checker component on a game object, Mirror also creates a Network Identity component on that game object if it does not already have one. - -Scene objects with a Network Scene Checker component are disabled when they're not in the same scene, and spawned objects are destroyed when they're not in the same scene. - -## Use with Additive Scenes - -In Mirror, the Server and connected Clients are always on the same main scene, however the server and clients can have various combinations of smaller subscenes loaded additively. The server may load all subscenes at start, or it may dynamically load and unload subscenes where players or other activity is going on as needed. - -All player objects are always first spawned in the main scene, which may or may not have visual content, networked objects, etc. With this component attached to all networked objects, whenever the player object is moved to a subscene (from the main or from another subscene), the observers lists for objects in both the new scene and the prior scene are updated accordingly. - -Loading the subscene(s) on the server is through the normal process with `SceneManager`: - -```cs -SceneManager.LoadSceneAsync(subScene, LoadSceneMode.Additive); -``` - -Next, you will send a `SceneMessage` to the client telling it to load a subscene additively: - -```cs -SceneMessage msg = new SceneMessage -{ - sceneName = subScene, - sceneOperation = SceneOperation.LoadAdditive -}; - -connectionToClient.Send(msg); -``` - -Then, on the server only, you just move the player object to the subscene: - -```cs -// Position the player object in world space first -// This assumes it has a NetworkTransform component that will update clients -player.transform.position = new Vector3(100, 1, 100); - -// Then move the player object to the subscene -SceneManager.MoveGameObjectToScene(player, subScene); -``` - -Optionally you can send another `SceneMessage` to the client with `SceneOperation.UnloadAdditive` to remove any previous additive scene the client no longer needs. This would apply to a game that has levels after a level change. A short delay may be necessary before removal to allow the client to get fully synced. - -Depending on the complexity of your game, you may find it helpful when switching a player between subscenes to move the player object to the main scene first, yield 100 ms, re-position it, and finally move it to the new subscene. diff --git a/doc/Articles/Components/NetworkSceneChecker.png b/doc/Articles/Components/NetworkSceneChecker.png deleted file mode 100644 index b1b7addfe..000000000 Binary files a/doc/Articles/Components/NetworkSceneChecker.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkStartPosition.PNG b/doc/Articles/Components/NetworkStartPosition.PNG deleted file mode 100644 index f71deb8d8..000000000 Binary files a/doc/Articles/Components/NetworkStartPosition.PNG and /dev/null differ diff --git a/doc/Articles/Components/NetworkStartPosition.md b/doc/Articles/Components/NetworkStartPosition.md deleted file mode 100644 index da6606862..000000000 --- a/doc/Articles/Components/NetworkStartPosition.md +++ /dev/null @@ -1,11 +0,0 @@ -# Network Start Position - -To control where players are spawned, you can use the Network Start Position component. - -To use these, attach a Network Start Position component to a game object in the scene, and position the game object where you would like one of the players to start. You can add as many start positions to your Scene as you like. The Network Manager detects all start positions in your Scene, and when it spawns each player instance, it uses the position and orientation of one of them. - -The Network Manager will spawn players at (0, 0, 0) by default. Adding this component to a game object will automatically register/unregister its game object's transform to the Network Manager as an available spawning position. - -Depending on the Network Manager Player Spawn Method setting the spawning is either Random (possible that the same spawn position will be used by two or more players) or Round Robin (use every available position, until there are more clients than spawn points). - -![Inspector](NetworkStartPosition.PNG) diff --git a/doc/Articles/Components/NetworkTransform.md b/doc/Articles/Components/NetworkTransform.md deleted file mode 100644 index 601ad2745..000000000 --- a/doc/Articles/Components/NetworkTransform.md +++ /dev/null @@ -1,15 +0,0 @@ -# Network Transform - -The Network Transform component synchronizes the position, rotation, and scale of networked game objects across the network. - -A game object with a Network Transform component must also have a Network Identity component. When you add a Network Transform component to a game object, Mirror also adds a Network Identity component on that game object if it does not already have one. - -![The Network Transform component](NetworkTransform.png) - -By default, Network Transform is server-authoritative unless you check the box for **Client Authority**. Client Authority applies to player objects as well as non-player objects that have been specifically assigned to a client, but only for this component. With this enabled, position changes are send from the client to the server. - -Under **Sensitivity**, you can set the minimum thresholds of change to the transform values in order for network messages to be generated. This helps minimize network "noise" for minor twitch and jitter. - -Normally, changes are sent to all observers of the object this component is on. Setting **Sync Mode** to Owner Only makes the changes private between the server and the client owner of the object. - -You can use the **Sync Interval** to specify how often it syncs (in seconds). diff --git a/doc/Articles/Components/NetworkTransform.png b/doc/Articles/Components/NetworkTransform.png deleted file mode 100644 index 02cebef60..000000000 Binary files a/doc/Articles/Components/NetworkTransform.png and /dev/null differ diff --git a/doc/Articles/Components/NetworkTransformChild.md b/doc/Articles/Components/NetworkTransformChild.md deleted file mode 100644 index 5eb9a0079..000000000 --- a/doc/Articles/Components/NetworkTransformChild.md +++ /dev/null @@ -1,11 +0,0 @@ -# Network Transform Child - -The Network Transform Child component synchronizes the position and rotation of the child game object of a game object with a Network Transform component. You should use this component in situations where you need to synchronize an independently-moving child object of a Networked game object. - -To use the Network Transform Child component, attach it to the same parent game object as the Network Transform, and use the Target field to define which child game object to apply the component settings to. You can have multiple Network Transform Child components on one parent game object . - -![The Network Transform Child component](NetworkTransform.png) - -You can modify **Compress Rotation** to save some bandwidth when synchronizing the rotation. You can use the **Network Sync Interval** to specify how often it syncs (in seconds). - -This component takes authority into account, so local player game objects (which have local authority) synchronize their position from the client to server, then out to other clients. Other game objects (with server authority) synchronize their position from the server to clients. diff --git a/doc/Articles/Components/index.md b/doc/Articles/Components/index.md deleted file mode 100644 index 5307e99ab..000000000 --- a/doc/Articles/Components/index.md +++ /dev/null @@ -1,42 +0,0 @@ -# Components Overview - -These core components are included in Mirror: - -- [Network Animator](NetworkAnimator.md) - The Network Animator component allows you to synchronize animation states for networked objects. It synchronizes state and parameters from an Animator Controller. -- [Network Authenticator](Authenticators/index.md) - Network Authenticators facilitate integration of user accounts and credentials into your application. -- [Network Discovery](NetworkDiscovery.md) - Network Discovery uses a UDP broadcast on the LAN enabling clients to find the running server and connect to it. -- [Network Identity](NetworkIdentity.md) - The Network Identity component is at the heart of the Mirror networking high-level API. It controls a game object’s unique identity on the network, and it uses that identity to make the networking system aware of the game object. It offers two different options for configuration and they are mutually exclusive, which means either one of the options or none can be checked. -- [Network Headless Logger](NetworkHeadlessLogger.md) - Network Headless Logger adds color to log when running in headless mode -- [Network Lerp Rigidbody](NetworkLerpRigidbody.md) - The Network Lerp Rigidbody synchronizes position and velocity of a rigidbody across the network. -- [Network Manager](NetworkManager.md) - The Network Manager is a component for managing the networking aspects of a multiplayer game. -- [Network Manager HUD](NetworkManagerHUD.md) - The Network Manager HUD is a quick-start tool to help you start building your multiplayer game straight away, without first having to build a user interface for game creation/connection/joining. It allows you to jump straight into your gameplay programming, and means you can build your own version of these controls later in your development schedule. -- [Network Match Checker](NetworkMatchChecker.md) - The Network Match Checker component controls visibility of networked objects based on match id. -- [Network Owner Checker](NetworkOwnerChecker.md) - The Network Owner Checker component controls visibility of networked objects based on owner client. -- [Network Ping Display](NetworkPingDisplay.md) - Network Ping Display shows the Ping time for clients using OnGUI -- [Network Proximity Checker](NetworkProximityChecker.md) - The Network Proximity Checker component controls the visibility of game objects for network clients, based on proximity to players. -- [Network Rigidbody](NetworkRigidbody.md) - The Network Rigidbody synchronizes velocity and other properties of a rigidbody across the network. -- [Network Room Manager](NetworkRoomManager.md) - The Network Room Manager is an extension component of Network Manager that provides a basic functional room. -- [Network Room Player](NetworkRoomPlayer.md) - The Network Room Player is a component that's required on Player prefabs used in the Room Scene with the Network Room Manager above. -- [Network Scene Checker](NetworkSceneChecker.md) - The Network Scene Checker component controls visibility of networked objects between scenes. -- [Network Start Position](NetworkStartPosition.md) - Network Start Position is used by the Network Manager when creating player objects. The position and rotation of the Network Start Position are used to place the newly created player object. -- [Network Transform](NetworkTransform.md) - The Network Transform component synchronizes the movement and rotation of game objects across the network. Note that the network Transform component only synchronizes spawned networked game objects. -- [Network Transform Child](NetworkTransformChild.md) - The Network Transform Child component synchronizes the position and rotation of the child game object of a game object with a Network Transform component. diff --git a/doc/Articles/Components/toc.yml b/doc/Articles/Components/toc.yml deleted file mode 100644 index ec9bbcfe6..000000000 --- a/doc/Articles/Components/toc.yml +++ /dev/null @@ -1,41 +0,0 @@ -- name: Overview - href: index.md -- name: Network Animator - href: NetworkAnimator.md -- name: Network Authenticators - href: Authenticators/toc.yml - topicHref: Authenticators/index.md -- name: Network Discovery - href: NetworkDiscovery.md -- name: Network Identity - href: NetworkIdentity.md -- name: Network Headless Logger - href: NetworkHeadlessLogger.md -- name: Network Lerp Rigidbody - href: NetworkLerpRigidbody.md -- name: Network Manager - href: NetworkManager.md -- name: Network Manager HUD - href: NetworkManagerHUD.md -- name: Network Match Checker - href: NetworkMatchChecker.md -- name: Network Owner Checker - href: NetworkOwnerChecker.md -- name: Network Ping Display - href: NetworkPingDisplay.md -- name: Network Proximity Checker - href: NetworkProximityChecker.md -- name: Network Rigidbody - href: NetworkRigidbody.md -- name: Network Room Manager - href: NetworkRoomManager.md -- name: Network Room Player - href: NetworkRoomPlayer.md -- name: Network Scene Checker - href: NetworkSceneChecker.md -- name: Network StartPosition - href: NetworkStartPosition.md -- name: Network Transform - href: NetworkTransform.md -- name: Network Transform Child - href: NetworkTransformChild.md diff --git a/doc/Articles/Examples/AdditiveScenes/index.md b/doc/Articles/Examples/AdditiveScenes/index.md deleted file mode 100644 index 6e17a2313..000000000 --- a/doc/Articles/Examples/AdditiveScenes/index.md +++ /dev/null @@ -1,24 +0,0 @@ -# Additive Scenes Example - -IMPORTANT: Make sure you have a layer in project settings called Player for this example to work well. - -In Build Settings, remove all scenes and add all of the scenes from the Scenes folder in the following order: -- MainScene -- SubScene - -Open the MainScene in the Editor and make sure the Sub Scenes list in the Network Manager component on the Network scene object contains the SubScene scene. This is already setup by default, but if the MainScene was opened and saved before putting the scenes in the Build Settings list, the Sub Scenes list may be cleared accidentally. - -File -> Build and Run - -Start up to 3 built instances: These will all be client players. - -Press Play in the Editor and click Host (Server + Client) in the HUD -- This will be the host and the 1st player of up to 4. You can also use Server Only if you prefer. - -Click Client in the built instances. -- WASDQE keys to move & turn your player capsule. -- There are objects in the corners of the scene hidden by Proximity Checkers. -- The big area in the middle is where the subscene will be loaded when you get near the shelter. -- There are also networked objects inside the subscene, also with Proximity Checkers. -- Since subscenes are only loaded for individual clients, other clients that are outside the middle Zone won't see what those in the subscene can see. -- If you play a built instance as Host or Server and play as client in the editor, you'll see the subscene content load and unload in the hierarchy as you move in and out of the middle Zone. diff --git a/doc/Articles/Examples/Basic/Basic.PNG b/doc/Articles/Examples/Basic/Basic.PNG deleted file mode 100644 index 1db3e8cd3..000000000 Binary files a/doc/Articles/Examples/Basic/Basic.PNG and /dev/null differ diff --git a/doc/Articles/Examples/Basic/BasicPlayer.PNG b/doc/Articles/Examples/Basic/BasicPlayer.PNG deleted file mode 100644 index 691bc7387..000000000 Binary files a/doc/Articles/Examples/Basic/BasicPlayer.PNG and /dev/null differ diff --git a/doc/Articles/Examples/Basic/index.md b/doc/Articles/Examples/Basic/index.md deleted file mode 100644 index dcb7b5a1e..000000000 --- a/doc/Articles/Examples/Basic/index.md +++ /dev/null @@ -1,7 +0,0 @@ -# Basic - -General description of Basic example. - -![Basic Example](Basic.PNG) - -![Basic Player](BasicPlayer.PNG) diff --git a/doc/Articles/Examples/MultipleAdditiveScenes/MultiSceneNetworkManager.PNG b/doc/Articles/Examples/MultipleAdditiveScenes/MultiSceneNetworkManager.PNG deleted file mode 100644 index ed03fde94..000000000 Binary files a/doc/Articles/Examples/MultipleAdditiveScenes/MultiSceneNetworkManager.PNG and /dev/null differ diff --git a/doc/Articles/Examples/MultipleAdditiveScenes/index.md b/doc/Articles/Examples/MultipleAdditiveScenes/index.md deleted file mode 100644 index 2c0bdf855..000000000 --- a/doc/Articles/Examples/MultipleAdditiveScenes/index.md +++ /dev/null @@ -1,36 +0,0 @@ -# Multiple Additive Scenes Example - -In Build Settings, remove all scenes and add both of the scenes from the Scenes folder in the following order: - -- Main -- Game - -Open the Main scene in the Editor and make sure the Game Scene field in the MultiScene Network Manager on the Network scene object contains the Game scene. This is already setup by default, but if the Main scene was opened and saved before putting the scenes in the Build Settings list, the Game Scene field may be cleared accidentally. - -## MultiScene Network Manager - -The MultiScene Network Manager is derived from the base Network Manager and is responsible for additively loading the subscene instances and placing the players in their respective subscene instances and initializing player SyncVars. It has a Game Scene field where the Game subscene is assigned, and an Instances field to set how many instances are loaded on the server. - -In this example, the subscene instances are additively loaded on the server with `localPhysicsMode = LocalPhysicsMode.Physics3D`. Physics subscenes do not auto-simulate, so each scene has a game object with a generic `PhysicsSimulator` script on it. This script does nothing on the client, only on the server. - -Clients only ever have one instance of the subscene additively loaded (without `localPhysicsMode`), while server has them all. All networked objects have a `NetworkSceneChecker` component which is what isolates them to their specific subscene. - -## Playing in the Instances - -File -\> Build and Run - -Start at least 3 built instances: These will all be client players. - -Press Play in the Editor and click Host (Server + Client) in the HUD - This will be the host and the 1st player. You can also use Server Only if you prefer. - -Click Client in the built instances. - -- WASDQE keys to move & turn your player capsule, Space to jump. - -- Colliding with the small colored spheres scores points base on their color. - -- Colliding with the larger tumblers sends them rolling around...they're server-side non-kinematic rigidbodies. - -- Only scores for the players in the same subscene are shown at the top of the game window. - -![MultiScene Network Manager](MultiSceneNetworkManager.PNG) diff --git a/doc/Articles/Examples/Pong/Pong1.jpg b/doc/Articles/Examples/Pong/Pong1.jpg deleted file mode 100644 index 8527e8774..000000000 Binary files a/doc/Articles/Examples/Pong/Pong1.jpg and /dev/null differ diff --git a/doc/Articles/Examples/Pong/Pong2.jpg b/doc/Articles/Examples/Pong/Pong2.jpg deleted file mode 100644 index 05488bb30..000000000 Binary files a/doc/Articles/Examples/Pong/Pong2.jpg and /dev/null differ diff --git a/doc/Articles/Examples/Pong/Pong3.jpg b/doc/Articles/Examples/Pong/Pong3.jpg deleted file mode 100644 index 0b1d04a83..000000000 Binary files a/doc/Articles/Examples/Pong/Pong3.jpg and /dev/null differ diff --git a/doc/Articles/Examples/Pong/Pong4.jpg b/doc/Articles/Examples/Pong/Pong4.jpg deleted file mode 100644 index 15ef9cb6d..000000000 Binary files a/doc/Articles/Examples/Pong/Pong4.jpg and /dev/null differ diff --git a/doc/Articles/Examples/Pong/index.md b/doc/Articles/Examples/Pong/index.md deleted file mode 100644 index 533516632..000000000 --- a/doc/Articles/Examples/Pong/index.md +++ /dev/null @@ -1,59 +0,0 @@ -# Pong - -A simple example for "How to built a multiplayer game with Mirror" is Pong, -which is included in the AssetStore package of Mirror. It illustrates the usage -of NetworkManager, NetworkManagerHUD, NetworkBehaviour, NetworkIdentity, -NetworkTransform, NetworkStartPosition and NetworkingAttributes. - -![Pong](Pong1.jpg) - -## Setting the number of players - -First of all, let's have a look at the NetworkManager object in the main scene. -When adding the NetworkManager component to a gameobject, a few default settings -are already set (**Don't destroy on Load**, **Run in Background**, ...) For -playing Pong the maximum number of players is 2, so the setting **Network -Info/Max connections** will also be 2. As there are no other scenes (room, -online or offline scene) in this sample the properties for **Offline Scene** and -**Online Scene** will stay empty. - -## Creating the player - -Furthermore every player needs a racket to play with. Each player who joins the -game will have his own controllable object, which represents him within the -game. This gameobject is called *PlayerObject*. For spawning the *PlayerObject* -a prefab has to be created, containing at least a NetworkIdentity component with -**Local Player Authority** checked. The **Local Player Authority** allows the -player to control and modify the gameobjects properties (e.g. for movement). The -NetworkManager needs a reference to this prefab, which is located in **Spawn -Info/Player Prefab**. To have the player movement synchronized over the network, -the player prefab also contains a NetworkTransform. - -![NetworkManagerSettings](Pong2.jpg) - -## Player start position - -The main scene contains 2 gameobjects with only a NetworkStartPosition component -(gameobjects RacketSpawnLeft, RacketSpawnRight in the scene). These transforms -will be automatically registered by the NetworkManager as spawning positions. - -![NetworkStartPositions](Pong3.jpg) - -## Setting up the network - -A very convenient component for establish/testing connections is the -NetworkManagerHUD. It provides basic functionality for start a game as -Client, Server, or Host (Client and Server at the same time). It -requires the NetworkManager component. - -![NetworkManagerHUD](Pong4.jpg) - -## The ball of Pong - -The ball is the main focus of Pong, as this is the object needed to score -points. Its NetworkIdentity component has neither **Server Only** nor **Local -Player Authority** checked, as it's moved by the server physics engine and can -be influenced by the players. As with the *PlayerObject* the position is -synchronized via NetworkTransform. When having multiple scenes, the ball can be -spawned by the NetworkManager, but to keep this sample simple, it's placed -directly within the main scene. diff --git a/doc/Articles/Examples/Room/Room1.PNG b/doc/Articles/Examples/Room/Room1.PNG deleted file mode 100644 index fdb34ea18..000000000 Binary files a/doc/Articles/Examples/Room/Room1.PNG and /dev/null differ diff --git a/doc/Articles/Examples/Room/Room2.PNG b/doc/Articles/Examples/Room/Room2.PNG deleted file mode 100644 index 68c9f94cf..000000000 Binary files a/doc/Articles/Examples/Room/Room2.PNG and /dev/null differ diff --git a/doc/Articles/Examples/Room/RoomManager.PNG b/doc/Articles/Examples/Room/RoomManager.PNG deleted file mode 100644 index 2bfc0ec80..000000000 Binary files a/doc/Articles/Examples/Room/RoomManager.PNG and /dev/null differ diff --git a/doc/Articles/Examples/Room/RoomPlayer.PNG b/doc/Articles/Examples/Room/RoomPlayer.PNG deleted file mode 100644 index f54c30501..000000000 Binary files a/doc/Articles/Examples/Room/RoomPlayer.PNG and /dev/null differ diff --git a/doc/Articles/Examples/Room/index.md b/doc/Articles/Examples/Room/index.md deleted file mode 100644 index 568349cd5..000000000 --- a/doc/Articles/Examples/Room/index.md +++ /dev/null @@ -1,20 +0,0 @@ -# Room - -General description of Room example. - -![Host's Room View](Room1.PNG) - -  - -![Player's Room View](Room2.PNG) - -  - -![Network Room Manager](RoomManager.PNG) - -  - -![Network Room Player](RoomPlayer.PNG) - - -> Note: If using `NetworkRoomManagerExt` then the GamePlayer prefab should have a `PlayerScore` attached. If you dont want to add `PlayerScore` to your prefab then replace the `NetworkRoomManagerExt` script for `NetworkRoomManager` diff --git a/doc/Articles/Examples/Tanks/index.md b/doc/Articles/Examples/Tanks/index.md deleted file mode 100644 index 9564ca5d4..000000000 --- a/doc/Articles/Examples/Tanks/index.md +++ /dev/null @@ -1,3 +0,0 @@ -# Tanks - -General description of Tanks example. diff --git a/doc/Articles/Examples/index.md b/doc/Articles/Examples/index.md deleted file mode 100644 index 9c12bef2b..000000000 --- a/doc/Articles/Examples/index.md +++ /dev/null @@ -1,15 +0,0 @@ -# Samples Overview - -Mirror includes several small examples to help you learn how to use various features and how to set things up so they work together. -- [Basic](Basic/index.md) - Basic is what it sounds like...the most rudimentary baseline of a networked game. Features SyncVars updating random UI data for each player. -- [Tanks](Tanks/index.md) - This is a simple scene with animated tanks, networked rigidbody projectiles, and NavMesh movement -- [Pong](Pong/index.md) - A simple example for "How to build a multiplayer game with Mirror" is Pong. It illustrates the usage of `NetworkManager`, `NetworkManagerHUD`, NetworkBehaviour, NetworkIdentity, `NetworkTransform`, `NetworkStartPosition`and various Attributes. -- [Additive Scenes](AdditiveScenes/index.md) - The Additive Scenes example demonstrates a server additively loading a sub-scene into a main scene at startup, and having a server-only trigger that generates a message to any client whose player enters the trigger zone to also load the sub-scene, and subsequently unload it when they leave the trigger zone. Only players inside the trigger zone can see the objects in the sub-scene. Network Proximity Checker components are key to making this scenario work. -- [Multiple Concurrent Additive Scenes](MultipleAdditiveScenes/index.md) - The Multiple Concurrent Additive Scenes example demonstrates a server additively loading multiple instances of a sub-scene into a main scene at startup, with physics separation, and assigning players to the instances to play matches independently. [NetworkSceneChecker](../Components/NetworkSceneChecker.md) is the key component that makes this example work. -- [Room System](Room/index.md) - The Room System example demonstrates how to set up a "staging" scene where players assemble before starting a match. When all players are ready, the server sends them all a message to change scenes (along with the server itself) to the actual game play scene so they all come in at once. Includes fully playable game with a character controller where players collect server-spawned prizes for score. diff --git a/doc/Articles/Examples/toc.yml b/doc/Articles/Examples/toc.yml deleted file mode 100644 index 652816e3f..000000000 --- a/doc/Articles/Examples/toc.yml +++ /dev/null @@ -1,14 +0,0 @@ -- name: Overview - href: index.md -- name: Basic - href: Basic/index.md -- name: Tanks - href: Tanks/index.md -- name: Pong - href: Pong/index.md -- name: Additive Scenes - href: AdditiveScenes/index.md -- name: Multiple Additive Scenes - href: MultipleAdditiveScenes/index.md -- name: Room - href: Room/index.md diff --git a/doc/Articles/FAQ.md b/doc/Articles/FAQ.md deleted file mode 100644 index 782f16231..000000000 --- a/doc/Articles/FAQ.md +++ /dev/null @@ -1,153 +0,0 @@ -# FAQ - -Anything to add to this list? Please make a PR or ask in the discord. - -### How do I use this feature? - -
- How to Send/Sync custom data types? - - Mirror can automatically create Serialization functions for many custom data types when your scripts are compiled. - - For example, mirror will automatically create a functions for `MyCustomStruct` so that it can be sent without any extra work. - ```cs - [ClientRpc] - public void RpcDoSomething(MyCustomStruct data) - { - // do stuff here - } - - struct MyCustomStruct - { - int someNumber; - Vector3 somePosition; - } - ``` - - For More details - - [DataTypes](https://mirror-networking.com/docs/Guides/DataTypes.html) - - [Serialization](https://mirror-networking.com/docs/Guides/Serialization.html) -
- - -### How to Connect - -
- How to connect to games on same PC - - Make sure the networkAddress field on NetworkManager or the Hud is set up `localHost` -
- -
- How to connect to a different PC/Device on same network - - Set the networkAddress field to the LAN IP of the host `192.168.x.x` - - *In some cases you may need additional steps, check below* - - To check ip on Windows you can open powershell and use the `ipconfig` command, then under your current adapter (ethernet/wifi/etc) look for `IPv4 Address` - - ` IPv4 Address. . . . . . . . . . . : 192.168.x.x ` -
- -
- How to connect to a different PC/Device over the internet - - Set the networkAddress field to be the IP address of the host (google 'whats my IP') - - > This section does not cover relays/dedicated vps/headless features - - For this to work, you will need to do **some** of the following, most of these depend on your set up and router - - - **Port forward**: you'll have to login your Router - - Either forward your game port (default is 7777) for your PC's local IP. (192.168.1.20 for example) - - Or the quick (but less safe) add that local IP to DMZ. - - - **PC Firewalls**: - - You can turn it off for a quick test (And turn it back on later) - - manually allow the editor and any builds you create it in firewalls settings. - - - Try from a build rather than the Unity Editor - - - Some anti virus/phones may have additional blocking. - - You can turn it off for a quick test (And turn it back on later) - - - In rare cases ISPs or companies/schools block ports and connections, this is harder to adjust yourself. - - If you need more help it is best to google for guide for your setup and router. - - An alternative to the above is to use a dedicated server (vps) or use a relay. -
- - -### Host Migration - -
- Host migration alternatives and work-around. - -Host migration as of writing is not built into Mirror, and it is best to avoid Host Migration completely if you can. -Below are some tips as to why, and how you can add a host migration-like alternative. - - Dedicated hosts should rarely ever be closed (If you are doing games that need to stay open such as MMO's). - - Short arena maps, take players back to the games list/matchmaker, so they can just join another, nice and simple. - -The work around is to basically fake the host migration, store info of a backup host on players game, upon disconnection, reconnect everyone in the game to that new host, then restore positions and variable data back to how it was before the original host dissappeared. -- Test players connections when they join, find one with unblocked ports, and decent ping/latency. -- Send this players data (IP and Port) on all connected players games. -- Save various player info, either locally or on that backup host, such as player positions, health etc -- Upon disconnection from server, call a function to connect to the backup hoster StartClient( BackupIP - BackupPort ). -- As the scenes will most likely reset, along with players respawning, you now need to set player position back to your stored one that was saved either via checkpoints, or in the disconnect detection callback. -- Cover all this up with a UI, saying please wait (optional, should happen in the blink of an eye). - -Depending on what your game is like, it'll either be easy or difficult to add the work-around. -An example of these are: -- (easier) A game only needing player position data such as "Fall Guys". -- (difficult) Forge of Empires, a game where created objects are placed, soldiers, vehicles, various other crafts and upgrades, all with their own levels/stats. - -
- -### Master / List Servers and Simple Matchmaker - -
- A database of world-wide registered host data. - -All the hosts, dedicated or player hosts, get added into a list database, players get the list and can choose who to join. -Using a list server means players do not have to manually enter IP addresses and Ports, it is all done behind the scenes, and works for localhost, LAN, and WAN connection types. -You can show as much, or as little data as you like to the players, such as host name, type (deathmatch), player count (45 / 50), ping, enemy difficulty, map, region etc - -- Mirror Listserver: Mirror squad manage and host this for you, you pay monthly subscription, but do not have to worry about setting up or maintaining it. -- Node ListServer: Free, but you host the files yourself on an unblocked PC, like a VPS. Has a wide variety of customisable features, best option if you want self hosted dedicated games. -- Dark Reflective Mirror: This is a list server and a relay, it is free, but you host and manage the files yourself. -Relays offer an unblocked route of traffic, but at the cost of extra latency/increased ping. This relay will test for a direct connection first, then fallback to routed traffic if that fails. Both the list server and relayed traffic is optional, you can use one part, and not the other. -This is the best option for player hosted games, where router port blocks are common. - -Simple Matchmaker -- You can make matchmakers out of these list servers, simply hide the list to players, have them auto join a game with space. You could also filter out various requirements the player has set, for example, "USA" Region only, or "Lava Island" map. -
- -### How to get the player count? - -
- There are a few ways to do this, each with their own unique benefit. - -NetworkServer.connections.Count -- Socket connections, includes people without spawned prefabs, non authenticated, or that may have bugged out but during spawn, but have connected temporarily (Android users minimising game). Only host / server can check this. - -NetworkManager.singleton.numPlayers -- Number of active spawned player objects on the server (only the host / server can check this) -
- -### Changing Transports - -
- Changing transports is very easy and only requires a few steps - -- Go to the game object that has the `NetworkManager` component -- Add another transport script via the Add Component button -- Drag the transport script to the "Transport" field in the `NetworkManager` -- Remove the old transport script (optional) - -You have successfully changed transports. If you have connection issues with a transport that requires port forwarding, make sure to port forward the correct protocol (TCP / UDP). - -NOTE: Some transports are not included with Mirror and need to be downloaded from their respective GitHub pages. - -
diff --git a/doc/Articles/General/ChangeLog.md b/doc/Articles/General/ChangeLog.md deleted file mode 100644 index 9cf5f5e0c..000000000 --- a/doc/Articles/General/ChangeLog.md +++ /dev/null @@ -1,508 +0,0 @@ -# Change Log - -**Mirror is published to the [Asset Store](https://assetstore.unity.com/packages/tools/network/mirror-129321) at the start of every month, unless some critical issue causes a delay.** - -Mirror uses semantic versioning, and the versions shown here are those that were published to the Asset Store, and occasionally major version bumps happen mid-month between store submissions and are therefore not individually shown here. - -## Version 31.x.x -- In progress -- Added: NetworkIdentity now has `isServer` / `isClientOnly`. -- Added: Global Interest Management. This may eventually lead to replacement of Scene Checker, Match Checker, and Owner Checker components. -- Added: GUI Console ported from uMMORPG (F12 to show/hide). -- Added: Network Manager now takes itself out of DDOL in StopServer / StopClient when offline scene is defined to avoid singleton collision. -- Fixed: Telepathy 1.7 receive timeout disabled by default, increased MirrorTransport timeout to 30sec from 5sec to cover scene changes. -- Changed: **Breaking** LogFactory and logging asset feature removed. -- Changed: **Breaking** Command `ignoreAuthority` parameter renamed to `requiresAthority`, default true. -- Changed: **Breaking** ClientRpc `excludeOwner` parameter renamed to `includeOwner`, default true. - -## Version 30.5.3 -- 2021-Feb-15 -- Fixed: Fixed a bug in batching for messages larger than MTU. -- Fixed: Telepathy 1.6 fixes data races and improves stability. -- Fixed: Kcp 1.8 fixes emput message sending / receiving undefined behaviour and fixes IPv6 on Nintendo Switch. -- Changed: Network Manager default max connections is now 100. -- Changed: **Breaking** NetworkServer and NetworkClient no longer use Connect/Disconnect messages...events are raised instead. -- Changed: **Breaking** Removed OnServerError / OnClientError messages and handlers. -- Changed: **Breaking** Removed NetworkConnection.InvokeHandler as no longer needed. - -## Version 30.5.0 -- 2021-Feb-05 -- Added: [KCP Transport](../Transports/KCPTransport.md) updated to version 1.7. -- Added: Batching support for server messages - See Network Manager to enable. -- Added: [Network Owner Checker](../Components/NetworkOwnerChecker.md). -- Added: [Script Templates](ScriptTemplates.md) are back in the package -- See the new Mirror section in the Assets > Create menu. -- Added: Unreliable channel added to KCP Transport. -- Fixed: Performance improvements to KCP Transport. -- Fixed: Examples with UI now work with Unity 2018.4 again -- Fixed: NetworkServer.OnConnected allows for connectionIds < 0 now. -- Fixed: Corrected `NetworkRoomPlayer` `ReadyStateChanged` `oldReadyState` parameter name. -- Changed: Ping/Pong messages now use unreliable channel if available from transports. -- Changed: **Breaking** Read / Write Blittable has been removed. - -## Version 30.2.2 -- 2020-Dec-17 -- Added: Network Reader/Writer now does Read/WriteBlittable for better performance. -- Added: [KCP Transport](../Transports/KCPTransport.md) updated to version 1.4. -- Added: Network Authenticator now has OnStopServer and OnStopClient overrides. -- Added: Network Transform now applies compression to rotations. -- Added: SyncVars now support using types that inherit from NetworkBehaviour. -- Added: SimpleWebTransport now has option for TLS outside the transport. -- Added: MultipleMatches example featuring Network Match Checker with Lobby and Match functionality. -- Fixed: Better presentation of Network Ping Display.. -- Fixed: Middleware Transport now listens for inner events correctly.. -- Fixed: Calling StartServer / StartClient more than once is now prevented.. -- Fixed: NRE when no host player in PlayerScore in MultipleAdditiveScenes example. -- Fixed: player collisions in MultipleAdditiveScenes example. -- Fixed: Weaver now properly generates readers and writers for structs in other assemblies, e.g. `Mathematics`. -- Fixed: NetworkServer.maxConnections is now public. -- Fixed: Skip reset of object that's being destroyed. -- Fixed: ReadyStatusChanged in NetworkRoomManager is now public. -- Fixed: NetworkTransform now correctly uses ArraySegment in Commands. -- Fixed: Added OnStopServer to NetworkSceneChecker and NetworkMatchChecker. -- Fixed: Weaver method lookup conflict with Unity 2020.2. -- Fixed: Memory allocation vulnerability in NetworkReader. -- Changed: Playmode now blocked for invalid scene id's, with error messages. -- Changed: Experimental Network Transform now uses `Channels.DefaultUnreliable` and applies compression to rotations. -- Changed: Server Only scene objects in examples replaced with normal objects instantiated on server or just eliminated. -- Changed: **Breaking** Force NetworkMessage to use structs in all cases - classes no longer supported. -- Changed: **Breaking** Removed ReadPacked / WritePacked functions - Use Read and Write variants instead. -- Changed: **Breaking** LLAPI has been removed. - -## Version 26.2.2 -- 2020-Nov-20 -- Added: [KCP Transport](../Transports/KCPTransport.md). -- Added: [Libuv2k Transport](../Transports/Libuv2k.md). -- Added: Quaternion and float compression. -- Added: Option to configure handshakeMaxSize in SimpleWebTransport. -- Added: ServerTeleport to Experimental NetworkTransform. -- Added: Accept and Reject methods to Authenticator base class for ease of use. -- Fixed: Weaver failure on Authenticators and assemblies with only messages and no behaviors. -- Fixed: Examples no longer rely on sequential connectionId. -- Fixed: Eliminated errors when first importing due to preprocessor defines in transports. -- Fixed: Scene ID logging is now consistently in hex format. -- Fixed: sceneId when using BuildPipeline.BuildPlayer with incorrect case in path. -- Fixed: Trigger not applied correctly for host in NetworkAnimator. -- Fixed: Ensure ReadHelper.Read reads exactly number of bytes in SimpleWebTransport. -- Changed: Minimum Unity version is now 2018.4.28 LTS. -- Changed: Script Templates are now available as a separate package [here](ScriptTemplates.md). -- Changed: Telepathy Transport is now obsolete - Use [KCP Transport](../Transports/KCPTransport.md) instead. -- Changed: **Breaking** NetworkIdentity.clientAuthorityCallback is an event now. -- Changed: **Breaking** Removed older obsolete methods and tests. -- Changed: **Breaking** Transports no longer support sending to a List of connectionIds. - -## Version 23.0.3 -- 2020-Oct-24 -- Added: Support null when serializing classes. -- Added: Support recursive data types. -- Added: Support jagged arrays. -- Added: New generic Read and Write methods for typed used by mirror and user callbacks. -- Added: NetworkAnimator now syncs animator.speed. -- Added: NetworkTransform Server Teleport function. -- Added: New websockets transport: [SimpleWebTransport](https://github.com/MirrorNetworking/SimpleWebTransport). -- Fixed: ClientScene.localplayer is now set to null when it is destroyed. -- Fixed: Fixing IndexChanged hook not being called for NetworkRoomPlayer. -- Fixed: Fixing NullReferenceException when loading scene. -- Fixed: Fixing NetworkConnectionToClient for IL2CPP. -- Fixed: NullReferenceException in tanks example when running in headless server only. -- Changed: **Breaking** Use SyncLists/SyncSet/SyncDictionary directly, e.g. `SyncList`, see [Pull Request 2307](https://github.com/vis2k/Mirror/pull/2307). -- Changed: **Breaking** Renamed `IMessageBase` to `NetworkMessage`, see [Pull Request 2317](https://github.com/vis2k/Mirror/pull/2317). -- Changed: OnSerialize now includes the component index as byte before serializing each component. Better CPU performance at the cost of bandwidth. -- Changed: Can now have 256 NetworkBehaviours per NetworkIdentity. -- Removed: **Breaking** SyncEvents, see [Pull Request 2178](https://github.com/vis2k/Mirror/pull/2178). -- Removed: **Breaking** Removing manual invoke for Cmd and RPC, see [Pull Request 2223](https://github.com/vis2k/Mirror/pull/2223). -- Removed: **Breaking** Removed Serialize/Deserialize in messages, see [Pull Request 2317](https://github.com/vis2k/Mirror/pull/2317). -- Removed: **Breaking** Removing auto initialize for SyncLists/SyncSet/SyncDictionary, see [Pull Request 2330](https://github.com/vis2k/Mirror/pull/2330). -- Removed: **Breaking** Replacing [Ninja.WebSockets](https://github.com/MirrorNetworking/NinjaWebSocketsTransport) with [SimpleWebTransport](https://github.com/MirrorNetworking/SimpleWebTransport). - -## Version 17.3.0 -- 2020-Sep-04 -- Added: NetworkAnimator now syncs Layer Weight. -- Added: Lists can now be sent in Command/Rpc/Message/etc. -- Added: `[Server]`/`[Client]` can now be used outside of NetworkBehaviour. -- Added: Experimental [NetworkLerpRigidbody](../Components/NetworkLerpRigidbody.md) component that syncs position and velocity and applies them using Lerp. -- Fixed: NetworkAnimator now fires triggers immediately on owner. -- Fixed: `isServer` will now keep its value after calling `NetworkServer.Destroy`. -- Fixed: `[Client]` error message now correctly logs the name of the method. -- Fixed: Messages can now be nested within other Message types. -- Fixed: `[Server]`/`[Client]` now correctly give error when used on abstract method. -- Fixed: Abstract classes can now implement IMessageBase. -- Fixed: Weaver now correctly gives error when generating a reader methods for abstract classes. -- Changed: NetworkServer no longer runs update if there are no connections. -- Changed: NetworkBehaviour.IsDirty is now a public. -- Changed: SyncEvent are now obsolete and will be removed in the next version. -- Removed: isHeadless is now obsolete, Use preprocessor directive `#if UNITY_SERVER` instead. - -## Version 16.9.0 -- 2020-Aug-01 -- Added: [NetworkHeadlessLogger](../Components/NetworkHeadlessLogger.md) log handler that sets console color. -- Added: New Mirror List Server, see [Cloud folder](https://github.com/vis2k/Mirror/tree/master/Assets/Mirror/Cloud). -- Added: Experimental [NetworkRigidbody](../Components/NetworkRigidbody.md) component that syncs velocity and other rigidbody settings. -- Fixed: base method called inside Command/RPC now work if the first base class does not have an override. -- Fixed: NetworkRoomPlayer now cleans up roomSlots on disable. -- Fixed: Fallback and Multiplex now disable their transports when they are disabled. -- Fixed: Websockets transport SocketState now returns false if socket is `undefined`. -- Fixed: SyncEvents can now have the same name if they are in different classes. -- Fixed: You can now have multiple SyncEvents per class. -- Fixed: Message base classes are now processed even if they are declared later in the file. -- Fixed: Registering a prefab with and same GUID no longer gives an error. -- Fixed: Weaver now generates Serialize methods for classes that implement IMessageBase. -- Changed: NetworkProximityChecker now has slightly better performance. -- Changed: ClientRpc no longer need Rpc prefix. -- Changed: Commands no longer need Cmd prefix. -- Changed: TargetRpc no longer need Target prefix. -- Changed: NetworkManager.networkSceneName is now protected set as it should not be set directly. - -## Version 16.1.1 -- 2020-Jun-13 -- Added: [Command] now has an `ignoreAuthority` option for invoking Commands on objects the client doesn't have authority over, and Command methods can have an optional `NetworkConnectionToClient sender` parameter. -- Added: [ClientRpc] now has an `excludeOwner` option to prevent messages from going to the client that owns the object. -- Added: Commands and Rpc's can now be declared as virtual and overridden in derived classes. -- Added: NetworkLogSettings component and Log Settings Window. -- Added: SyncLists now support `AddRange`, `InsertRange`, and `RemoveAll`. -- Added: Network Room Manager now has a virtual `OnRoomServerPlayersNotReady` that fires on server from `CheckReadyToBegin`. -- Added: Network Room Player template now includes base Network Behaviour overrides. -- Added: Network Room Player now has a virtual hook for the index SyncVar, and the override is in the template. -- Added: Experimental Network Transform with more control settings and features. -- Added: [Network Ping Display](../Components/NetworkPingDisplay.md) component -- Fixed: Network Room Manager.minPlayers is now protected so it's available for derived classes. -- Fixed: Network Room Manager no longer does redundant player prefab registration in `OnStartClient`. -- Fixed: Network Room Player `OnClientEnterRoom` now correctly only fires on clients. -- Fixed: `RegisterClientMessages` was being incorrectly invoked for every scene change. -- Fixed: Network Behaviour `SyncMode` and `SyncInterval` was not showing in the inspector in some cases (regression). -- Fixed: Network Manager now cleans up network objects better when server stops. -- Fixed: Network Manager no longer tries to change to offline scene redundantly in `StopClient`. -- Fixed: Network Connection's `lastMessageTime` wasn't being properly initialized, causing incorrect idle timeout disconnects. -- Fixed: Websockets transport now correctly pauses and queues messages during scene changes and should otherwise be more stable with SSL -- Changed: **Breaking** Websockets Transport now requires full path to PFX Certificate file. -- Changed: Improvements were made to the Tanks example. -- Changed: Network Room Player now uses virtual SyncVar hook for ReadyStateChanged. -- Changed: Network Proximity Checker now uses direct distance check against player objects instead of Physics.SphereCastNonAlloc for better performance. -- Removed: Discord Transport - -## Version 13.0.1 -- 2020-May-06 -- Added: [Multiple Concurrent Additive Scenes Example](../Examples/MultipleAdditiveScenes/index.md). -- Added: [Network Match Checker](../Components/NetworkMatchChecker.md) component. Use this component to create many concurrent isolated matches within a single game server. -- Added: [SyncLists](../Guides/Sync/SyncLists.md) now have Find and FindAll functions. -- Added: Network Behaviour now has OnStopServer and OnStopClient virtual methods. -- Added: Weaver now supports custom Reader & Writer for types in other assemblies. -- Added: Network Manager now has an optional setting to check for and disconnect remote connections that have gone silent for a specified interval. -- Added: Network Manager now has a ReplaceHandler method to avoid warnings when attempting to double register message handlers. -- Added: `NetworkServer.SendToAll` now has an optional bool to only send to ready clients, and a `SendToReady` method that doesn't require a Network Identity. -- Fixed: Network Animator no longer double-fires SetTrigger / ResetTrigger on the host client. -- Fixed: Network Animator is no longer limited to one component per object. -- Fixed: Destroy is no longer invoked twice on the server for the player object. -- Fixed: `RegisterClientMessages` is no longer invoked twice on the client. -- Fixed: Network Behaviour `SyncMode` and `SyncInterval` was not showing in the inspector in some cases. -- Fixed: Telepathy Transport - `LateUpdate` now processes a limited amount of messages per tick to avoid deadlocks. -- Changed: Network Behaviour: `OnNetworkDestroy` was renamed to `OnStopClient`. -- Changed: **Breaking** RemovePlayerMessage has been removed as a potential security risk. Use `NetworkServer.RemovePlayerForConnection` instead. -- Changed: **Breaking** Network Behaviour: `OnRebuildObservers`, `OnCheckObserver`, and `OnSetHostVisibility` were moved to a separate class called `NetworkVisibility`. - -## Version 11.4.2 - 2020-Apr-03 -- Added: SyncVar hooks can be virtual now, and overridden in a derived class. -- Added: Virtual `OnRoomStopServer` added to Network Room Manager and Script Template. -- Added: 10K Networked Objects Benchmark Example. -- Fixed: Setting breakpoints in an IDE for Command's and Rpc's work correctly now. -- Fixed: `NetworkServer.SendToObservers` now reports correct channel to Mirror Profiler. -- Fixed: Network Room Manager's `roomPlayerPrefab` is now `protected` so it can be accessed in derived classes. -- Fixed: Network Room Player inspector and documentation updated to be less confusing. -- Fixed: Network Identity no longer double calls `NetworkServer.Destroy`. -- Fixed: Network Animator now correctly excludes parameters controlled by curves. -- Fixed: Network Behaviour now uses a property drawer for the SyncVar label so it displays better. -- Fixed: `NetworkServer.SendToReady` overloads are no longer ambiguous. -- Fixed: Network Room Manager no longer incorrectly destroys the game player object. It's left in the game scene to be cleaned up by Unity when the scene changes. -- Fixed: `StopHost` correctly raises `OnServerDisconnect` in Network Manager, and correctly unwinds before shutting down the server. -- Fixed: `isServer` is no longer incorrectly false on server in Network Identity's `OnDestroy`. -- Changed: Network Manager `offlineScene` and `onlineScene` store full paths now, so use SceneManager.GetActiveScene().path instead. -- Changed: Network Manager HUD now calls `StopHost` / `StopServer` / `StopClient` more appropriately. -- Changed: Network Manager HUD labels no longer say LAN. Associated docs also cleaned up to eliminate the misconception of Mirror being LAN only solution. -- Changed: Network Transform compression removed and message handling is much simpler now. -- Changed: Network Scene Checker initializes in Awake again because `OnEnable` proved to be unreliable in some cases. -- Changed: Network Manager will no longer lose references to scenes if they aren't in the Build Settings scene list, however moving or renaming scenes may cause references to be lost. -- Changed: **Breaking** Many obsolete methods and properties removed. Use [version 10](https://github.com/vis2k/Mirror/releases/tag/v10.4.7) first if upgrading from UNet or older Mirror. See [Deprecations](Deprecations.md) for complete list. - -## Version 10.4.7 - 2020-Mar-03 -- Added: Weaver will now block play mode and builds if there are weaver errors and show them in the console again. -- Added: `PooledNetworkReader` and `PooledNetworkWriter`, both Disposable. -- Added: `NetworkReader.ReadMessage`. -- Added: Network Discovery now handles headless server mode. -- Added: SyncVar, Cmd's and Rpc's now support Scriptable Objects via CreateInstance on the receiving side. -- Added: Discord Transport *Removed in v16.1.1* -- Fixed: `isClient` now returns true on clients in OnDestroy for networked objects. -- Fixed: Host Player race condition for Ready message. -- Fixed: Network Animator and Network Transform now correctly check for client authority in their respective Command methods. -- Fixed: Network Room Manager Script Template had a virtual method instead of an override. -- Fixed: Network Server's calls to NetworkConnectionToClient.Send now includes the channelId parameter that was missing. -- Fixed: Network Server's calls to SendToAll, SendToReady, and SendToObservers send to the exact connection if it is detected as local connection, instead of falling back to the .localConnection. -- Fixed: Network Server.SpawnObjects returns false if server isn't running. -- Fixed: Network Transform rotation detection improved. -- Fixed: Weaver generated code now builds properly for IL2CPP (again). -- Changed: StartHost in Network Manager is no longer a virtual method (and shouldn't have been). Override OnStartHost instead. -- Changed: Network Room Manager's OnRoomServerSceneLoadedForPlayer now includes NetworkConnection parameter. -- Changed: Network Scene Checker now works from OnEnable instead of Awake, and uses Scene instead of scene name. -- Changed: Renamed NeworkWriter.Write to WriteMessage for consistency. - -## Version 9.0.2 - 2020-Feb-04 -- Added: Network Animator now has a ResetTrigger function and server / client authority warnings. -- Added: Network Transform now has 3 new floats for Sensitivity to quiet down message traffic from micro changes. -- Added: Network Observer added to [Script Templates](ScriptTemplates.md) -- See the new Mirror section in the Assets > Create menu. -- Added: [Network Discovery](../Components/NetworkDiscovery.md) has been reimplemented including an example and script template -- thanks to all those who contributed! -- Added: [Network Scene Checker Component](../Components/NetworkSceneChecker.md). -- Added: Mirror Icon for all components. -- Added: Inspector Headers to Network Behaviour, Network Transform, and Network Animator. -- Added: URI added to supported data types. -- Added: `NetworkReaderPool` has been implemented in place of `new NetworkReader` everywhere, significantly reducing garbage allocation. -- Fixed: Network Transform and Network Animator now uses NetworkWriterPool. -- Fixed: Network Transform and Network Animator now respect `hasAuthority` for client owned objects. -- Fixed: Network Transform will now correctly teleport if time / distance are too large. -- Fixed: Network Animator now correctly syncs when clientAuthority is false. -- Fixed: Client owned objects are now destroyed when client disconnects (regression). -- Fixed: Client authority is now preserved for networked objects carried through scene change in DontDestroyOnLoad (DDOL). -- Fixed: Starting server immediately after canceling client connection attempt no longer throws a NRE. -- Fixed: IL2CPP builds no longer trigger an assert when stopping server. -- Fixed: SyncVars are now set for Host player before hook is invoked. -- Fixed: SyncDictionary now correctly updates the value before invoking callbacks. -- Fixed: StopHost no longer tries to change to the Offline scene twice. -- Fixed: Network Room Manager roomSlots are now correctly managed on both server and clients. -- Fixed: Network Room Manager now correctly supports multiple GamePlay scenes and adds a virtual `OnRoomServerAddPlayer`. -- Fixed: Additive scene operations no longer incorrectly lead to extraneous AddPlayer messages from clients. -- Fixed: `NetworkWriterPool` is now used everywhere instead of `new NetworkWriter` (we missed a couple when the pool was implemented). -- Fixed: Patch for Unity 2019.3.x `RequestScriptReload` was moved to EditorUtility from UnityEditorInternal.InternalEditorUtility. -- Fixed: Arrays of custom types are now correctly supported. -- Changed: Shutdown logic has been streamlined. -- Changed: `NetworkIdentity.GetSceneIdenity` method renamed to `GetSceneIdentity` (name typo). -- Changed: OnApplicationQuit virtual method added to Transport class and `Transport.activeTransport.Shutdown()` is no longer called from Network Manager. -- Changed: **Breaking** SyncVar Hooks now require **two** parameters, one each for the old and new value, and the property value is now set **before** the hook is called. - -## Version 6.7.7 - 2020-Jan-01 -- Added: [Script Templates](ScriptTemplates.md) -- See the new Mirror section in the Assets > Create menu. -- Added: Full Text Search added to docs. -- Added: Basic Chat example. -- Added: Some YouTube videos have been created and linked from various doc pages where appropriate. -- Added: Transports can now support using a URI for connection including port. -- Added: version.txt file is now included with the release version in it. -- Added: Structs that inherit from IMessageBase now generate serializers. -- Fixed: Components now appear in docs under API Reference. -- Fixed: Delayed disconnect in Basic Authenticator. -- Fixed: Multiplexer now handles OnClientConnect and GetMaxMessageSize correctly. -- Fixed: Network Room Manager OnRoomServerCreateGamePlayer now includes the Room Player Object as parameter. -- Changed: Room example now has Network Room Manager in the Offline scene and correctly switches to the Room scene when server / client is started. -- Changed: Network Manager startPositionIndex and loadingSceneAsync are now public. -- Changed: SceneMessage now has an optional customHandling flag so devs can handle their own custom scene loading, e.g. using Addressables. -- Changed: **Breaking** Network Transform now defaults to server authority and has a Client Authority checkbox. - -## Version 6.3.0 - 2019-Dec-09 -- Added: SyncMode selector now works for components on any scene objects owned by a client in addition to the player object, e.g. pets. -- Added: MessageBase now fully supports inheritance. -- Added: Room example now has UI button for host to return all clients to the Room scene and other improvements. -- Fixed: ReplacePlayerForConnection now works for existing scene objects as long as another player doesn't own the targeted object. -- Fixed: isClient and isServer are now true for networked objects in Start and OnStartClient / OnStartServer, respectively. -- Fixed: hasAuthority is now set before OnStartClient and OnStartLocalPlayer are invoked. -- Changed: connectionToClient is now used to assign client authority. -- Changed: In many respects, the Host player acts a lot more like a client and will reveal bugs better. -- Changed: ReplacePlayerForConnection now has an optional bool to retain authority of the previous object (default = false). -- Removed: `NetworkServer.SpawnWithClientAuthority` is deprecated in favor of overloads of `NetworkServer.Spawn`. - -## Version 5.0.2 - 2019-Nov-03 -- Added: SyncList and SyncSet custom Equality Comparer support. -- Added: Custom serializers may be implemented for any type in Cmd's and Rpc's. -- Added: [Fallback Transport](../Transports/Fallback.md). -- Fixed: SyncVar hooks are no longer called in Host if no change. -- Fixed: Network Identity no longer throws a null reference exception in RemoveClientAuthority. -- Fixed: Server transport now suspended during scene change to prevent erroneous messages. -- Fixed: SyncList, SyncDictionary and SyncSet now use a custom IEnumerator to avoid memory allocation. -- Fixed: sceneID is no longer reset in certain cases when editing a prefab. -- Changed: PreprocessorDefine code moved to CompilerSymbols folder to avoid paradox of missing symbols preventing the symbols being added to the project. -- Changed: Host player no longer gets authority assigned to all objects by default. -- Changed: Commands no longer bypass serialization for Host player, making debugging easier. -- Changed: Local connections now maintain their own message queue. -- Changed: Transport.Available is now abstract. -- Removed: Network Identity: Local Player Authority has been removed as no longer necessary. - -## Version 4.0.7 - 2019-Oct-03 -- Added: [Authenticators](../Components/Authenticators/index.md) support to authenticate clients in the Connect phase. -- Added: Profiler events. These events can be subscribed to by the [Network Profiler](../Guides/Profiler.md) to provide visual information. -- Added: Transports now include channel in profiler events. -- Added: Transport abstract class now supports sending a message to a list of connection id's. -- Fixed: SceneMessage now has sceneOperation enum so clients can properly handle additive scenes. -- Fixed: NetworkClient handlers are now cleared in Shutdown. -- Fixed: Offline scene is no longer reloaded when client fails to connect or is rejected. -- Fixed: Start Position Index is now reset to zero when server is stopped. -- Fixed: Network Room Players are now all in DontDestroyOnLoad so they don't respawn in the game scene. -- Fixed: Network Room example player controller restores main camera on disable. -- Fixed: Components with different sync intervals were not sending updates to clients. -- Fixed: In certain cases, weaver wouldn't weave some external assemblies. -- Fixed: Network Animator now does a full sync for new clients. -- Fixed: Network Behaviour inspector now shows SyncMode for private SyncVars. -- Fixed: Calling Commands and Rpcs of parent classes from inherited classes works as it should. -- Fixed: Telepathy no longer hangs when attempting to connect to a nonexistent host. -- Fixed: Websockets Transport now properly returns the client endpoint information via `ServerGetClientAddress`. -- Fixed: WebGL build now works with ArraySegment. -- Changed: Mirror is now free of garbage memory allocation on the sending side. - - Some transports may still have a little garbage allocation yet. -- Changed: Deprecated the AddPlayerMessage extraMessage byte\[\] in favor of an easier approach to [Custom Players](../Guides/GameObjects/SpawnPlayerCustom.md). - - This is a breaking change: The virtual method OnServerAddPlayer loses the AddPlayerMessage parameter. -- Changed: `NetworkIdentity.RemoveAuthorityForConnection` is now easier to use: no need to supply the current "owner" anymore. -- Changed: Renamed `NetworkConnection.playerController` to `identity` ... see [Deprecations](Deprecations.md) for details. -- Changed: Lobby system renamed to Room to better align the name for what it is and make way for a future Lobby framework. - -## Version 3.17.4 - 2019-Sep-04 -- Added: Custom Network Readers & Writers via extension methods. -- Added: Network Sync Mode selector on components to sync to observers (default) or just the owner. -- Added: SyncVars now support structs and enums in other assemblies. -- Added: Support for reading and writing array segments. -- Added: Network Animator now has layers support. -- Added: New virtual method OnServerChangeScene to Network Manager. -- Added: XML summary comments for intellisense and future generated class docs. -- Updated Examples and Documentation. -- Fixed: SceneID was not set to 0 for prefab variants. -- Fixed: Observers were not properly rebuilt on scene changes. -- Fixed: SyncVar hooks were not able to change other SyncVars in Host mode. -- Fixed: Telepathy not setting socket options on accepted clients. -- Fixed: Catch IL2CPP bug. -- Fixed: Telepathy and Websockets now start connections ID's at 1 instead of 2. -- Fixed: Websockets support for SSL restored. -- Fixed: Network Manager no longer complains about missing player prefab if auto-create is disabled. -- Fixed: Removed a garbage allocation in Network Transform. -- Fixed: NetworkClient.Ready was being called unnecessarily in certain cases, e.g. SceneMessages. -- Changed: Documentation moved to website and API generated docs implemented. -- Changed: AddPlayerForConnection handler is now internal to keep safety checks intact. -- Changed: A bunch of messages converted to value types for performance. - -## Version 3.11.6 - 2019-Jul-10 -- Fixed: Telepathy IPv4, IPv6, and FQDN should all work now. -- Fixed: TelepathyTransport error in UWP builds. -- Fixed: OnApplicationQuit is handled better now. -- Fixed: Performance and memory allocation improvements. -- Changed: Telepathy Source is now included instead of a DLL. - -## Version 3.10.10 - 2019-Jun-19 -- Added: Scene Message now supports params for SceneMode (Normal / Additive) and PhysicsMode (2D / 3D). -- Added: ClientScene.Send now has an optional ChannelId parameter. -- Added: ASMDEF to Examples folder. -- Added: Support for sending and receiving ArraySegment\ -- Added: IReadOnlyList\ in SyncLists. -- Fixed: Network Manager not switching to correct scene in some cases. -- Fixed: ListServer Ping not found in WebGL. -- Fixed: TelepathyTransport.GetMaxPacketSize uses the new configurable max size. -- Fixed: Significant reduction in memory allocation and garbage collection. -- Changed: Use transform.localPosition and transform.localRotation for better VR support. -- Removed: Websockets send queues (they never worked) and SSL (temporarily because it didn't work). - -## Version 3.6.7 -- 2019-Apr-28 -- Changed: NetworkReader now uses ArraySegment\ to minimize allocations. - -## Version 3.6.6 -- 2019-Apr-24 -- Fixed: Reverted two internal refactor commits that had unintended consequences. - -## Version 3.6.5 -- 2019-Apr-23 -- Fixed: Unity 2019.1 compatibility. -- Fixed: Erroneous error indicating prefabs were missing Scene ID's. -- Fixed: OnDeserializeSafely now works without allocations. -- Fixed: Weaver not writing symbol files, preventing breakpoints from working in Visual Studio. -- Fixed: Network Identity SceneID generation now uses RNG Crypto Service Provider. -- Fixed: Scene lighting in Additive example. -- Fixed: Player Prefab transform details now respected when instantiated in the absence of NetworkStartPosition. -- Removed: Tests folder from Unity package generation (no end-user value). - -## Version 3.5.9 -- 2019-Apr-12 -- Fixed: Network Manager round-robin mode using NetworkStartPosition objects now uses hierarchy sibling order. -- Fixed: IsLocalPlayer is now reliably accurate in `Start()` by combining OwnerMessage and SpawnPrefabMessage. -- Fixed: Stack overflow issues with Weaver and Cecil. -- Fixed: Corrected assembly paths passed to weaver. -- Fixed: Enum bandwidth reduced in SyncVars, Commands, and Rpcs. -- Fixed: Placeholder files added for removed code files so updating works better. -- Changed: Network Manager `isHeadless` is a static property now, changed from `IsHeadless()`. - -## Version 3.5.3 -- 2019-Apr-10 -- Fixed: Exceptions in overrides of Network Manager and other components incorrectly silenced. -- Fixed: Lobby system sometimes would not spawn and swap game player prefabs into the game scene. -- Fixed: Application.targetFrameRate no longer set in host mode. -- Changed: Telepathy: Split MaxMessageSize to allow setting a different value for client and server. - -## Version 3.4.9 -- 2019-Apr-6 -- Added: Semantic Versioning (which is why we jumped from 1.6 to 3.4.9). -- Added: [SyncDictionary](../Guides/Sync/SyncDictionary.md). -- Added: [SyncHashSet](../Guides/Sync/SyncHashSet.md). -- Added: [SyncSortedSet](../Guides/Sync/SyncSortedSet.md). -- Added: SyncList and SyncDictionary support all IList and IDictionary derived types, respectively. -- Added: Documentation for [SyncVars](../Guides/Sync/SyncVars.md). -- Added: Documentation for [SyncEvents](../Guides/Sync/SyncEvent.md). -- Added: NoRotation to Network Transform. -- Added: Scale is now included in spawn payload along with position and rotation. -- Added: Generic `IMessageBase` to allow struct message types. -- Added: Weaver now supports Vector2Int and Vector3Int. -- Added: List Server example. -- Added: Additive Scenes example. -- Fixed: SyncLists now work correctly for primitives and structs. -- Fixed: SyncVar Hooks now will update the local property value after the hook is called. - - You no longer need to have a line of code in your hook method to manually update the local property. -- Fixed: Host should not call Disconnect on transports. -- Fixed: NetworkAnimimator now supports up to 64 animator parameters. -- Fixed: Network Manager `StartServer` no longer assumes scene zero is the default scene...uses `GetActiveScene` now. -- Fixed: `NetworkServer.Shutdown` now resets `netId` to zero. -- Fixed: Observers are now properly rebuilt when client joins and `OnRebuildObservers` / `OnCheckObserver` is overridden. -- Fixed: NetworkProximityChecker: On rare occasion, player could be excluded from observers rebuild. -- Fixed: NetworkLobbyPlayer `OnClientReady` works now. -- Fixed: NetworkLobbyPlayer Remove button not showing for P1 when Server Only. -- Fixed: NetworkLobbyManager `pendingPlayers` and `lobbySlots` lists are now public for inheritors. -- Fixed: Offline scene switching now works via `StopClient()`. -- Fixed: Pong example updated. -- Fixed: Source Weaver was deleting PDB files, preventing breakpoints and debugging from working. -- Changed: TargetRpc NetworkConnection parameter is now optional...the calling client's NetworkConnection is default. -- Changed: Movement example replaced with Tank example. -- Changed: NetworkClient functions are all static now, so the singleton is gone. Use NetworkClient directly. -- Changed: SyncList now supports structs directly, making SyncListSTRUCT obsolete. -- Removed: SyncListSTRUCT - Use SyncList instead. -- Removed: NetworkClient.ShutdownAll is obsolete -- Use NetworkClient.Shutdown instead. - -## Version 1.6 -- 2019-Mar-14 -- Fixed: Websockets transport moved to Mirror.Websocket namespace. -- Fixed: Network Animator bandwidth abuse. -- Fixed: Network Animator float sync bug. -- Fixed: Persistent SceneID's for Networked objects. -- Changed: Documentation for [Transports](../Transports/index.md). -- Changed: Weaver is now full source...FINALLY! -- Changed: ClientScene.AddPlayer 2nd parameter is now `byte[] extraData` instead of `MessageBase extraMessage`. - - Please refer to the code sample [here](../Guides/GameObjects/SpawnPlayerCustom.md) to see how to update your code. -- Changed: Network Manager -- Headless Auto-Start moved to `Start()` from `Awake()`. -- Changed: Removed Message ID's for all messages - See [Network Messages](../Guides/Communications/NetworkMessages.md) for details. - - Message IDs are now generated automatically based on the message name. - - Previously you would call Send(MyMessage.MsgId, message), now you call Send(message). -- Removed: Documentation for Groove Transport - use Websockets Transport instead. - -## Version 1.5 -- 2019-Mar-01 -- Added: **Migration Tool** to (mostly) automate conversion from UNet. -- Added: Full support for WebSockets and WebSocketsSecure to replace UNet LLAPI. -- Added: Transport Multiplexer - allows the use of multiple concurrent transports. -- Added: NetworkLobbyManager and NetworkLobbyPlayer with example game. -- Added: Configurable Server Tick rate in Network Manager. -- Added: New virtual OnClientChangeScene fires right before SceneManager.LoadSceneAsync is executed. -- Added: Unit tests for Weaver. -- Fixed: Garbage allocations removed from a lot of things (more work to do, we know). -- Fixed: NetworkProximityChecker now uses `OverlapSphereNonAlloc` and `OverlapCircleNonAlloc`. -- Fixed: SyncVar hook not firing when clients joined. -- Fixed: Network Manager no longer assumes it's on Scene(0) in Build Settings. -- Fixed: Network Animator no longer limited to 6 variables. -- Fixed: TelepathyTransport delivering messages when disabled. -- Changed: Minimum Unity version: **2018.3.6** -- Removed: SceneAttribute.cs (merged to CustomAttributes.cs). -- Removed: `NetworkClient.allClients` (Use `NetworkClient.singleton` instead). -- Removed: `NetworkServer.hostId` and `NetworkConnection.hostId` (holdovers from LLAPI). -- Removed: `NetworkConnection.isConnected` (Network Connection is always connected). -- Removed: `Transport.GetConnectionInfo` (Use `ServerGetClientAddress` instead). - -## Version 1.4 -- 2019-Feb-01 -- Added: HelpURL attributes to components. -- Added: Automatic targetFramerate for headless builds. -- Added: ByteMessage to Messages class. -- Fixed: Connecting state can be canceled properly. -- Fixed: Network Transform interpolation applied to client's own object. -- Fixed: Objects are spawned with correct rotation. -- Fixed: SceneId assignment. -- Fixed: Changed syncInterval wasn't saved...it is now. -- Fixed: Additive Scene loading. -- Changed: **Mirror is now full source** -- no more DLL's. -- Changed: **Transports are now components** -- TCP, UDP, WebGL, Steam. -- Changed: Transport class now dispatches Unity Events. -- Changed: `NetworkServer.SendToClientOfPlayer` uses `NetworkIdentity` now. -- Changed: `NetworkServer.SendToObservers` uses `NetworkIdentity` parameter now. -- Changed: `NetworkServer.SendToReady` uses `NetworkIdentity` now. -- Changed: `NetworkServer.DestroyPlayerForConnection` uses `NetworkIdentity.spawned` now. -- Changed: `NetworkConnection.Dispose` uses `NetworkIdentity.spawned` now. -- Changed: `NetworkReader.ReadTransform` uses `NetworkIdentity.spawned` now. -- Changed: Network Transform reimplemented -- physics removed, code simplified. -- Removed: `NetworkClient.hostPort` (port is handled at Transport level). -- Removed: `NetworkServer.FindLocalObject` (Use `NetworkIdentity.spawned[netId]` instead). -- Removed: `ClientScene.FindLocalObject` (Use `NetworkIdentity.spawned[netId]` instead). diff --git a/doc/Articles/General/Deprecations.md b/doc/Articles/General/Deprecations.md deleted file mode 100644 index 4aecf0493..000000000 --- a/doc/Articles/General/Deprecations.md +++ /dev/null @@ -1,367 +0,0 @@ -# Deprecations - -Certain features of Unity Networking (UNet) were removed from Mirror or modified for various reasons. This page will identify all changed and removed features, properties, and methods, the reason for change or removal, and possible alternatives. - -> Note: Some changes in this document may apply to an upcoming release to the Asset Store. - -## Match Namespace & Host Migration - -As part of the Unity Services, this entire namespace was removed. It didn't work well to begin with, and was incredibly complex to be part of the core networking package. We expect this, along with other back-end services, will be provided through standalone apps that have integration to Mirror. - -## Network Server Simple - -This was too complex and impractical to maintain for what little it did, and was removed. There are much easier ways to make a basic listen server, with or without one of our transports. - -## Couch Co-Op - -The core networking was greatly simplified by removing this low-hanging fruit. It was buggy, and too convoluted to be worth fixing. For those that need something like this, consider defining a non-visible player prefab as a message conduit that spawns actual player prefabs with client authority. All inputs would route through the conduit prefab to control the player objects. - -## Message Types - -The `MsgType` enumeration was removed. All message types are generated dynamically. Use `Send` instead. - -## Network Transform - -[Network Transform](../Components/NetworkTransform.md) was significantly simplified so that it only syncs position, rotation and scale. Rigidbody support was removed. We may create a new NetworkRigidbody component that will be server authoritative with physics simulation and interpolation. - -## Network Animator - -[Network Animator](../Components/NetworkAnimator.md) was also simplified, as it batches all Animator parameters into a single update message. - -## SyncVar Hook Parameters - -[SyncVar](../Guides/Sync/SyncVars.md) property values are now updated before the hook is called, and hooks now require two parameters of the same type as the property: `oldValue` and `newValue` - -## SyncListSTRUCT - -Use `SyncList` instead. - -## SyncList Operations - -- `OP_REMOVE` was replaced by `OP_REMOVEAT` -- `OP_DIRTY` was replaced by `OP_SET` - -## SyncIDictionary Operations - -- `OP_DIRTY` was replaced by `OP_SET` - -## Quality of Service Flags - -In classic UNet, QoS Flags were used to determine how packets got to the remote end. For example, if you needed a packet to be prioritized in the queue, you would specify a high priority flag which the Unity LLAPI would then receive and deal with appropriately. Unfortunately, this caused a lot of extra work for the transport layer and some of the QoS flags did not work as intended due to buggy code that relied on too much magic. - -In Mirror, QoS flags were replaced with a "Channels" system. While the default transport, [Telepathy](../Transports/Telepathy.md), does not use channels at all because it's TCP-based, other transports, such as [Ignorance](../Transports/Ignorance.md) and [LiteNetLib4Mirror](../Transports/LiteNetLib4Mirror.md), do support them. - -The currently defined channels are: -- `Channels.DefaultReliable = 0` -- `Channels.DefaultUnreliable = 1` - -## Changes by Class - -### NetworkManager - -- `networkPort` - Removed as part of separating Transports to components. Not all transports use ports, but those that do have a field for it. See [Transports](../Transports/index.md) for more info. - -- `IsHeadless()` - Use compiler symbol `UNITY_SERVER` instead. - -- `client` - Use NetworkClient directly, it will be made static soon. For example, use `NetworkClient.Send(message)` instead of `NetworkManager.client.Send(message)`. - -- `IsClientConnected()` - Use static property `NetworkClient.isConnected` instead. - -- `onlineScene` and `offlineScene` - These store full paths now, so use SceneManager.GetActiveScene().path instead. - -- `OnStartClient(NetworkClient client)` - Override OnStartClient() instead since all `NetworkClient` methods are static now. - -- `OnClientChangeScene(string newSceneName)` - Override `OnClientChangeScene(string newSceneName, SceneOperation sceneOperation, bool customHandling)` instead. - -- `OnClientChangeScene(string newSceneName, SceneOperation sceneOperation)` - Override `OnClientChangeScene(string newSceneName, SceneOperation sceneOperation, bool customHandling)` instead. - -- `OnServerAddPlayer(NetworkConnection conn, AddPlayerMessage extraMessage)` - Override `OnServerAddPlayer(NetworkConnection conn)` instead. See [Custom Player Spawn Guide](../Guides/GameObjects/SpawnPlayerCustom.md) for details. - -- `OnServerRemovePlayer(NetworkConnection conn, NetworkIdentity player)` - Use `NetworkServer.RemovePlayerForConnection(NetworkConnection conn, GameObject player, bool keepAuthority = false)` instead. - -### NetworkRoomManager - -- `OnRoomServerCreateGamePlayer(NetworkConnection conn)` - Use `OnRoomServerCreateGamePlayer(NetworkConnection conn, GameObject roomPlayer)` instead. - -- `OnRoomServerSceneLoadedForPlayer(GameObject roomPlayer, GameObject gamePlayer)` - Use `OnRoomServerSceneLoadedForPlayer(NetworkConnection conn, GameObject roomPlayer, GameObject gamePlayer)` instead. - -### NetworkIdentity - -- `clientAuthorityOwner` - Use connectionToClient instead - -- `GetSceneIdenity` - Use `GetSceneIdentity` instead (typo in original name) - -- `RemoveClientAuthority(NetworkConnection conn)` - NetworkConnection parameter is no longer needed and nothing is returned - -- Local Player Authority checkbox - This checkbox is no longer needed, and we simplified how [Authority](../Guides/Authority.md) works in Mirror. - -### NetworkBehaviour - -- `sendInterval` attribute - Use `NetworkBehaviour.syncInterval` field instead. Can be modified in the Inspector too. - -- `List m_SyncObjects` - Use `List syncObjects` instead. - -- `OnSetLocalVisibility(bool visible)` - Override `OnSetHostVisibility(bool visible)` instead. - -- `OnRebuildObservers`, `OnCheckObserver`, and `OnSetHostVisibility` were moved to a separate class called `NetworkVisibility` - -- `NetworkBehaviour.OnNetworkDestroy` was renamed to `NetworkBehaviour.OnStopClient`. - -### NetworkConnection - -- `hostId` - Removed because it's not needed ever since we removed LLAPI as default. It's always 0 for regular connections and -1 for local connections. Use `connection.GetType() == typeof(NetworkConnection)` to check if it's a regular or local connection. - -- `isConnected` - Removed because it's pointless. A NetworkConnection is always connected. - -- `InvokeHandlerNoData(int msgType)` - Use `InvokeHandler` instead. - -- `playerController` - renamed to `identity` since that's what it is: the `NetworkIdentity` for the connection. If you need to convert a project after this change, Visual Studio / VS Code can help...read more [here](PlayerControllerToIdentity.md). - -- `RegisterHandler(short msgType, NetworkMessageDelegate handler)` - Use `NetworkServer.RegisterHandler()` or `NetworkClient.RegisterHandler()` instead. - -- `UnregisterHandler(short msgType)` - Use `NetworkServer.UnregisterHandler()` or `NetworkClient.UnregisterHandler()` instead. - -- `Send(int msgType, MessageBase msg, int channelId = Channels.DefaultReliable)` - Use `Send(msg, channelId)` instead. - -### NetworkServer - -- `FindLocalObject(uint netId)` - Use `NetworkIdentity.spawned[netId].gameObject` instead. - -- `RegisterHandler(int msgType, NetworkMessageDelegate handler)` - Use `RegisterHandler(T msg)` instead. - -- `RegisterHandler(MsgType msgType, NetworkMessageDelegate handler)` - Use `RegisterHandler(T msg)` instead. - -- `UnregisterHandler(int msgType)` - Use `UnregisterHandler(T msg)` instead. - -- `UnregisterHandler(MsgType msgType)` - Use `UnregisterHandler(T msg)` instead. - -- `SendToAll(int msgType, MessageBase msg, int channelId = Channels.DefaultReliable)` - Use `SendToAll(T msg, int channelId = Channels.DefaultReliable)` instead. - -- `SendToClient(int connectionId, int msgType, MessageBase msg)` - Use `NetworkConnection.Send(T msg, int channelId = Channels.DefaultReliable)` instead. - -- `SendToClient(int connectionId, T msg)` - Use `NetworkConnection.Send(T msg, int channelId = Channels.DefaultReliable)` instead. - -- `SendToClientOfPlayer(NetworkIdentity identity, int msgType, MessageBase msg)` - Use `SendToClientOfPlayer(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable)` instead. - -- `SendToReady(NetworkIdentity identity, short msgType, MessageBase msg, int channelId = Channels.DefaultReliable)` - Use `SendToReady(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable)` instead. - -- `SpawnWithClientAuthority(GameObject obj, GameObject player)` - Use `Spawn(GameObject obj, GameObject player)` instead. - -- `SpawnWithClientAuthority(GameObject obj, NetworkConnection ownerConnection)` - Use `Spawn(GameObject obj, NetworkConnection ownerConnection)` instead. - -- `SpawnWithClientAuthority(GameObject obj, Guid assetId, NetworkConnection ownerConnection)` - Use `Spawn(GameObject obj, Guid assetId, NetworkConnection ownerConnection)` instead - -### NetworkClient - -- `NetworkClient singleton` - Use `NetworkClient` directly. Singleton isn't needed anymore as all functions are static now. - Example: `NetworkClient.Send(message)` instead of `NetworkClient.singleton.Send(message)`. - -- `allClients` - Use `NetworkClient` directly instead. There is always exactly one client. - -- `GetRTT()` - Use `NetworkTime.rtt` instead. - -- `RegisterHandler(int msgType, NetworkMessageDelegate handler)` - Use `RegisterHandler(T msg)` instead. - -- `RegisterHandler(MsgType msgType, NetworkMessageDelegate handler)` - Use `RegisterHandler(T msg)` instead. - -- `UnregisterHandler(int msgType)` - Use `UnregisterHandler(T msg)` instead. - -- `UnregisterHandler(MsgType msgType)` - Use `UnregisterHandler(T msg)` instead. - -- `Send(short msgType, MessageBase msg)` - Use `Send(T msg, int channelId = Channels.DefaultReliable)` with no message id instead - -- `ShutdownAll()` - Use `Shutdown()` instead. There is only one client. - -### ClientScene - -- `FindLocalObject(uint netId)` - Use `NetworkIdentity.spawned[netId]` instead. - -### Messages - -Basic messages of simple types were all removed as unnecessary bloat. You can create your own message classes instead. - -- `StringMessage` -- `ByteMessage` -- `BytesMessage` -- `IntegerMessage` -- `DoubleMessage` -- `EmptyMessage` - -NetworkMessage requires structs in all cases - classes no longer supported - -### NetworkReader - -- `Read(byte[] buffer, int offset, int count)` - Use `ReadBytes` instead. - -- `ReadPackedInt32(int value)` - Use `ReadInt32(int value)` instead - -- `ReadPackedUInt32(uint value)` - Use `ReadUInt32(uint value)` instead - -- `ReadPackedUInt64(ulong value)` - Use `ReadUInt64(ulong value)` instead - -### NetworkWriter - -- `Write(bool value)` - Use `WriteBoolean` instead. - -- `Write(byte value)` - Use `WriteByte` instead. - -- `Write(sbyte value)` - Use `WriteSByte` instead. - -- `Write(short value)` - Use `WriteInt16` instead. - -- `Write(ushort value)` - Use `WriteUInt16` instead. - -- `Write(int value)` - Use `WriteInt32` instead. - -- `Write(uint value)` - Use `WriteUInt32` instead. - -- `Write(long value)` - Use `WriteInt64` instead. - -- `Write(ulong value)` - Use `WriteUInt64` instead. - -- `Write(float value)` - Use `WriteSingle` instead. - -- `Write(double value)` - Use `WriteDouble` instead. - -- `Write(decimal value)` - Use `WriteDecimal` instead. - -- `Write(string value)` - Use `WriteString` instead. - -- `Write(char value)` - Use `WriteChar` instead. - -- `Write(Vector2 value)` - Use `WriteVector2` instead. - -- `Write(Vector2Int value)` - Use `WriteVector2Int` instead. - -- `Write(Vector3 value)` - Use `WriteVector3` instead. - -- `Write(Vector3Int value)` - Use `WriteVector3Int` instead. - -- `Write(Vector4 value)` - Use `WriteVector4` instead. - -- `Write(Color value)` - Use `WriteColor` instead. - -- `Write(Color32 value)` - Use `WriteColor32` instead. - -- `Write(Guid value)` - Use `WriteGuid` instead. - -- `Write(Transform value)` - Use `WriteTransform` instead. - -- `Write(Quaternion value)` - Use `WriteQuaternion` instead. - -- `Write(Rect value)` - Use `WriteRect` instead. - -- `Write(Plane value)` - Use `WritePlane` instead. - -- `Write(Ray value)` - Use `WriteRay` instead. - -- `Write(Matrix4x4 value)` - Use `WriteMatrix4x4` instead. - -- `Write(NetworkIdentity value)` - Use `WriteNetworkIdentity` instead. - -- `Write(GameObject value)` - Use `WriteGameObject` instead. - -- `Write(byte[] buffer, int offset, int count)` - Use `WriteBytes` instead. - -- `WritePackedInt32(int value)` - Use `WriteInt32(int value)` instead - -- `WritePackedUInt32(uint value)` - Use `WriteUInt32(uint value)` instead - -- `WritePackedUInt64(ulong value)` - Use `WriteUInt64(ulong value)` instead - -### Transport - -- `GetConnectionInfo(int connectionId, out string address)` - Use `ServerGetClientAddress(int connectionId)` instead. - -### TelepathyTransport - -- `MaxMessageSize` - Use `MaxMessageSizeFromClient` or `MaxMessageSizeFromServer` instead. diff --git a/doc/Articles/General/Integrations/Dissonance.jpg b/doc/Articles/General/Integrations/Dissonance.jpg deleted file mode 100644 index 069786e60..000000000 Binary files a/doc/Articles/General/Integrations/Dissonance.jpg and /dev/null differ diff --git a/doc/Articles/General/Integrations/MasterAudioMultiplayer.jpg b/doc/Articles/General/Integrations/MasterAudioMultiplayer.jpg deleted file mode 100644 index 53d0ad2cb..000000000 Binary files a/doc/Articles/General/Integrations/MasterAudioMultiplayer.jpg and /dev/null differ diff --git a/doc/Articles/General/Integrations/NobleConnectFree.jpg b/doc/Articles/General/Integrations/NobleConnectFree.jpg deleted file mode 100644 index e1426579e..000000000 Binary files a/doc/Articles/General/Integrations/NobleConnectFree.jpg and /dev/null differ diff --git a/doc/Articles/General/Integrations/Rucksack.jpg b/doc/Articles/General/Integrations/Rucksack.jpg deleted file mode 100644 index 3e0526707..000000000 Binary files a/doc/Articles/General/Integrations/Rucksack.jpg and /dev/null differ diff --git a/doc/Articles/General/Integrations/SmoothSync.jpg b/doc/Articles/General/Integrations/SmoothSync.jpg deleted file mode 100644 index 09b5e5d1e..000000000 Binary files a/doc/Articles/General/Integrations/SmoothSync.jpg and /dev/null differ diff --git a/doc/Articles/General/Integrations/SteamworksNetworking.jpg b/doc/Articles/General/Integrations/SteamworksNetworking.jpg deleted file mode 100644 index 439cb8487..000000000 Binary files a/doc/Articles/General/Integrations/SteamworksNetworking.jpg and /dev/null differ diff --git a/doc/Articles/General/Integrations/WeatherMaker.jpg b/doc/Articles/General/Integrations/WeatherMaker.jpg deleted file mode 100644 index 431618df5..000000000 Binary files a/doc/Articles/General/Integrations/WeatherMaker.jpg and /dev/null differ diff --git a/doc/Articles/General/Integrations/index.md b/doc/Articles/General/Integrations/index.md deleted file mode 100644 index 25f6a483b..000000000 --- a/doc/Articles/General/Integrations/index.md +++ /dev/null @@ -1,35 +0,0 @@ -# Integrations - -Here we will maintain a list of assets known to be compatible with Mirror. If you know of others, please have the publisher contact us directly in our [Discord](https://discord.gg/2BvnM4R). - -## [SmoothSync](https://assetstore.unity.com/packages/tools/network/smooth-sync-96925) - -![SmoothSync](SmoothSync.jpg) - -## [Weather Maker](https://assetstore.unity.com/packages/tools/particles-effects/weather-maker-unity-weather-system-sky-water-volumetric-clouds-a-60955) - -![Weather Maker](WeatherMaker.jpg) - -## [Noble Connect Free](https://assetstore.unity.com/packages/tools/network/noble-connect-free-141599) - -![Noble Connect Free](NobleConnectFree.jpg) - -## [Dissonance Voice Chat](https://assetstore.unity.com/packages/tools/audio/dissonance-voice-chat-70078) - -![Dissonance](Dissonance.jpg) - -## [RTS Engine](https://assetstore.unity.com/packages/templates/packs/rts-engine-79732) - -![RTS Engine](rts-engine.png) - -## [Rucksack](https://assetstore.unity.com/packages/templates/systems/rucksack-multiplayer-inventory-system-114921) - -![Rucksack](Rucksack.jpg) - -## [Steamworks Networking](https://assetstore.unity.com/packages/tools/integration/steamworks-networking-151300) - -![Steamworks Networking](SteamworksNetworking.jpg) - -## [Master Audio Multiplayer](https://assetstore.unity.com/packages/tools/audio/master-audio-multiplayer-69547) - -![Master Audio Multiplayer](MasterAudioMultiplayer.jpg) diff --git a/doc/Articles/General/Integrations/rts-engine.png b/doc/Articles/General/Integrations/rts-engine.png deleted file mode 100644 index a2a822f79..000000000 Binary files a/doc/Articles/General/Integrations/rts-engine.png and /dev/null differ diff --git a/doc/Articles/General/Migration.md b/doc/Articles/General/Migration.md deleted file mode 100644 index 1b1e5951e..000000000 --- a/doc/Articles/General/Migration.md +++ /dev/null @@ -1,234 +0,0 @@ -# Migration Guide - -## Migrating a project from UNet (HLAPI) - -This guide gives you a step by step instruction for migrating your project from HLAP to Mirror. Mirror is a fork of UNet. As such the migration is straight forward for most projects. - -You should review the information on the [Deprecations](Deprecations.md) page to see if your project will be impacted. - -There's also a Migration Tool you can try: - - -### 1. BACKUP - -You have been warned. - -### 2. Install Mirror and Restart Unity - -Get Mirror from the [asset store](https://assetstore.unity.com/packages/tools/network/mirror-129321) and import it in your project. - -Alternatively you can grab the latest [release](https://github.com/vis2k/Mirror/releases) from GitHub if you're feeling adventurous, but be aware that bleeding edge dev releases are not necessarily stable. - -**NOTE:** You must restart Unity after adding Mirror to the project for the components menu to update correctly. - -### 3. Replace namespace - -Replace `UnityEngine.Networking` for `Mirror` everywhere in your project. For example, if you have this: - -```cs -using UnityEngine.Networking; - -public class Player : NetworkBehaviour -{ - ... -} -``` - -replace it with: - -```cs -using Mirror; - -public class Player : NetworkBehaviour -{ - ... -} -``` - -At this point, you might get some compilation errors. Don't panic, these are easy to fix. Keep going... - -### 4. Replace playerController with identity - -Replace references to `NetworkConnection.playerController` with `NetworkConnection.identity`. Click [here](PlayerControllerToIdentity.md) for guidance. - -### 5. Remove NetworkSettings - -NetworkSettings in UNet have channels, but this is flat out broken. Rather than ignoring your settings we removed channels from NetworkSettings completely. `sendInterval` is now set in code and / or the inspector too. - -For example, if you have this code: - -```cs -[NetworkSettings(channel=1,sendInterval=0.05f)] -public class NetStreamer : NetworkBehaviour -{ - ... -} -``` - -replace it with: - -```cs -public class NetStreamer : NetworkBehaviour -{ - void Start() - { - syncInterval = 0.05f; - } -} -``` - -Please note that the default transport [Telpathy](../Transports/Telepathy.md), completely ignores channels, all messages are reliable, sequenced and fragmented. They just work with no fuss. If you want to take advantage of unreliable channels try a UDP or Steam [transport](../Transports/index.md) instead. - -### 6. Change SyncListStruct to SyncList - -There is a bug in the original UNet Weaver that makes it mess with our `Mirror.SyncListStruct` without checking the namespace. In Mirror, we fixed SyncLists so that they work with structs by default. - -For example, if you have definitions like: - -```cs -public class SyncListQuest : SyncListStruct { } -``` - -replace them with: - -```cs -public class SyncListQuest : SyncList { } -``` - -### 7. Replace NetworkHash128 and NetworkInstanceId - -These have been changed to System.Guid and uint, respectively. - -For example, if you have something like this: - -```cs -public sealed class SpawnItemMessage : MessageBase -{ - public NetworkHash128 assetID; - public NetworkInstanceId networkInstanceID; - public Vector3 position; - public Quaternion rotation; -} -``` - -replace with: - -```cs -public sealed struct SpawnItemMessage : NetworkMessage -{ - public System.Guid assetID; - public uint networkInstanceID; - public Vector3 position; - public Quaternion rotation; -} -``` - -### 8. Update your synclist callbacks - -In UNet, SyncLists have a callback delegate that gets called in the client whenever the list is updated. We have changed the callback to be a C\# event instead and we also pass the item that was updated/removed. - -For example, if you have this code: - -```cs -using UnityEngine; -using UnityEngine.Networking; - -public class MyBehaviour : NetworkBehaviour -{ - public SyncListInt m_ints = new SyncListInt(); - - private void OnIntChanged(SyncListInt.Operation op, int index) - { - Debug.Log("list changed " + op); - } - - public override void OnStartClient() - { - m_ints.Callback = OnIntChanged; - } -} -``` - -replace it with: - -```cs -using UnityEngine; -using Mirror; - -public class MyBehaviour : NetworkBehaviour -{ - public SyncListInt m_ints = new SyncListInt(); - - private void OnIntChanged(SyncListInt.Operation op, int index, int oldItem, int newItem) - { - Debug.Log("list changed " + op + " old item: " + item + " new item: " + newItem); - } - - public override void OnStartClient() - { - m_ints.Callback += OnIntChanged; - } -} -``` - -Notice the callback will also work in the server in Mirror. - -### 9. Replace Components - -Every networked prefab and scene object needs to be adjusted. They will be using `NetworkIdentity` from Unet, and you need to replace that component with `NetworkIdentity` from Mirror. You may be using other network components, such as `NetworkAnimator` or `NetworkTransform`. All components from Unet should be replaced with their corresponding component from Mirror. - -Note that if you remove and add a NetworkIdentity, you will need to reassign it in any component that was referencing it. - -### 10. Update Extended Components - -Some commonly extended components, such as NetworkManager, have changed method parameters in Mirror. A commonly used override is OnServerAddPlayer. Using the original HLAPI, your override may have looked like this: - -```cs -public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader) -{ - base.OnServerAddPlayer(conn, playerControllerId, extraMessageReader); - // your code -} -``` - -In your newly Mirror-capable NetworkManager, if you are using the `OnServerAddPlayer` override, remove the "playerControllerId" and "extraMessageReader" parameters from your override and the base call: - -```cs -public override void OnServerAddPlayer(NetworkConnection conn) -{ - base.OnServerAddPlayer(conn); - // your code -} -``` - -See [Custom Player Spawn Guide](../Guides/GameObjects/SpawnPlayerCustom.md) for details on how to submit custom characters now. - -### 11. Pick your transport - -You can choose one of several transports in Mirror. Open your NetworkManager gameobject, in the inspector you will see a `TelepathyTransport` component by default. Drag in one of the available transports and remove `TelepathyTransport` if you wish to use a UDP based transport instead. - -### 12. Configure address and port - -In HLAPI, you configure the port and local address in the NetworkManager. One of our goals is to make Mirror transport independent. Not all transports need address and port. Some transports might even use more than one port at the same time, so these settings were inadequate. We removed the port and address and all other Network Info properties from NetworkManager, and we moved them to the transport components instead. - -### 13. Update your firewall and router - -LLAPI uses UDP. Mirror uses TCP by default. This means you may need to change your router port forwarding and firewall rules in your machine to expose the TCP port instead of UDP. This highly depends on your router and operating system. - -## Video version - -See for yourself how uMMORPG was migrated to Mirror - -[![Manually upgrading uMMORPG V1.130 to V1.131 (Mirror)](MigrationVideo.jpg)](http://www.youtube.com/watch?v=LF9rTSS3rlI) - -## Possible Error Messages -- TypeLoadException: A type load exception has occurred. - happens if you still have SyncListStruct instead of SyncListSTRUCT in your project. -- NullPointerException: The most likely cause is that you replaced NetworkIdentities or other components but you had them assigned somewhere. Reassign those references. -- `error CS0246: The type or namespace name 'UnityWebRequest' could not be found. Are you missing 'UnityEngine.Networking' using directive?` - - Add this to the top of your script: - ```cs - using UnityWebRequest = UnityEngine.Networking.UnityWebRequest; - ``` - - `UnityWebRequest` is not part of UNet or Mirror, but it is in the same namespace as UNet. Changing the namespace to Mirror caused your script not to find UnityWebRequest. The same applies for `WWW` and all `UnityWebRequest` related classes. diff --git a/doc/Articles/General/MigrationVideo.jpg b/doc/Articles/General/MigrationVideo.jpg deleted file mode 100644 index d789ec367..000000000 Binary files a/doc/Articles/General/MigrationVideo.jpg and /dev/null differ diff --git a/doc/Articles/General/NetworkHost.png b/doc/Articles/General/NetworkHost.png deleted file mode 100644 index fbeeaa9d4..000000000 Binary files a/doc/Articles/General/NetworkHost.png and /dev/null differ diff --git a/doc/Articles/General/NetworkLayers.jpg b/doc/Articles/General/NetworkLayers.jpg deleted file mode 100644 index b6f7e049b..000000000 Binary files a/doc/Articles/General/NetworkLayers.jpg and /dev/null differ diff --git a/doc/Articles/General/PlayerControllerToIdentity.md b/doc/Articles/General/PlayerControllerToIdentity.md deleted file mode 100644 index d5b0ac17b..000000000 --- a/doc/Articles/General/PlayerControllerToIdentity.md +++ /dev/null @@ -1,43 +0,0 @@ -# Changing playerController to identity - -If you need to fix up a project after `NetworkConnection.playerController` was changed to `identity` these instructions should be helpful. - -1. Open your Unity project and look for Assets/Mirror/Runtime/**NetworkConnection**: - -![Project window in Unity](pc2i-1.png) - - -2. Open this file in Visual Studio or Visual Code from Unity and look for these lines: - -![Code snip in NetworkConnection.cs](pc2i-2.png) - -The line numbers could be off a bit if minor file changes happen above them after this document was written. - - -3. Comment the last line shown: - -```cs - // public NetworkIdentity identity { get; internal set; } -``` - - -4. Double-click and then right-click `playerController` and select Rename: - -![Start of Rename process](pc2i-3.png) - - -5. Change `playerController` to `identity` and click Apply: - -![Finishing the Rename process](pc2i-4.png) - - -Visual Studio will now have applied the change throughout your project, but you're not done yet! - -Without using the replace feature this time, simply retype the name back to `playerController` and un-comment the last line in the code image that you commented out in step 3. - -Your code should now look like the code image again. - -![Code snip in NetworkConnection.cs](pc2i-2.png) - - -**Save your work!** diff --git a/doc/Articles/General/ScriptTemplates.md b/doc/Articles/General/ScriptTemplates.md deleted file mode 100644 index 88524404a..000000000 --- a/doc/Articles/General/ScriptTemplates.md +++ /dev/null @@ -1,16 +0,0 @@ -# Script Templates - -We've added Script Templates to make it easier to create derived class scripts that inherit from our base classes. - -- All possible overrides are already made for you and organized. -- They're all fully commented as to what they all do. -- Base method calls are all in place where needed so you can see what they already do. -- Each has links at the top to their doc page(s). - -> **Root Folder Required:** ScriptTemplates is a special folder to Unity and must remain in the Assets root...don't move it. - -The **Mirror** section will appear under the **Assets > Create menu**, as well as the context menu that comes up when you right-click on any folder in your project. You'll be prompted for the file name like any other asset creation. - -Hopefully these templates will be helpful to new users of Mirror to learn what methods are available in various classes, as well as just being more convenient for everyone. - -![Script Templates](ScriptTemplates.png) diff --git a/doc/Articles/General/ScriptTemplates.png b/doc/Articles/General/ScriptTemplates.png deleted file mode 100644 index 0c85ad446..000000000 Binary files a/doc/Articles/General/ScriptTemplates.png and /dev/null differ diff --git a/doc/Articles/General/Start.md b/doc/Articles/General/Start.md deleted file mode 100644 index ee2a652f8..000000000 --- a/doc/Articles/General/Start.md +++ /dev/null @@ -1,83 +0,0 @@ -# Getting Started - -This document describes steps to creating a multiplayer game with Mirror. The process described here is a simplified, higher level version of the actual process for a real game; it doesn’t always work exactly like this, but it provides a basic recipe for the process. - -## Video tutorials - -Check out these [awesome videos](https://www.youtube.com/playlist?list=PLkx8oFug638oBYF5EOwsSS-gOVBXj1dkP) showing you how to get started with mirror. Courtesy of [First Gear Games](https://www.youtube.com/channel/UCGIF1XekJqHYIafvE7l0c2A) also known as Punfish in discord. - -## Script Templates -- Create new Network Behaviours and other common scripts faster - -See [Script Templates](ScriptTemplates.md). - -## NetworkManager set-up -- Add a new game object to the Scene and rename it “NetworkManager”. -- Add the NetworkManager component to the “NetworkManager” game object. -- Add the NetworkManagerHUD component to the game object. This provides the default UI for managing the network game state. - -See [Using the NetworkManager](../Components/NetworkManager.md). - -## Player Prefab -- Find the Prefab for the player game object in the game, or create a Prefab from the player game object -- Add the NetworkIdentity component to the player Prefab -- Set the `playerPrefab` in the NetworkManager’s Spawn Info section to the player Prefab -- Remove the player game object instance from the Scene if it exists in the Scene - -See [Player Objects](../Guides/GameObjects/SpawnPlayer.md) for more information. - -## Player movement -- Add a NetworkTransform component to the player Prefab -- Check the Client Authority checkbox on the component. -- Update input and control scripts to respect `isLocalPlayer` -- Override OnStartLocalPlayer to take control of the Main Camera in the scene for the player. - -For example, this script only processes input for the local player: - -``` cs -using UnityEngine; -using Mirror; - -public class Controls : NetworkBehaviour -{ - void Update() - { - if (!isLocalPlayer) - { - // exit from update if this is not the local player - return; - } - - // handle player input for movement - } -} -``` - -## Basic player game state -- Make scripts that contain important data into NetworkBehaviours instead of MonoBehaviours -- Make important member variables into SyncVars - -See [State Synchronization](../Guides/Sync/index.md). - -## Networked actions -- Make scripts that perform important actions into NetworkBehaviours instead of MonoBehaviours -- Update functions that perform important player actions to be commands - -See [Networked Actions](../Guides/Communications/index.md). - -## Non-player game objects - -Fix non-player prefabs such as enemies: -- Add the NetworkIdentity component -- Add the NetworkTransform component -- Register spawnable Prefabs with the NetworkManager -- Update scripts with game state and actions - -## Spawners -- Potentially change spawner scripts to be NetworkBehaviours -- Modify spawners to only run on the server (use isServer property or the `OnStartServer()` function) -- Call `NetworkServer.Spawn()` for created game objects - -## Spawn positions for players -- Add a new game object and place it at player’s start location -- Add the NetworkStartPosition component to the new game object diff --git a/doc/Articles/General/Support.md b/doc/Articles/General/Support.md deleted file mode 100644 index d748405f5..000000000 --- a/doc/Articles/General/Support.md +++ /dev/null @@ -1,8 +0,0 @@ -# Support - -## Discord -- You can find us on [Discord](https://discord.gg/2BvnM4R). - -## GitHub -- You can create an issue in [GitHub](https://github.com/vis2k/Mirror/issues) -- You can also contribute with Pull Requests...see [Contributing](https://github.com/vis2k/Mirror/blob/master/CONTRIBUTING.md) diff --git a/doc/Articles/General/TCPvsUDP.md b/doc/Articles/General/TCPvsUDP.md deleted file mode 100644 index 0855f424c..000000000 --- a/doc/Articles/General/TCPvsUDP.md +++ /dev/null @@ -1,55 +0,0 @@ -# TCP vs UDP - -TCP and UDP are protocol used to send information over the internet. - -Key difference between UDP and TCP -- TCP has higher latency, reliable -- UDP has lower latency, unreliable - - -## [TCP (Transmission Control Protocol)](https://en.wikipedia.org/wiki/Transmission_Control_Protocol) - -TCP is the most popular protocol on the internet. TCP is used for HTTP, SSH, FTP, and many more. - -TCP features make it easy for programers to work with TCP but at the cost of latency. - -TCP is better for slower paced games where latency isn't important. - -#### Key features include - -* **Reliable:** Applications don't have to worry about missing packets. If a packet gets lost, TCP will resend it. All data is either transmitted successfully or you get an error and the connection is closed. -* **Sequenced:** TCP guarantees that every message will arrive in the same order it was sent. If you send "a" then "b" you will receive "a" then "b" on the other side as well. -* **Connection oriented:** TCP has the concept of a connection. A connection will say open until either the client or server decides to close it. Both the client and server get notified when the connection ends. -* **Congestion control:** If a server is being overwhelmed, TCP will throttle the data to avoid congestion collapse. - - -#### Transports - -* [Telepathy](../Transports/Telepathy.md) -* [Apathy](https://mirror-networking.com/apathy/) -* [WebGL](../Transports/SimpleWebTransport.md) - -## [UDP (User Datagram Protocol)](https://en.wikipedia.org/wiki/User_Datagram_Protocol) - -UDP is used for real time applications such as fast paced action games or voice over ip, where low latency is more important than reliability. - -UDP features allow a greater control of how data is sent allowing non-critical data to be send faster. - -UDP is better for fast paced games where latency is important and if a few packets are lost the game can recover. - -#### Key features include - -* **Low Latency:** UDP is faster because it doesn't need to wait for acknowledge packets, instead it can send keep sending new pacakges one after the other. -* **Channel support:** Channels allow for different delivery types. One channel can be used for critical data that needs to get to the destination, while a different channel can just be specified by send and forget without any reliability. -* **Different packet types:** Reliable Ordered, Reliable Unordered, Unreliable, and more depending on the implementation - -#### Transports - -* [Ignorance](../Transports/Ignorance.md) -* [LiteNetLib](../Transports/LiteNetLibTransport.md) - -## The choice is yours - -Mirror is transport independent, they can simply by added to your NetworkManager GameObject. Mirror comes with 2 built in transports to pick from, [Telepathy](../Transports/Telepathy.md) and [Ninja WebSockets](../Transports/SimpleWebTransport.md). See the [transports](../Transports/index.md) page for more about transports. - -Pick whatever works best for you. We recommend you profile your game and collect real world numbers before you make a final decision. diff --git a/doc/Articles/General/index.md b/doc/Articles/General/index.md deleted file mode 100644 index 99cc41d51..000000000 --- a/doc/Articles/General/index.md +++ /dev/null @@ -1,54 +0,0 @@ -# General Overview - -Mirror’s multiplayer High Level API (HLAPI) is a system for building multiplayer capabilities for Unity games. It is built on top of the lower level transport real-time communication layer, and handles many of the common tasks that are required for multiplayer games. While the transport layer supports any kind of network topology, the HLAPI is a server authoritative system; although it allows one of the participants to be a client and the server at the same time, so no dedicated server process is required. Working in conjunction with the internet services, this allows multiplayer games to be played over the internet with little work from developers. - -The HLAPI is focused on ease of use and iterative development and provides useful functionality for multiplayer games, such as: -- Message handlers -- General purpose high performance serialization -- Distributed object management -- State synchronization -- Network classes: Server, Client, Connection, etc - -The HLAPI is built from a series of layers that add functionality: - -![Network Layers](NetworkLayers.jpg) - -## Server and Host - -In Mirror’s High Level API (HLAPI) system, multiplayer games include: -- **Server** - A server is an instance of the game which all other players connect to when they want to play together. A server often manages various aspects of the game, such as keeping score, and transmit that data back to the client. -- **Clients** - Clients are instances of the game that usually connect from different computers to the server. Clients can connect over a local network, or online. - -A client is an instance of the game that connects to the server, so that the person playing it can play the game with other people, who connect on their own clients. - -The server might be either a “dedicated server”, or a “host server”. -- **Dedicated server** - This is an instance of the game that only runs to act as a server. -- **Host server** - When there is no dedicated server, one of the clients also plays the role of the server. This client is the “host server”. The host server creates a single instance of the game (called the host), which acts as both server and client. - -The diagram below represents three players in a multiplayer game. In this game, one client is also acting as host, which means the client itself is the “local client”. The local client connects to the host server, and both run on the same computer. The other two players are remote clients - that is, they are on different computers, connected to the host server. - -![This diagram shows two remote clients connected to a host.](NetworkHost.png) - -The host is a single instance of your game, acting as both server and client at the same time. The host uses a special kind of internal client for local client communication, while other clients are remote clients. The local client communicates with the server through direct function calls and message queues, because it is in the same process. It actually shares the Scene with the server. Remote clients communicate with the server over a regular network connection. When you use Mirror’s HLAPI, this is all handled automatically for you. - -One of the aims of the multiplayer system is for the code for local clients and remote clients to be the same, so that you only have to think about one type of client most of the time when developing your game. In most cases, Mirror handles this difference automatically, so you should rarely need to think about the difference between your code running on a local client or a remote client. - -## Instantiate and Spawn - -When you make a single player game In Unity, you usually use the `GameObject.Instantiate` method to create new game objects at runtime. However, with a multiplayer system, the server itself must “spawn” game objects in order for them to be active within the networked game. When the server spawns game objects, it triggers the creation of game objects on connected clients. The spawning system manages the lifecycle of the game object, and synchronizes the state of the game object based on how you set the game object up. - -For more details about networked instantiating and spawning, see documentation on Spawning [game objects](../Guides/GameObjects/index.md). - -## Players and Local Players - -Mirror’s multiplayer HLAPI system handles player game objects differently to non-player game objects. When a new player joins the game (when a new client connects to the server), that player’s game object becomes a “local player” game object on the client of that player, and Mirror associates the player’s connection with the player’s game object. Mirror associates one player game object for each person playing the game, and routes networking commands to that individual game object. A player cannot invoke a command on another player’s game object, only their own. - -For more details, see documentation on Player [game objects](../Guides/GameObjects/index.md). - -## Authority - -Servers and clients can both manage a game object’s behavior. The concept of “authority” refers to how and where a game object is managed. Mirror’s HLAPI is based around “server authority” as the default state, where the Server has authority over all game objects. Player game objects are a special case and treated as having “local authority”. You may want to build your game using a different system of authority - for more details, see [Network Authority](../Guides/Authority.md). diff --git a/doc/Articles/General/pc2i-1.png b/doc/Articles/General/pc2i-1.png deleted file mode 100644 index 0dddfe574..000000000 Binary files a/doc/Articles/General/pc2i-1.png and /dev/null differ diff --git a/doc/Articles/General/pc2i-2.png b/doc/Articles/General/pc2i-2.png deleted file mode 100644 index c74a001a9..000000000 Binary files a/doc/Articles/General/pc2i-2.png and /dev/null differ diff --git a/doc/Articles/General/pc2i-3.png b/doc/Articles/General/pc2i-3.png deleted file mode 100644 index 746b4a91c..000000000 Binary files a/doc/Articles/General/pc2i-3.png and /dev/null differ diff --git a/doc/Articles/General/pc2i-4.png b/doc/Articles/General/pc2i-4.png deleted file mode 100644 index 863ad7027..000000000 Binary files a/doc/Articles/General/pc2i-4.png and /dev/null differ diff --git a/doc/Articles/General/toc.yml b/doc/Articles/General/toc.yml deleted file mode 100644 index d7da54d27..000000000 --- a/doc/Articles/General/toc.yml +++ /dev/null @@ -1,20 +0,0 @@ -- name: Overview - href: index.md -- name: Getting Started - href: Start.md -- name: Script Templates - href: ScriptTemplates.md -- name: Migration Guide - href: Migration.md -- name: Deprecations - href: Deprecations.md -- name: ChangeLog - href: ChangeLog.md -- name: Showcase - href: https://mirror-networking.com/showcase/ -- name: Integrations - href: Integrations/index.md -- name: TCP vs UDP - href: TCPvsUDP.md -- name: Support - href: Support.md diff --git a/doc/Articles/Guides/Attributes.md b/doc/Articles/Guides/Attributes.md deleted file mode 100644 index 157bafa4b..000000000 --- a/doc/Articles/Guides/Attributes.md +++ /dev/null @@ -1,42 +0,0 @@ -# Attributes Overview - -Networking attributes are added to member functions of NetworkBehaviour scripts, to make them run on either the client or server. - -These attributes can be used for Unity game loop methods like Start or Update, as well as other implemented methods. - -> **NOTE**: when using abstract or virtual methods the Attributes need to be applied to the override methods too. - -- **NetworkSettings** - This attribute has been deprecated because `channels` were moved to transports (where applicable) and `interval` was moved to an inspector property -- **Server** - Only a server can call the method (throws a warning or an error when called on a client). -- **ServerCallback** - Same as **Server** but does not throw warning when called on client. -- **Client** - Only a Client can call the method (throws a warning or an error when called on the server). -- **ClientCallback** - Same as **Client** but does not throw warning when called on server. -- **ClientRpc** - The server uses a Remote Procedure Call (RPC) to run that function on clients. See also: [Remote Actions](Communications/RemoteActions.md) -- **TargetRpc** - This is an attribute that can be put on methods of NetworkBehaviour classes to allow them to be invoked on clients from a server. Unlike the ClientRpc attribute, these functions are invoked on one individual target client, not all of the ready clients. See also: [Remote Actions](Communications/RemoteActions.md) -- **Command** - Call this from a client to run this function on the server. Make sure to validate input etc. It's not possible to call this from a server. Use this as a wrapper around another function, if you want to call it from the server too. See also [Remote Actions​](Communications/RemoteActions.md) - The allowed argument types are: - - - Basic type (byte, int, float, string, UInt64, etc) - - - Built-in Unity math type (Vector3, Quaternion, etc), - - - Arrays of basic types - - - Structs containing allowable types - - - NetworkIdentity - - - Game object with a NetworkIdentity component attached. -- **SyncVar** - [SyncVars](Sync/SyncVars.md) are used to synchronize a variable from the server to all clients automatically. Don't assign them from a client, it's pointless. Don't let them be null, you will get errors. You can use int, long, float, string, Vector3 etc. (all simple types) and NetworkIdentity and game object if the game object has a NetworkIdentity attached to it. You can use [hooks](Sync/SyncVarHook.md). -- **SyncEvent (Obsolete)** - [SyncEvent](Sync/SyncEvent.md) are networked events like ClientRpc's, but instead of calling a function on the game object, they trigger Events instead. - **IMPORTANT:** removed in version 18.0.0, see this [Issue](https://github.com/vis2k/Mirror/pull/2178) for more information. diff --git a/doc/Articles/Guides/Authority.md b/doc/Articles/Guides/Authority.md deleted file mode 100644 index 352036463..000000000 --- a/doc/Articles/Guides/Authority.md +++ /dev/null @@ -1,75 +0,0 @@ -# Network Authority - -Authority is a way of deciding who owns an object and has control over it. - - -## Server Authority - -Server authority means that the server has control of an object. Server has authority over an object by default. This means the server would manage and control of all collectible items, moving platforms, NPCs, and any other networked objects that aren't the player. - -## Client Authority - -Client authority means that the client has control of an object. - -When a client has authority over an object it means that they can call [Commands](Communications/RemoteActions.md) and that the object will automatically be destroyed when the client disconnects. - -Even if a client has authority over an object the server still controls SyncVar and control other serialization features. A component will need to use a [Commands](Communications/RemoteActions.md) to update the state on the server in order for it to sync to other clients. - - -## How to give authority - -By default the server has Authority over all objects. The server can give authority to objects that a client needs to control, like the player object. - -If you spawn a player object using `NetworkServer.AddPlayerForConnection` then it will automatically be given authority. - - -### Using NetworkServer.Spawn - -You can give authority to a client when an object is spawned. This is done by passing in the connection to the spawn message -```cs -GameObject go = Instantiate(prefab); -NetworkServer.Spawn(go, connectionToClient); -``` - -### Using identity.AssignClientAuthority - -You can give authority to a client any time using `AssignClientAuthority`. This can be done by calling `AssignClientAuthority` on the object you want to give authority to. -```cs -identity.AssignClientAuthority(conn); -``` - -You may want to do this when a player picks up an item - -```cs -// Command on player object -void CmdPickupItem(NetworkIdentity item) -{ - item.AssignClientAuthority(connectionToClient); -} -``` - -## How to remove authority - -You can use `identity.RemoveClientAuthority` to remove client authority from an object. - -```cs -identity.RemoveClientAuthority(); -``` - -Authority can't be removed from the player object. Instead you will have to replace the player object using `NetworkServer.ReplacePlayerForConnection`. - - -## On Authority - -When authority is given to or removed from an object a message will be sent to that client to notify them. This will cause the `OnStartAuthority` or `OnStopAuthority` functions to be called. - - -## Check Authority - -### Client Side - -The `identity.hasAuthority` property can be used to check if the local player has authority over an object. - -### Server Side - -The `identity.connectionToClient` property can be check to see which client has authority over an object. If it is null then the server has authority. diff --git a/doc/Articles/Guides/BestPractices.md b/doc/Articles/Guides/BestPractices.md deleted file mode 100644 index 583f6d0b6..000000000 --- a/doc/Articles/Guides/BestPractices.md +++ /dev/null @@ -1,20 +0,0 @@ -# Best Practices - -> work in progress - - -## Custom Messages - -If you send custom message regularly then the message should be a struct so that there is no GC/allocations - -```cs -struct CreateVisualEffect : NetworkMessage -{ - public Vector3 position; - public Guid prefabId; - - // Mirror will automatically implement message that are empty - public void Deserialize(NetworkReader reader) { } - public void Serialize(NetworkWriter writer) { } -} -``` diff --git a/doc/Articles/Guides/ClockSync.md b/doc/Articles/Guides/ClockSync.md deleted file mode 100644 index 13198c186..000000000 --- a/doc/Articles/Guides/ClockSync.md +++ /dev/null @@ -1,47 +0,0 @@ -# Clock Synchronization - -For many algorithms you need the clock to be synchronized between the client and -the server. Mirror does that automatically for you. - -To get the current time use this code: - -```cs -double now = NetworkTime.time; -``` - -It will return the same value in the client and the servers. It starts at 0 when -the server starts. Note the time is a double and should never be casted to a -float. Casting this down to a float means the clock will lose precision after -some time: -- after 1 day, accuracy goes down to 8 ms -- after 10 days, accuracy is 62 ms -- after 30 days , accuracy is 250 ms -- after 60 days, accuracy is 500 ms - -Mirror will also calculate the RTT time as seen by the application: - -```cs -double rtt = NetworkTime.rtt; -``` - -You can measure accuracy. - -```cs -double time_standard_deviation = NetworkTime.timeSd; -``` - -for example, if this returns 0.2, it means the time measurements swing up and -down roughly 0.2 s - -Network hiccups are compensated against by smoothing out the values using EMA. -You can configure how often you want the the ping to be sent: - -```cs -NetworkTime.PingFrequency = 2.0f; -``` - -You can also configure how many ping results are used in the calculation: - -```cs -NetworkTime.PingWindowSize = 10; -``` diff --git a/doc/Articles/Guides/Communications/NetworkBehaviourCallbacks.md b/doc/Articles/Guides/Communications/NetworkBehaviourCallbacks.md deleted file mode 100644 index 972dc67b1..000000000 --- a/doc/Articles/Guides/Communications/NetworkBehaviourCallbacks.md +++ /dev/null @@ -1,68 +0,0 @@ -# NetworkBehaviour Callbacks - -**See also in the API Reference.** - -There are a number of events relating to network behaviours that can occur over the course of a normal multiplayer game. These include events such as the host starting up, a player joining, or a player leaving. Each of these possible events has an associated callback that you can implement in your own code to take action when the event occurs. - -When you create a script which inherits from `NetworkBehaviour`, you can write your own implementation of what should happen when these events occur. To do this, you override the virtual methods on the `NetworkBehaviour` class with your own implementation of what should happen when the given event occurs. - -This is a full list of virtual methods (callbacks) that you can implement on `NetworkBehaviour`, and where they are called - -## Server Only - -- OnStartServer - - called when behaviour is spawned on server -- OnStopServer - - called when behaviour is destroyed or unspawned on server -- OnSerialize - - called when behaviour is serialize before it is sent to client, when overriding make sure to call `base.OnSerialize` - -## Client only - -- OnStartClient - - called when behaviour is spawned on client -- OnStartAuthority - - called when behaviour has authority when it is spawned (eg local player) - - called when behaviour is given authority by the sever -- OnStartLocalPlayer - - called when the behaviour is on the local player object - -- OnStopAuthority - - called when authority is taken from the object (eg local player is replaced but not destroyed) -- OnStopClient - - called when object is destroyed on client by the `ObjectDestroyMessage` or `ObjectHideMessage` messages - - -# Example flows - -Below is some example call order for different modes - -> NOTE: `Start` is called by unity before the first frame, while normally this happens after Mirror's callbacks. But if you dont call ` NetworkServer.Spawn` the same frame as `instantiate` then start may be called first - -> Note: `OnRebuildObservers` and `OnSetHostVisibility` is now on `NetworkVisibility` instead of `NetworkBehaviour` - -## Server mode - -When a NetworkServer.Spawn is called (eg when new client connections and a player is created) -- `OnStartServer` -- `OnRebuildObservers` -- `Start` - -## Client mode - -When local player is spawned for client -- `OnStartAuthority` -- `OnStartClient` -- `OnStartLocalPlayer` -- `Start` - -## Host mode - -These are only called on the **Player Game Objects** when a client connects: -- `OnStartServer` -- `OnRebuildObservers` -- `OnStartAuthority` -- `OnStartClient` -- `OnSetHostVisibility` -- `OnStartLocalPlayer` -- `Start` diff --git a/doc/Articles/Guides/Communications/NetworkManager.md b/doc/Articles/Guides/Communications/NetworkManager.md deleted file mode 100644 index a5a6a1163..000000000 --- a/doc/Articles/Guides/Communications/NetworkManager.md +++ /dev/null @@ -1,68 +0,0 @@ -# Network Manager Callbacks - -**See also in the API Reference.** - -There are a number of events that can occur over the course of the normal operation of a multiplayer game, such as the host starting up, a player joining, or a player leaving. Each of these possible events has an associated callback that you can implement in your own code to take action when the event occurs. - -To do this for the `NetworkManager`, you need to create your own script which inherits from `NetworkManager`. You can then override the virtual methods on `NetworkManager` with your own implementation of what should happen when the given event occurs. - -This page lists all the virtual methods (the callbacks) that you can implement on the `NetworkManager`, and when they occur. The callbacks that occur, and the order they occur, vary slightly depending on which mode your game is running in, so each mode’s callbacks are listed separately below. - -A game can be running in one of three modes, host, client, or server-only. The callbacks for each mode are listed below: - -## Host Mode: - -When the host is started: -- `OnStartServer` -- `OnStartHost` -- `OnServerConnect` -- `OnStartClient` -- `OnClientConnect` -- `OnServerSceneChanged` -- `OnServerReady` -- `OnServerAddPlayer` -- `OnClientChangeScene` -- `OnClientSceneChanged` - -When a client connects: -- `OnServerConnect` -- `OnServerReady` -- `OnServerAddPlayer` - -When a client disconnects: -- `OnServerDisconnect` - -When the host is stopped: -- `OnStopHost` -- `OnServerDisconnect` -- `OnStopClient` -- `OnStopServer` - -## Client Mode - -When the client starts: -- `OnStartClient` -- `OnClientConnect` -- `OnClientChangeScene` -- `OnClientSceneChanged` - -When the client stops: -- `OnStopClient` -- `OnClientDisconnect` - -## Server Mode - -When the server starts: -- `OnStartServer` -- `OnServerSceneChanged` - -When a client connects: -- `OnServerConnect` -- `OnServerReady` -- `OnServerAddPlayer` - -When a client disconnects: -- `OnServerDisconnect` - -When the server stops: -- `OnStopServer` diff --git a/doc/Articles/Guides/Communications/NetworkMessages.md b/doc/Articles/Guides/Communications/NetworkMessages.md deleted file mode 100644 index 4a3dfdd3a..000000000 --- a/doc/Articles/Guides/Communications/NetworkMessages.md +++ /dev/null @@ -1,56 +0,0 @@ -# Network Messages - -For the most part we recommend the high level [Commands and RPC](RemoteActions.md) calls and [SyncVar](../Sync/index.md), but you can also send low level network messages. -This can be useful if you want clients to send messages that are not tied to game objects, such as logging, analytics or profiling information. - -There is a public interface called NetworkMessage that you can extend to make serializable network message structs. -This interface has Serialize and Deserialize functions that take writer and reader objects. -You can implement these functions yourself, but we recommend you let Mirror generate them for you. - -The auto generated Serialize/Deserialize can efficiently deal any [supported mirror type](../DataTypes.md). Make your members public. -If you need classes or complex containers such as List and Dictionary, you must implement the Serialize and Deserialize methods yourself. - -To send a message, use the `Send()` method on the NetworkClient, NetworkServer, and NetworkConnection classes, which all work the same way -using a message struct that is derived from NetworkMessage. The code below demonstrates how to send and handle a message: - -To declare a custom network message class and use it: - -``` cs -using UnityEngine; -using Mirror; - -public class Scores : MonoBehaviour -{ - public struct ScoreMessage : NetworkMessage - { - public int score; - public Vector3 scorePos; - public int lives; - } - - public void SendScore(int score, Vector3 scorePos, int lives) - { - ScoreMessage msg = new ScoreMessage() - { - score = score, - scorePos = scorePos, - lives = lives - }; - - NetworkServer.SendToAll(msg); - } - - public void SetupClient() - { - NetworkClient.RegisterHandler(OnScore); - NetworkClient.Connect("localhost"); - } - - public void OnScore(NetworkConnection conn, ScoreMessage msg) - { - Debug.Log("OnScoreMessage " + msg.score); - } -} -``` - -Note that there is no serialization code for the `ScoreMessage` class in this source code example. The body of the serialization functions is automatically generated for this class by Mirror. diff --git a/doc/Articles/Guides/Communications/RemoteActions.md b/doc/Articles/Guides/Communications/RemoteActions.md deleted file mode 100644 index 18fbc37d3..000000000 --- a/doc/Articles/Guides/Communications/RemoteActions.md +++ /dev/null @@ -1,163 +0,0 @@ -# Remote Actions - -The network system has ways to perform actions across the network. These type of actions are sometimes called Remote Procedure Calls. There are two types of RPCs in the network system, Commands - which are called from the client and run on the server; and ClientRpc calls - which are called on the server and run on clients. - -The diagram below shows the directions that remote actions take: - -![Data Flow Graph](UNetDirections.jpg) - -## Commands - -Commands are sent from player objects on the client to player objects on the server. For security, Commands can only be sent from YOUR player object by default, so you cannot control the objects of other players. You can bypass the authority check using `[Command(ignoreAuthority = true)]`. - -To make a function into a command, add the [Command] custom attribute to it, and add the “Cmd” prefix. This function will now be run on the server when it is called on the client. Any parameters of [allowed data type](../DataTypes.md) will be automatically passed to the server with the command. - -Commands functions must have the prefix “Cmd” and cannot be static. This is a hint when reading code that calls the command - this function is special and is not invoked locally like a normal function. - -``` cs -public class Player : NetworkBehaviour -{ - // assigned in inspector - public GameObject cubePrefab; - - void Update() - { - if (!isLocalPlayer) return; - - if (Input.GetKey(KeyCode.X)) - CmdDropCube(); - } - - [Command] - void CmdDropCube() - { - if (cubePrefab != null) - { - Vector3 spawnPos = transform.position + transform.forward * 2; - Quaternion spawnRot = transform.rotation; - GameObject cube = Instantiate(cubePrefab, spawnPos, spawnRot); - NetworkServer.Spawn(cube); - } - } -} -``` - -Be careful of sending commands from the client every frame! This can cause a lot of network traffic. - -### Commands and Authority - -It is possible to invoke commands on non-player objects if any of the following are true: - -- The object was spawned with client authority -- The object has client authority set with `NetworkIdentity.AssignClientAuthority` -- the Command has the `ignoreAuthority` option set true. - - You can include an optional `NetworkConnectionToClient sender = null` parameter in the Command method signature and Mirror will fill in the sending client for you. - - Do not try to set a value for this optional parameter...it will be ignored. - -Commands sent from these object are run on the server instance of the object, not on the associated player object for the client. - -```cs -public enum DoorState : byte -{ - Open, Closed -} - -public class Door : NetworkBehaviour -{ - [SyncVar] - public DoorState doorState; - - [Command(ignoreAuthority = true)] - public void CmdSetDoorState(DoorState newDoorState, NetworkConnectionToClient sender = null) - { - if (sender.identity.GetComponent().hasDoorKey) - doorState = newDoorState; - } -} -``` - -## ClientRpc Calls - -ClientRpc calls are sent from objects on the server to objects on clients. They can be sent from any server object with a NetworkIdentity that has been spawned. Since the server has authority, then there no security issues with server objects being able to send these calls. To make a function into a ClientRpc call, add the [ClientRpc] custom attribute to it, and add the “Rpc” prefix. This function will now be run on clients when it is called on the server. Any parameters of [allowed data type](../DataTypes.md) will automatically be passed to the clients with the ClientRpc call.. - -ClientRpc functions must have the prefix “Rpc” and cannot be static. This is a hint when reading code that calls the method - this function is special and is not invoked locally like a normal function. - -ClientRpc messages are only sent to observers of an object according to its [Network Visibility](../Visibility.md). Player objects are always obeservers of themselves. In some cases, you may want to exclude the owner client when calling a ClientRpc. This is done with the `excludeOwner` option: `[ClientRpc(excludeOwner = true)]`. - -``` cs -public class Player : NetworkBehaviour -{ - int health; - - public void TakeDamage(int amount) - { - if (!isServer) return; - - health -= amount; - RpcDamage(amount); - } - - [ClientRpc] - public void RpcDamage(int amount) - { - Debug.Log("Took damage:" + amount); - } -} -``` - -When running a game as a host with a local client, ClientRpc calls will be invoked on the local client even though it is in the same process as the server. So the behaviours of local and remote clients are the same for ClientRpc calls. - -## TargetRpc Calls - -TargetRpc functions are called by user code on the server, and then invoked on the corresponding client object on the client of the specified NetworkConnection. The arguments to the RPC call are serialized across the network, so that the client function is invoked with the same values as the function on the server. These functions must begin with the prefix "Target" and cannot be static. - -**Context Matters:** - -- If the first parameter of your TargetRpc method is a `NetworkConnection` then that's the connection that will receive the message regardless of context. -- If the first parameter is any other type, then the owner client of the object with the script containing your TargetRpc will receive the message. - -This example shows how a client can use a Command to make a request to the server (`CmdMagic`) by including another Player's `connectionToClient` as one of the parameters of the TargetRpc invoked directly from that Command: - -``` cs -public class Player : NetworkBehaviour -{ - public int health; - - [Command] - void CmdMagic(GameObject target, int damage) - { - target.GetComponent().health -= damage; - - NetworkIdentity opponentIdentity = target.GetComponent(); - TargetDoMagic(opponentIdentity.connectionToClient, damage); - } - - [TargetRpc] - public void TargetDoMagic(NetworkConnection target, int damage) - { - // This will appear on the opponent's client, not the attacking player's - Debug.Log($"Magic Damage = {damage}"); - } - - // Heal thyself - [Command] - public void CmdHealMe() - { - health += 10; - TargetHealed(10); - } - - [TargetRpc] - public void TargetHealed(int amount) - { - // No NetworkConnection parameter, so it goes to owner - Debug.Log($"Health increased by {amount}"); - } -} -``` - -## Arguments to Remote Actions - -The arguments passed to commands and ClientRpc calls are serialized and sent over the network. You can use any [supported mirror type](../DataTypes.md). - -Arguments to remote actions cannot be sub-components of game objects, such as script instances or Transforms. diff --git a/doc/Articles/Guides/Communications/UNetDirections.jpg b/doc/Articles/Guides/Communications/UNetDirections.jpg deleted file mode 100644 index 9f8889701..000000000 Binary files a/doc/Articles/Guides/Communications/UNetDirections.jpg and /dev/null differ diff --git a/doc/Articles/Guides/Communications/index.md b/doc/Articles/Guides/Communications/index.md deleted file mode 100644 index 24e1b2b41..000000000 --- a/doc/Articles/Guides/Communications/index.md +++ /dev/null @@ -1,19 +0,0 @@ -# Actions and Communication - -When you are making a multiplayer game, In addition to synchronizing the properties of networked game objects, you are likely to need to send, receive, and react to other pieces of information - such as when the match starts, when a player joins or leaves the match, or other information specific to your type of game, for example a notification to all players that a flag has been captured in a “capture-the-flag” style game. - -Within the Mirror networking High-Level API there are three main ways to communicate this type of information. - -## Remote Actions - -Remote actions allow you to call a method in your script across the network. You can make the server call methods on all clients or individual clients specifically. You can also make clients call methods on the server. Using remote actions, you can pass data as parameters to your methods in a very similar way to how you call methods in local (non-multiplayer) projects. - -## Networking Callbacks - -Networking callbacks allow you to hook into built-in Mirror events which occur during the course of the game, such as when players join or leave, when game objects are created or destroyed, or when a new Scene is loaded. There are two types of networking callbacks that you can implement: -- Network manager callbacks, for callbacks relating to the network manager itself (such as when clients connect or disconnect) -- Network behaviour callbacks, for callbacks relating to individual networked game objects (such as when its Start function is called, or what this particular game object should do if a new player joins the game) - -## Network Messages - -Network messages are a “lower level” approach to sending messages (although they are still classed as part of the networking “High level API”). They allow you to send data directly between clients and the server using scripting. You can send basic types of data (int, string, etc) as well as most common Unity types (such as Vector3). Since you implement this yourself, these messages are not associated directly with any particular game objects or Unity events - it is up to you do decide their purpose and implement them! diff --git a/doc/Articles/Guides/Communications/toc.yml b/doc/Articles/Guides/Communications/toc.yml deleted file mode 100644 index 760419586..000000000 --- a/doc/Articles/Guides/Communications/toc.yml +++ /dev/null @@ -1,10 +0,0 @@ -- name: Overview - href: index.md -- name: Remote Actions - href: RemoteActions.md -- name: Network Manager Callbacks - href: NetworkManager.md -- name: Network Behaviour Callbacks - href: NetworkBehaviourCallbacks.md -- name: Network Messages - href: NetworkMessages.md \ No newline at end of file diff --git a/doc/Articles/Guides/DataTypes.md b/doc/Articles/Guides/DataTypes.md deleted file mode 100644 index e13d707f3..000000000 --- a/doc/Articles/Guides/DataTypes.md +++ /dev/null @@ -1,221 +0,0 @@ -# Data types - -The client and server can pass data to each other via [Remote methods](Communications/RemoteActions.md), [State Synchronization](Sync/index.md) or via [Network Messages](Communications/NetworkMessages.md) - -Mirror supports a number of data types you can use with these, including: -- Basic c# types (byte, int, char, uint, UInt64, float, string, etc) -- Built-in Unity math type (Vector3, Quaternion, Rect, Plane, Vector3Int, etc) -- URI -- NetworkIdentity -- Game object with a NetworkIdentity component attached - - See important details in [Game Objects](#game-objects) section below. -- Structures with any of the above - - It's recommended to implement IEquatable\ to avoid boxing, and to have the struct readonly because modifying one of fields doesn't cause a resync -- Classes as long as each field has a supported data type - - These will allocate garbage and will be instantiated new on the receiver every time they're sent. -- ScriptableObject as long as each field has a supported data type - - These will allocate garbage and will be instantiated new on the receiver every time they're sent. -- Arrays of any of the above - - Not supported with SyncVars or SyncLists -- ArraySegments of any of the above - - Not supported with SyncVars or SyncLists - -## Game Objects - -Game Objects in SyncVars, SyncLists, and SyncDictionaries are fragile in some cases, and should be used with caution. - -- As long as the game object *already exists* on both the server and the client, the reference should be fine. - -When the sync data arrives at the client, the referenced game object may not yet exist on that client, resulting in null values in the sync data. This is because interally Mirror passes the `netId` from the `NetworkIdentity` and tries to look it up on the client's `NetworkIdentity.spawned` dictionary. - -If the object hasn't been spawned on the client yet, no match will be found. It could be in the same payload, especially for joining clients, but after the sync data from another object. -It could also be null because the game object is excluded from a client due to network visibility, e.g. `NetworkProximityChecker`. - -You may find that it's more robust to sync the `NetworkIdentity.netID` (uint) instead, and do your own lookup in `NetworkIdentity.spawned` to get the object, perhaps in a coroutine: - -```cs - public GameObject target; - - [SyncVar(hook = nameof(OnTargetChanged))] - public uint targetID; - - void OnTargetChanged(uint _, uint newValue) - { - if (NetworkIdentity.spawned.TryGetValue(targetID, out NetworkIdentity identity)) - target = identity.gameObject; - else - StartCoroutine(SetTarget()); - } - - IEnumerator SetTarget() - { - while (target == null) - { - yield return null; - if (NetworkIdentity.spawned.TryGetValue(targetID, out NetworkIdentity identity)) - target = identity.gameObject; - } - } -``` - -## Custom Data Types - -Sometimes you don't want mirror to generate serialization for your own types. For example, instead of serializing quest data, you may want to serialize just the quest id, and the receiver can look up the quest by id in a predefined list. - -Sometimes you may want to serialize data which uses a different type not supported by Mirror, such as DateTime or System.Uri - -You can add support for any type by adding extension methods to `NetworkWriter` and `NetworkReader`. For example, to add support for `DateTime`, add this somewhere in your project: - -```cs -public static class DateTimeReaderWriter -{ - public static void WriteDateTime(this NetworkWriter writer, DateTime dateTime) - { - writer.WriteInt64(dateTime.Ticks); - } - - public static DateTime ReadDateTime(this NetworkReader reader) - { - return new DateTime(reader.ReadInt64()); - } -} -``` - -...then you can use `DateTime` in your `[Command]` or `SyncList` - -## Inheritance and Polymorphism - -Sometimes you might want to send a polymorphic data type to your commands. Mirror does not serialize the type name to keep messages small and for security reasons, therefore Mirror cannot figure out the type of object it received by looking at the message. - -> **This code does not work out of the box.** - -```cs -class Item -{ - public string name; -} - -class Weapon : Item -{ - public int hitPoints; -} - -class Armor : Item -{ - public int hitPoints; - public int level; -} - -class Player : NetworkBehaviour -{ - [Command] - void CmdEquip(Item item) - { - // IMPORTANT: this does not work. Mirror will pass you an object of type item - // even if you pass a weapon or an armor. - if (item is Weapon weapon) - { - // The item is a weapon, - // maybe you need to equip it in the hand - } - else if (item is Armor armor) - { - // you might want to equip armor in the body - } - } - - [Command] - void CmdEquipArmor(Armor armor) - { - // IMPORTANT: this does not work either, you will receive an armor, but - // the armor will not have a valid Item.name, even if you passed an armor with name - } -} -``` - -CmdEquip will work if you provide a custom serializer for the `Item` type. For example: - -```cs - -public static class ItemSerializer -{ - const byte WEAPON = 1; - const byte ARMOR = 2; - - public static void WriteItem(this NetworkWriter writer, Item item) - { - if (item is Weapon weapon) - { - writer.WriteByte(WEAPON); - writer.WriteString(weapon.name); - writer.WriteInt32(weapon.hitPoints); - } - else if (item is Armor armor) - { - writer.WriteByte(ARMOR); - writer.WriteString(armor.name); - writer.WriteInt32(armor.hitPoints); - writer.WriteInt32(armor.level); - } - } - - public static Item ReadItem(this NetworkReader reader) - { - byte type = reader.ReadByte(); - switch(type) - { - case WEAPON: - return new Weapon - { - name = reader.ReadString(), - hitPoints = reader.ReadInt32() - }; - case ARMOR: - return new Armor - { - name = reader.ReadString(), - hitPoints = reader.ReadInt32(), - level = reader.ReadInt32() - }; - default: - throw new Exception($"Invalid weapon type {type}"); - } - } -} -``` - -## Scriptable Objects - -People often want to send scriptable objects from the client or server. For example, you may have a bunch of swords created as scriptable objects and you want put the equipped sword in a syncvar. This will work fine, Mirror will generate a reader and writer for scriptable objects by calling ScriptableObject.CreateInstance and copy all the data. - -However the generated reader and writer are not suitable for every occasion. Scriptable objects often reference other assets such as textures, prefabs, or other types that can't be serialized. Scriptable objects are often saved in the in the Resources folder. Scriptable objects sometimes have a large amount of data in them. The generated reader and writers may not work or may be inneficient for these situations. - -Instead of passing the scriptable object data, you can pass the name and the other side can lookup the same object by name. This way you can have any kind of data in your scriptable object. You can do that by providing a custom reader and writer. Here is an example: - -```cs -[CreateAssetMenu(fileName = "New Armor", menuName = "Armor Data")] -class Armor : ScriptableObject -{ - public int Hitpoints; - public int Weight; - public string Description; - public Texture2D Icon; - // ... -} - -public static class ArmorSerializer -{ - public static void WriteArmor(this NetworkWriter writer, Armor armor) - { - // no need to serialize the data, just the name of the armor - writer.WriteString(armor.name); - } - - public static Armor ReadArmor(this NetworkReader reader) - { - // load the same armor by name. The data will come from the asset in Resources folder - return Resources.Load(reader.ReadString()); - } -} -``` - diff --git a/doc/Articles/Guides/DevServer/AWS/AWS Setup.png b/doc/Articles/Guides/DevServer/AWS/AWS Setup.png deleted file mode 100644 index ab17c3d92..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/AWS Setup.png and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Configure RDP for Data.PNG b/doc/Articles/Guides/DevServer/AWS/Configure RDP for Data.PNG deleted file mode 100644 index 5f768c0cf..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Configure RDP for Data.PNG and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Connect to your instance 1.png b/doc/Articles/Guides/DevServer/AWS/Connect to your instance 1.png deleted file mode 100644 index 11b8bd83b..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Connect to your instance 1.png and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Connect to your instance 2.png b/doc/Articles/Guides/DevServer/AWS/Connect to your instance 2.png deleted file mode 100644 index c2e8de055..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Connect to your instance 2.png and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Connect to your instance 3.png b/doc/Articles/Guides/DevServer/AWS/Connect to your instance 3.png deleted file mode 100644 index 856158922..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Connect to your instance 3.png and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/KeyPair.PNG b/doc/Articles/Guides/DevServer/AWS/KeyPair.PNG deleted file mode 100644 index 49561c60b..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/KeyPair.PNG and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Microsoft Server 2019.PNG b/doc/Articles/Guides/DevServer/AWS/Microsoft Server 2019.PNG deleted file mode 100644 index f8c1db610..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Microsoft Server 2019.PNG and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Retrieve Default Windows Administrator Password 2.PNG b/doc/Articles/Guides/DevServer/AWS/Retrieve Default Windows Administrator Password 2.PNG deleted file mode 100644 index 33c99bd67..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Retrieve Default Windows Administrator Password 2.PNG and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Retrieve Default Windows Administrator Password.PNG b/doc/Articles/Guides/DevServer/AWS/Retrieve Default Windows Administrator Password.PNG deleted file mode 100644 index 11f6cd1c2..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Retrieve Default Windows Administrator Password.PNG and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Review.png b/doc/Articles/Guides/DevServer/AWS/Review.png deleted file mode 100644 index 694572a49..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Review.png and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Running instances.png b/doc/Articles/Guides/DevServer/AWS/Running instances.png deleted file mode 100644 index 1d6c824ad..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Running instances.png and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Step 2.png b/doc/Articles/Guides/DevServer/AWS/Step 2.png deleted file mode 100644 index 870623b03..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Step 2.png and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Step 6.png b/doc/Articles/Guides/DevServer/AWS/Step 6.png deleted file mode 100644 index 62b86b159..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Step 6.png and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Windows Firewall Exception.PNG b/doc/Articles/Guides/DevServer/AWS/Windows Firewall Exception.PNG deleted file mode 100644 index 84e4049e2..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Windows Firewall Exception.PNG and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/Your Drive on the dedicated host.PNG b/doc/Articles/Guides/DevServer/AWS/Your Drive on the dedicated host.PNG deleted file mode 100644 index b0e5aea45..000000000 Binary files a/doc/Articles/Guides/DevServer/AWS/Your Drive on the dedicated host.PNG and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/AWS/index.md b/doc/Articles/Guides/DevServer/AWS/index.md deleted file mode 100644 index e2751dcae..000000000 --- a/doc/Articles/Guides/DevServer/AWS/index.md +++ /dev/null @@ -1,189 +0,0 @@ -# Amazon Web Services (AWS) - -During this section we will focus on using a Windows instance and connecting from a Windows computer. - -> **NOTE**: AWS requires a payment method/credit card added before being able to use a Windows server. - -Don't forget to read up on the [free tier limitations](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html). -During this example we will be using the free tier of the EC2 option, which gives us the possibility to use a Windows instance (if you have already added a payment method). -For more information about which services offer a Free Tier, see [AWS Free Tier](https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc&awsf.Free%20Tier%20Types=tier%2312monthsfree&awsf.Free%20Tier%20Categories=categories%23compute). - -These are the steps we will go through from start to finish: - -1. Account creation -2. Setting up an instance with the EC2 Management Console -3. Configuring the server via RDP (Remote Desktop) -4. Setting up the firewall to allow connections through -5. Testing the connection - -## 1. Account Creation - -Go to the [Account creation page](https://portal.aws.amazon.com/billing/signup?nc2=h_ct&src=default&redirect_url=https%3A%2F%2Faws.amazon.com%2Fregistration-confirmation#/start) and -sign up with your details and payment method (e.g. credit card). Adding the payment method is necessary to run a windows instance on AWS. - -## 2. Setting up an instance with the EC2 Management Console -After setting up your account you should be logged in. -Always make sure you're in your correct region so it's a good habit to check in the top right corner. Change it to the closest location to you now. -After this click on Services in the top left corner and click on EC2. This will bring you to the EC2 instance dashboard and ready to Launch your instance! - -Click on **"Launch Instance"**. -![EC2-Management-Dashboard](AWS%20Setup.png) - -There are 7 steps to creating your AWS Instance: - -1. Choose an Amazon Machine Image (AMI) -2. Choose Instance Type -3. Configure Instance -4. Add Storage -5. Add Tags -6. Configure Security Group -7. Review - -#### Step 1: Choose an Amazon Machine Image - -Scroll down until you see the Microsoft Windows Server 2019 Base (take the newest one if this is outdated). -Make sure that the option you select has the "Free Tier Eligible" under the icon and click on "Select". -![Amazon Machine Image: Microsoft Server 2019](Microsoft%20Server%202019.PNG) - -#### Step 2: Choose Instance Type - -Make sure you choose the instance type with the "free tier eligible", at the time of writing this is the t2.micro instance. -Click on **"Next: Configure Instance Details"**. **Do not** click on Review and Launch. - -![Choose Instance Type](Step%202.png) - -#### Step 3: Configure Instance - -Nothing has to be changed at this step. Keep it default. Click on **"Next: Add Storage"**. - -#### Step 4: Add Storage - -Nothing has to be changed. Keep it default. The 30GB is more than you need but there will be an error if you choose a lower amount. -Keep in mind that you can always click "Previous" if you need to return, you do not need to repeat the entire process if you make a mistake (unless you click Launch at the end). - -Click on **"Next: Add Tags"** to continue. - -#### Step 5: Add Tags - -Nothing has to be changed. Keep it default. Click on **"Next: Configure Security Groups"** - -#### Step 6: Configure Security Groups - -> **IMPORTANT STEP** This makes it possible to connect to your instance from outside for: - -- RDP (needed for this example) -- For clients connecting through port 7777 for your Mirror Project. -- SSH (if needed) - -Create a new security group and you can give it your own name and description. Add the following rules: - -- RDP with source "Anywhere", Description can be whatever but put it as Remote Desktop Program. -- Custom TCP Rule with port 7777 and source "Anywhere", Description can be whatever but put it as Mirror. - - If you're using the default Kcp Transport in your Network Manager instead of the Telepathy Transport, create the above rule as a Custom UDP rule instead. -- SSH with source "Anywhere", Description can be whatever but put it as SSH. - -SSH is not strictly necessary but can be used to remote connect to it through other means than the RDP. - -You can ignore the warning about the source as this is just a testing environment. In the future you might wish to restrict this but you will almost never know the clients' connection IP's beforehand. - -Click on **"Next: Review and Launch"** - -![Configuring Security Groups](Step%206.png) - -#### Step 7: Review - -Almost there! Make sure everything is correct and you are using the free tier, then click on **"Launch"**. - -![Review Of The Instance](Review.png) - -One more thing: A window will pop up asking for your key pair. Just create a new one by selecting the dropdown: **"Create a new key pair"** and give it a name, click on **"Download Key Pair"**. - -Keep the key file (.PEM File) somewhere secure (To be 100% certain, back it up somewhere). - -> **YOU CANNOT ACCESS THE CREATED INSTANCE WITHOUT THIS KEY** - -![Key Pair](KeyPair.PNG) - -Now you can (finally) click on **"Launch Instances"**! - -Go back to your EC2 dashboard by clicking on "Services" at the top left and clicking on EC2. -Now you see you have "Running Instances: 1". **Click on "Running Instances" to continue**. - -![Your Running Instances](Running%20instances.png) - -> A new instance might take around 5-10 minutes to set up. Refresh the page after 10 minutes if nothing changes. - -Now you did all this but you want to get ON the dedicated server right? Perfect! The next step will get you up and running! - -## 3. Configuring the server via RDP (Remote Desktop) - -Time to get the RDP file so you can start connecting. There are a few things we'll need: - -1. RDP file with the key pair added to it -2. Configure RDP file once downloaded to allow getting files from our C: drive or other drives (so you can easily get your zip project) -3. Enter the windows Admin password once you start the RDP file - -Once you've done this, you should be able to continue using the same RDP file. - -#### RDP file with the key pair added to it - -> Get the password **before** clicking Download - -![Connect To Your Instance 1](Connect%20to%20your%20instance%201.png) - -> **Copy the Password for later** - -![Connect To Your Instance 2](Connect%20to%20your%20instance%202.png) - -Now click on **"Download Remote Desktop File"**. The RDP file will be downloaded. - -![Connect To Your Instance 3](Connect%20to%20your%20instance%203.png) - -#### Configure RDP file for easy file access - -Go to your freshly downloaded RDP file and rightclick it and then click "Edit". - -Go to the third tab "Local sources", at the bottom click "more" under local devices and sources. -On the new window select your C: drive or any other drive. This is your own computer your connecting from. For easy file exchange. - -![Configuring the RDP file](Configure%20RDP%20for%20Data.PNG) - -Perfect! Now you can run the RDP file! The RDP file will ask a password. If you forgot your password you can get it back by rightclicking -the instance and clicking on "Get Windows Password". You will be asked to re-enter your key pair (.PEM) file and decrypt the message. -Once done you will be able to copy the password. - -![Retrieve Your Default Windows Administrator Password](Retrieve%20Default%20Windows%20Administrator%20Password.PNG) - -![Retrieve Your Default Windows Administrator Password 2](Retrieve%20Default%20Windows%20Administrator%20Password%202.PNG) - -There you have it! Now you have your password and Remote Desktop should show you logging into your dedicated server! - -#### Setting up the firewall to allow connections through - -Go to the windows firewall settings, go to the advanced firewall settings and go to inbound rules. **Add a new rule** and choose the port type. -Select TCP and enter the 7777 port (or any other if you use another port in Mirror). Continue clicking next and keep things default. -Close all the windows when done. - -![Windows Firewall Exception](Windows%20Firewall%20Exception.PNG) - -AWESOME! You now have everything set up to accept incoming requests on **port 7777**. - -## 4. Testing the connection - -Before you can (finally) test out your server build of your project you need to get it on the dedicated server! - -Place your (zipped) server build at the root of your added drive (C: or another) to make it easier to find it fast. - -Go to **"My Computer"** and because of our previous changes to the RDP we should now see your local drive under "Devices and Drives". -Double click it and because you placed your zipped server build on that drive, you should see it immediatly when it's done loading. - -![Your Drive on the dedicated host](Your%20Drive%20on%20the%20dedicated%20host.PNG) - -Now unzip the project in a new folder on the dedicated server's desktop and run it. - -Want to test if it sees the 7777 port is open after you started your Mirror server? -Get your IPv4 public IP from the EC2 Management Console from your instance and use it on your client to connect to that IP. - -Go to [PortChecker](https://www.portcheckers.com/) and enter the Dedicated Server IP address and enter port 7777. - -> NOTE: If you are not running your game / project then the port will be closed. It's only open when the server is running. diff --git a/doc/Articles/Guides/DevServer/gcloud/01-vm-instances.jpg b/doc/Articles/Guides/DevServer/gcloud/01-vm-instances.jpg deleted file mode 100644 index e693137a8..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/01-vm-instances.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/02-create-instance-name-region.jpg b/doc/Articles/Guides/DevServer/gcloud/02-create-instance-name-region.jpg deleted file mode 100644 index e86b20f38..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/02-create-instance-name-region.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/03-boot-disk.jpg b/doc/Articles/Guides/DevServer/gcloud/03-boot-disk.jpg deleted file mode 100644 index 73b84bca8..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/03-boot-disk.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/04-expand-network-settings.jpg b/doc/Articles/Guides/DevServer/gcloud/04-expand-network-settings.jpg deleted file mode 100644 index c9f1c893b..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/04-expand-network-settings.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/05-network-tag.jpg b/doc/Articles/Guides/DevServer/gcloud/05-network-tag.jpg deleted file mode 100644 index 7bd8caa02..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/05-network-tag.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/06-ip-address.jpg b/doc/Articles/Guides/DevServer/gcloud/06-ip-address.jpg deleted file mode 100644 index b9738ea8a..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/06-ip-address.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/07-create-network-rule.jpg b/doc/Articles/Guides/DevServer/gcloud/07-create-network-rule.jpg deleted file mode 100644 index bc0804b29..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/07-create-network-rule.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/08-connect-to-instance.jpg b/doc/Articles/Guides/DevServer/gcloud/08-connect-to-instance.jpg deleted file mode 100644 index 61c367de2..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/08-connect-to-instance.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/09-update-and-install.jpg b/doc/Articles/Guides/DevServer/gcloud/09-update-and-install.jpg deleted file mode 100644 index 7344ffea0..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/09-update-and-install.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/10-server-build.jpg b/doc/Articles/Guides/DevServer/gcloud/10-server-build.jpg deleted file mode 100644 index 0cd5df500..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/10-server-build.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/11-upload-a-file.jpg b/doc/Articles/Guides/DevServer/gcloud/11-upload-a-file.jpg deleted file mode 100644 index 0df81132a..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/11-upload-a-file.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/12-uploading.jpg b/doc/Articles/Guides/DevServer/gcloud/12-uploading.jpg deleted file mode 100644 index b628c77b3..000000000 Binary files a/doc/Articles/Guides/DevServer/gcloud/12-uploading.jpg and /dev/null differ diff --git a/doc/Articles/Guides/DevServer/gcloud/index.md b/doc/Articles/Guides/DevServer/gcloud/index.md deleted file mode 100644 index ecb95fc33..000000000 --- a/doc/Articles/Guides/DevServer/gcloud/index.md +++ /dev/null @@ -1,251 +0,0 @@ -# Google Cloud Services - -This guide will explain how to set up a Linux server running on [Google Cloud](https://cloud.google.com/). - -Google cloud offers $300 free credits to new users for a limited time, and it also have "Always free products". See [overview](https://cloud.google.com/free) and [docs](https://cloud.google.com/free/docs/gcp-free-tier) for more information. - - -## Before you begin - -1) In the Cloud Console, on the project selector page, select or create a Cloud project. - -> Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project. - -**[Go to the project selector page](https://console.cloud.google.com/projectselector2/home/dashboard)** - -2) You may need to enable billing for your Google Cloud project. If you have free credits (see above) then these will be used first. [Learn how to confirm billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project) - -## Setting up a new Server - -Start by creating and configuring a new Compute Engine instance. - -1) In the Cloud Console, go to the VM instances page: - -**[Go to the VM instances page](https://console.cloud.google.com/compute/instances)** - -If this is your first instance you will see a dialog prompting you to create a new virtual machine - -![create new](./01-vm-instances.jpg) - -2) Click Create to get started. - -3) On the Create an instance page, configure your instance as follows: - - - Name your instance. This tutorial uses the instance name `mirror-instance-demo` throughout. - - Select the region and zone in which you want your instance to be hosted. This tutorial uses the region `us-central1 (Iowa)` and the zone `us-central1-a` throughout. - - Machine configuration depends on the size of your game. For a simple example we can use a small server. - - select `N1` for series - - select `f1-micro` for machine type - - In the Boot disk section, click Change. The Boot disk dialog will pop up. - - Change the disk type to SSD Persistent Disk. - -![create instance with name and region](./02-create-instance-name-region.jpg) - -4) Boot disk can be left as default `10gb standard persistent disk` with `Debian GNU/Linux 9 (stretch)` for this tutorial. - -You may want to change it to best fit your needs. You can instead use an ssd or increase its size, however this will increase the monthly cost. - -![Boot disk](./03-boot-disk.jpg) - -> Note: The monthly estimate should be shown at the top right next to `Name` - -5) To configure Network settings first example the `Management, security, disks, networking, solo tenancy` section, then click on the `Networking` tab. - -![expand network settings](./04-expand-network-settings.jpg) - -6) Set a Network tag, this will allow you to set up firewall rules later on. - -This tutorial use `mirror-demo` as the tag - -![set network tag](./05-network-tag.jpg) - -7) Set up a static IP address for your instance - - a) Under **Network interfaces** click on `default` and it will bring up a config menu - - b) Select the **External IP** dropdown and select `Create IP address` - - c) Enter a name for this ip and press **Reserve**. For this tutorial we will use `mirror-demo-ip` - -![reserve ip address](./06-ip-address.jpg) - -8) Create your instance. - -Press the **Create** button at the bottom of the page to finish set up and create your instance - -## Configure Firewall - -This will allow other people to connect to your server using its IP and port - -1) In the Cloud Console, go to the Firewall page. - -**[Go to the Firewall page](https://console.cloud.google.com/networking/firewalls/list)** - -2) Click Create firewall rule. - -3) On the Create a firewall rule page, fill out the form as follows: - - - Name: `mirror-demo-rule` - - Target tags: `mirror-demo` - - Source filter: IP ranges - - Source IP ranges: 0.0.0.0/0 - - Protocols or ports: Select TCP, and then enter port 7777 into the field provided. - - If you're using the default Kcp Transport in your Network Manager instead of the Telepathy Transport, then you will need to use UDP instead. If you are using a different transport or have configured it to use a different port then you will need to use those settings. - -![Create network rule](./07-create-network-rule.jpg) - -4) Press **Create** to confirm setting and create the rule. - -## Connect to your new instance - -Once your instance has finished being created you can press the **SSH** button to connect to your instance in your web browser - -![connect to instance](./08-connect-to-instance.jpg) - -## Setting up the linux instance - -When you first connect you will need to set up a few things - -1) First update the list of packages -```sh -sudo apt-get update -``` - -2) Install `screen` and `unzip` -```sh -sudo apt-get install -y screen unzip -``` - -`screen` allows you to have multiple terminals, allows you do do other stuff while your game is running - -`unzip` unzips can be used to extract files from a ZIP file after you upload it to the instance - -![update and install packages](./09-update-and-install.jpg) - -## Build your game - -Build your game with Target Platform `Linux` and **Server Build** ticked - -![Server build](./10-server-build.jpg) - - -## Upload and extract your game - -Once you have built your game zip the folder so that you can upload it to your server. - -In the SSH connection window click on the settings cogwheel and select **Upload File** then find and select your zipped build folder. - -![Upload a file](./11-upload-a-file.jpg) - -This should upload the game folder to the home directory. - -If you need to go to the home directory you can use: -```sh -cd ~ -``` - -> Note: the destination will be `/home/username` where username should be the cloud account you are logged into. - -![Uploading](./12-uploading.jpg) - -Once your file has finished upload you can extract the files - -```sh -unzip ./mirror-demo.zip -``` - -## Run server - -1) Move into game folder -```sh -cd mirror-demo -``` - -2) Mark game as executable -```sh -chmod +x ./mirror-demo.x86_64 -``` - -You should now be able to run your game server! - -The following is optional but will most likely be useful - -3) Start your server in a detached screen - -```sh -screen -d -m -S mirrorServer ./mirror-demo.x86_64 -logfile ~/server.log -``` - -The parts of the command above: -- `screen -d -m` will create the new terminal in detached mode -- `-S mirrorServer` name of the screen -- `./mirror-demo.x86_64` your game server file -- `-logfile ~/server.log` unity argument for log file location, this will create a log file in the home directory - - -4) Create start file so you can start your server the same way each time - - a) create `start.sh` - ``` - echo "screen -d -m -S mirrorServer ./mirror-demo.x86_64 -logfile ~/server.log" > ./start.sh - ``` - - b) mark as executable - ```sh - chmod +x ./start.sh - ``` - -5) Run your server -```sh -./start.sh -``` - -### Using Screen - -Here are a few useful commands for using `screen` - -- List active screens -```sh -screen -ls -``` - -- Attach to existing screen, - - process-id is show when calling `screen -ls` - - screen name is given by `-S` when creating the screen, for this tutorial it was `mirrorServer` -```sh -screen -r -``` - -- Detach from screen press `CTRL A + D` - -- Stop your game - -Once attached to a screen you can press `CTRL + C` to stop the process, this will stop your game and close the screen - - -### View log files - -You can use the `-logfile ~/path/to/log.log` argument for Unity when starting your game server. This will cause the logs to be written to a file instead of to the terminal. This will means recent logs wont show up in `screen -r`. - -- you can use the `tail` command to view the the end of the log file - -```sh -tail -n 50 ./server.log -``` -- you can use the `-n` argument to set how many lines to show - -- you can use the `-f` argument follow the end of the file stream showing you any new logs that are written to the file in real time. You will need to press `CTRL + C` to exit follow mode - - - -## Clean up after tutorial - -If you used an existing project you will need to delete the following: -- VM instance -- Firewall rule - - -If you have created a new project you should be able to just delete the project. - -**[Go to the Manage resources page](https://console.cloud.google.com/iam-admin/projects)** - diff --git a/doc/Articles/Guides/DevServer/index.md b/doc/Articles/Guides/DevServer/index.md deleted file mode 100644 index af0b484e3..000000000 --- a/doc/Articles/Guides/DevServer/index.md +++ /dev/null @@ -1,60 +0,0 @@ -# Development Servers - -During this guide we will set up a dedicated server and place the server build of our project on the dedicated server. - -**IMPORTANT:** Before we begin, there are some potential problems you may face, as no server is truly 'free': - -1. Service providers are NOT free. -2. Most of the time you can start with free trials for a limited time, after x amount of time or x amount of used resources the trial will end and you might incur payment. -3. Always read the providers free trial limitations. -4. Some providers require a payment method for using a Windows instance, however as long as you do not go over the limitations the provider should not bill you. - -> **NOTE**: Mirror is not affiliated and can not be held responsible for any charges or fees associated with service providers like -[AWS](https://aws.amazon.com/), -[Microsoft Azure](https://azure.microsoft.com/en-us/free/), -[Google Compute Engine](https://cloud.google.com/compute/) and others... - -## Introduction - -During your development with Mirror you will need to test your project as a client and as a server. -There are a few possible ways to test your project: - -1. Default build: Host/client as one and connecting with another build/editor to the host locally on 1 computer. -2. Server build: Server is a separate executable. You can place it on your computer run it and connect to it as a client. -3. Dedicated Server: Same as the server build but placed on an external machine, you connect to it with the server's external ip. - -This guide will focus on the "Dedicated Server" option. There are multiple providers and even self hosted dedicated machines. -All possibilities still go through the same process to ensure connectivity to clients. A few requirements for a dedicated server: - -1. Port forwarding (Not strictly necessary but makes everything a lot easier without needing NAT punchthrough) -2. Firewall exceptions -3. Computer/machine that stays online and accessible whenever you need it. - -In the upcoming sections we will go through setting up a provider with the free tier. - -**Always double check that you do not select a paid feature as this is purely meant as a short term period to test out basic functionality during development of your project.** - -### Amazon Web Services (AWS) - -See [AWS setup](https://mirror-networking.com/docs/Articles/Guides/DevServer/AWS/index.html) - - -### Google Compute Engine - -See this guides: [Google cloud setup](https://mirror-networking.com/docs/Articles/Guides/DevServer/gcloud/index.html) - - -### Microsoft Azure - -Microsoft Azure (as of time of writing) allows setting up a windows instance during the free trial without an active payment method. - -**To be added** - -### Self Hosted Dedicated Server - -A self hosted dedicated server is the same as the other providers but you provide the hardware, internet connection and costs for running the computer. -Most of the time this is the cheapest option during development if you already have an extra machine. -Preferably you would put the machine on a different network (to simulate the conditions as the other providers). -This would mean you could connect to the machine and put your server build on whenever you need and have access to the router and security settings of the machine for port forwarding and firewall exceptions. - -In essence, this is the simplest set up but does require extra hardware. diff --git a/doc/Articles/Guides/DevServer/toc.yml b/doc/Articles/Guides/DevServer/toc.yml deleted file mode 100644 index 1e50fe159..000000000 --- a/doc/Articles/Guides/DevServer/toc.yml +++ /dev/null @@ -1,6 +0,0 @@ -- name: Overview - href: index.md -- name: AWS - href: AWS/index.md -- name: Google Cloud - href: gcloud/index.md diff --git a/doc/Articles/Guides/GameObjects/ChildObjects1.PNG b/doc/Articles/Guides/GameObjects/ChildObjects1.PNG deleted file mode 100644 index f6a01b367..000000000 Binary files a/doc/Articles/Guides/GameObjects/ChildObjects1.PNG and /dev/null differ diff --git a/doc/Articles/Guides/GameObjects/ChildObjects2.PNG b/doc/Articles/Guides/GameObjects/ChildObjects2.PNG deleted file mode 100644 index 88c8e0f87..000000000 Binary files a/doc/Articles/Guides/GameObjects/ChildObjects2.PNG and /dev/null differ diff --git a/doc/Articles/Guides/GameObjects/ChildObjects3.PNG b/doc/Articles/Guides/GameObjects/ChildObjects3.PNG deleted file mode 100644 index e6520a950..000000000 Binary files a/doc/Articles/Guides/GameObjects/ChildObjects3.PNG and /dev/null differ diff --git a/doc/Articles/Guides/GameObjects/NetworkLocalPlayers.png b/doc/Articles/Guides/GameObjects/NetworkLocalPlayers.png deleted file mode 100644 index ddf28174d..000000000 Binary files a/doc/Articles/Guides/GameObjects/NetworkLocalPlayers.png and /dev/null differ diff --git a/doc/Articles/Guides/GameObjects/PickupDropChild.md b/doc/Articles/Guides/GameObjects/PickupDropChild.md deleted file mode 100644 index 3057ff6b7..000000000 --- a/doc/Articles/Guides/GameObjects/PickupDropChild.md +++ /dev/null @@ -1,244 +0,0 @@ -# Pickups, Drops, and Child Objects - -Frequently the question comes up about how to handle objects that are attached as children of the player prefab that all clients need to know about and synchronize, such as which weapon is equipped, picking up networked scene objects, and players dropping objects into the scene. - -> Mirror cannot support multiple Network Identity components within an object hierarchy. Since the Player object must have a Network Identity, none of its descendant objects can have one. - -## Child Objects - -Let's start with the simple case of a single attachment point that is somewhere down the hierarchy of our Player, such as a hand at the end of an arm. In a script that inherits from NetworkBehaviour on the Player Prefab, we'd have a `GameObject` reference where the attachment point can be assigned in the inspector, a SyncVar enum with various choices of what the player is holding, and and a Hook for the SyncVar to swap out the art of the held item based on the new value. - -In the image below, Kyle has an empty game object, `RightHand`, added to the wrist, and some prefabs to be equipped (Ball, Box, Cylinder), and a Player Equip script to handle them. - -> **NOTE**: The item prefabs are *art only*...they have no scripts, and they *must not* have networking components. They can have monobehaviour-based scripts, of course, which can be referenced and called from ClientRpc's on the player prefab. - -The inspector shows `RightHand` assigned in 2 places, the Player Equip script, as well as the target of the Network Transform Child component, so we could adjust the relative position of the attachment point (not the art) for all clients as needed. - -![Screenshot of Player with Equip Script](ChildObjects1.PNG) - -Below is the Player Equip script to handle the changing of the equipped item, and some notes for consideration: -- While we could just have all the art items attached at design time and just enable / disable them based on the enum, this doesn't scale well to a lot of items and if they have scripts on them for how they behave in the game, such as animations, special effects, etc. it could get ugly pretty fast, so this example locally instantiates and destroys instead as a design choice. -- The example makes no effort to deal with position offset between the item and the attach point, e.g. having the grip or handle of an item align with the hand. This is best dealt with in a monobehaviour script on the item that has public fields for the local position and rotation that can be set in the designer and a bit of code in Start to apply those values in local coordinates relative to the parent attach point. - -``` cs -using UnityEngine; -using System.Collections; -using Mirror; - -public enum EquippedItem : byte -{ - nothing, - ball, - box, - cylinder -} - -public class PlayerEquip : NetworkBehaviour -{ - public GameObject sceneObjectPrefab; - - public GameObject rightHand; - - public GameObject ballPrefab; - public GameObject boxPrefab; - public GameObject cylinderPrefab; - - [SyncVar(hook = nameof(OnChangeEquipment))] - public EquippedItem equippedItem; - - void OnChangeEquipment(EquippedItem oldEquippedItem, EquippedItem newEquippedItem) - { - StartCoroutine(ChangeEquipment(newEquippedItem)); - } - - // Since Destroy is delayed to the end of the current frame, we use a coroutine - // to clear out any child objects before instantiating the new one - IEnumerator ChangeEquipment(EquippedItem newEquippedItem) - { - while (rightHand.transform.childCount > 0) - { - Destroy(rightHand.transform.GetChild(0).gameObject); - yield return null; - } - - switch (newEquippedItem) - { - case EquippedItem.ball: - Instantiate(ballPrefab, rightHand.transform); - break; - case EquippedItem.box: - Instantiate(boxPrefab, rightHand.transform); - break; - case EquippedItem.cylinder: - Instantiate(cylinderPrefab, rightHand.transform); - break; - } - } - - void Update() - { - if (!isLocalPlayer) return; - - if (Input.GetKeyDown(KeyCode.Alpha0) && equippedItem != EquippedItem.nothing) - CmdChangeEquippedItem(EquippedItem.nothing); - if (Input.GetKeyDown(KeyCode.Alpha1) && equippedItem != EquippedItem.ball) - CmdChangeEquippedItem(EquippedItem.ball); - if (Input.GetKeyDown(KeyCode.Alpha2) && equippedItem != EquippedItem.box) - CmdChangeEquippedItem(EquippedItem.box); - if (Input.GetKeyDown(KeyCode.Alpha3) && equippedItem != EquippedItem.cylinder) - CmdChangeEquippedItem(EquippedItem.cylinder); - } - - [Command] - void CmdChangeEquippedItem(EquippedItem selectedItem) - { - equippedItem = selectedItem; - } -} -``` - -## Dropping Items - -Now that we can equip the items, we need a way to drop the current item into the world as a networked item. Remember that, as child art, the item prefabs have no networking components on them at all. - -First, let's add one more Input to the Update method above, and a `CmdDropItem` method: - -``` cs - void Update() - { - if (!isLocalPlayer) return; - - if (Input.GetKeyDown(KeyCode.Alpha0) && equippedItem != EquippedItem.nothing) - CmdChangeEquippedItem(EquippedItem.nothing); - if (Input.GetKeyDown(KeyCode.Alpha1) && equippedItem != EquippedItem.ball) - CmdChangeEquippedItem(EquippedItem.ball); - if (Input.GetKeyDown(KeyCode.Alpha2) && equippedItem != EquippedItem.box) - CmdChangeEquippedItem(EquippedItem.box); - if (Input.GetKeyDown(KeyCode.Alpha3) && equippedItem != EquippedItem.cylinder) - CmdChangeEquippedItem(EquippedItem.cylinder); - - if (Input.GetKeyDown(KeyCode.X) && equippedItem != EquippedItem.nothing) - CmdDropItem(); - } -``` - -``` cs - [Command] - void CmdDropItem() - { - // Instantiate the scene object on the server - Vector3 pos = rightHand.transform.position; - Quaternion rot = rightHand.transform.rotation; - GameObject newSceneObject = Instantiate(sceneObjectPrefab, pos, rot); - - // set the RigidBody as non-kinematic on the server only (isKinematic = true in prefab) - newSceneObject.GetComponent().isKinematic = false; - - SceneObject sceneObject = newSceneObject.GetComponent(); - - // set the child object on the server - sceneObject.SetEquippedItem(equippedItem); - - // set the SyncVar on the scene object for clients - sceneObject.equippedItem = equippedItem; - - // set the player's SyncVar to nothing so clients will destroy the equipped child item - equippedItem = EquippedItem.nothing; - - // Spawn the scene object on the network for all to see - NetworkServer.Spawn(newSceneObject); - } -``` - -In the image above, there's a `sceneObjectPrefab` field that is assigned to a prefab that will act as a container for our item prefabs. The SceneObject prefab has a SceneObject script with a SyncVar like the Player Equip script, and a SetEquippedItem method that takes the shared enum value as a parameter. - -``` cs -using UnityEngine; -using System.Collections; -using Mirror; - -public class SceneObject : NetworkBehaviour -{ - [SyncVar(hook = nameof(OnChangeEquipment))] - public EquippedItem equippedItem; - - public GameObject ballPrefab; - public GameObject boxPrefab; - public GameObject cylinderPrefab; - - void OnChangeEquipment(EquippedItem oldEquippedItem, EquippedItem newEquippedItem) - { - StartCoroutine(ChangeEquipment(newEquippedItem)); - } - - // Since Destroy is delayed to the end of the current frame, we use a coroutine - // to clear out any child objects before instantiating the new one - IEnumerator ChangeEquipment(EquippedItem newEquippedItem) - { - while (transform.childCount > 0) - { - Destroy(transform.GetChild(0).gameObject); - yield return null; - } - - // Use the new value, not the SyncVar property value - SetEquippedItem(newEquippedItem); - } - - // SetEquippedItem is called on the client from OnChangeEquipment (above), - // and on the server from CmdDropItem in the PlayerEquip script. - public void SetEquippedItem(EquippedItem newEquippedItem) - { - switch (newEquippedItem) - { - case EquippedItem.ball: - Instantiate(ballPrefab, transform); - break; - case EquippedItem.box: - Instantiate(boxPrefab, transform); - break; - case EquippedItem.cylinder: - Instantiate(cylinderPrefab, transform); - break; - } - } -} -``` - -In the run-time image below, the Ball(Clone) is attached to the `RightHand` object, and the Box(Clone) is attached to the SceneObject(Clone), which is shown in the inspector. - -> The art prefabs have simple colliders on them (sphere, box, capsule). If your art item has a mesh collider, it must be marked as Convex to work with the RigidBody on the SceneObject container. - -![Screenshot of Kyle with equipped item and scene object](ChildObjects2.PNG) - -## Pickup Items - -Now that we have a box dropped in the scene, we need to pick it up again. To do that, a `CmdPickupItem` method is added to the Player Equip script: - -``` cs - // CmdPickupItem is public because it's called from a script on the SceneObject - [Command] - public void CmdPickupItem(GameObject sceneObject) - { - // set the player's SyncVar so clients can show the equipped item - equippedItem = sceneObject.GetComponent().equippedItem; - - // Destroy the scene object - NetworkServer.Destroy(sceneObject); - } -``` - -This method is simply called from `OnMouseDown` in the Scene Object script: - -``` cs - void OnMouseDown() - { - NetworkClient.connection.identity.GetComponent().CmdPickupItem(gameObject); - } -``` - -Since the SceneObject(Clone) is networked, we can pass it directly through to `CmdPickupItem` on the player object to set the equipped item SyncVar and destroy the scene object. - -For this entire example, the only prefab that needs to be registered with Network Manager besides the Player is the SceneObject prefab. - -![Screenshot of inspector](ChildObjects3.PNG) diff --git a/doc/Articles/Guides/GameObjects/SceneObjects.md b/doc/Articles/Guides/GameObjects/SceneObjects.md deleted file mode 100644 index c4d29e23d..000000000 --- a/doc/Articles/Guides/GameObjects/SceneObjects.md +++ /dev/null @@ -1,22 +0,0 @@ -# Scene Game Objects - -There are two types of networked game objects in Mirror’s multiplayer system: -- Those that are created dynamically at runtime -- Those that are saved as part of a Scene - -Game objects that are created dynamically at runtime use the multiplayer Spawning system, and the prefabs they are instantiated from must be registered in the Network Manager’s list of networked game object prefabs. - -However, networked game objects that you save as part of a Scene (and therefore already exist in the Scene when it is loaded) are handled differently. These game objects are loaded as part of the Scene on both the client and server, and exist at runtime before any spawn messages are sent by the multiplayer system. - -When the Scene is loaded, all networked game objects in the Scene are disabled on both the client and the server. Then, when the Scene is fully loaded, the Network Manager automatically processes the Scene’s networked game objects, registering them all (and therefore causing them to be synchronized across clients), and enabling them, as if they were spawned at runtime. Networked game objects will not be enabled until a client has requested a Player object. - -Saving networked game objects in your Scene (rather than dynamically spawning them after the scene has loaded) has some benefits: -- They are loaded with the level, so there will be no pause at runtime. -- They can have specific modifications that differ from prefabs -- Other game object instances in the Scene can reference them, which can avoid you having to use code to finding the game objects and make references to them up at runtime. - -When the Network Manager spawns the networked Scene game objects, those game objects behave like dynamically spawned game objects. Mirror sends them updates and ClientRPC calls. - -If a Scene game object is destroyed on the server before a client joins the game, then it is never enabled on new clients that join. - -When a client connects, the client is sent an ObjectSpawnScene spawn message for each of the Scene game objects that exist on the server, that are visible to that client. This message causes the game object on the client to be enabled, and has the latest state of that game object from the server in it. This means that only game objects that are visible to the client, and not destroyed on the server, are activated on the client. Like regular non-Scene game objects, these Scene game objects are started with the latest state when the client joins the game. diff --git a/doc/Articles/Guides/GameObjects/SpawnObject.md b/doc/Articles/Guides/GameObjects/SpawnObject.md deleted file mode 100644 index 0740ba799..000000000 --- a/doc/Articles/Guides/GameObjects/SpawnObject.md +++ /dev/null @@ -1,209 +0,0 @@ -# Spawning Game Objects - -In Unity, you usually “spawn” (that is, create) new game objects with `Instantiate`. However, in Mirror, the word “spawn” means something more specific. In the server-authoritative model of the Mirror, to “spawn” a game object on the server means that the game object is created on clients connected to the server, and is managed by the spawning system. - -Once the game object is spawned using this system, state updates are sent to clients whenever the game object changes on the server. When Mirror destroys the game object on the server, it also destroys it on the clients. The server manages spawned game objects alongside all other networked game objects, so that if another client joins the game later, the server can spawn the game objects on that client. These spawned game objects have a unique network instance ID called “netId” that is the same on the server and clients for each game object. The unique network instance ID is used to route messages set across the network to game objects, and to identify game objects. - -When the server spawns a game object with a Network Identity component, the game object spawned on the client has the same “state”. This means it is identical to the game object on the server; it has the same Transform, movement state, and (if Network Transform and SyncVars are used) synchronized variables. Therefore, client game objects are always up-to-date when Mirror creates them. This avoids issues such as game objects spawning at the wrong initial location, then reappearing at their correct position when a state update arrives. - -A game object Prefab must have a Network Identity component before trying to register it with the Network Manager. - -To register a Prefab with the Network Manager in the Editor, select the Network Manager game object, and in the Inspector, navigate to the Network Manager component. Click the triangle next to Spawn Info to open the settings, then under Registered Spawnable Prefabs, click the plus (+) button. Drag and drop Prefabs into the empty field to assign them to the list. - -![Registered Spawnable Prefabs](SpawnObjects.PNG) - -## Spawning Without Network Manager - -For more advanced users, you may find that you want to register Prefabs and spawn game objects without using the Network Manager component. - -To spawn game objects without using the Network Manager, you can handle the Prefab registration yourself via script. Use the `ClientScene.RegisterPrefab` method to register Prefabs to the Network Manager. - -``` cs -using UnityEngine; -using Mirror; - -public class MyNetworkManager : MonoBehaviour -{ - public GameObject treePrefab; - - // Register prefab and connect to the server - public void ClientConnect() - { - ClientScene.RegisterPrefab(treePrefab); - NetworkClient.RegisterHandler(OnClientConnect); - NetworkClient.Connect("localhost"); - } - - void OnClientConnect(NetworkConnection conn, ConnectMessage msg) - { - Debug.Log("Connected to server: " + conn); - } -} -``` - -In this example, you create an empty game object to act as the Network Manager, then create and attach the `MyNetworkManager` script (above) to that game object. Create a prefab that has a Network Identity component attached to it, and drag that onto the `treePrefab` slot on the `MyNetworkManager` component in the Inspector. This ensures that when the server spawns the tree game object, it also creates the same kind of game object on the clients. - -Registering prefabs ensures that there is no stalling or loading time for creating the Asset. - -For the script to work, you also need to add code for the server. Add this to the `MyNetworkManager` script: - -``` cs -public void ServerListen() -{ - NetworkServer.RegisterHandler(OnServerConnect); - NetworkServer.RegisterHandler(OnClientReady); - - // start listening, and allow up to 4 connections - NetworkServer.Listen(4); -} - -// When client is ready spawn a few trees -void OnClientReady(NetworkConnection conn, ReadyMessage msg) -{ - Debug.Log("Client is ready to start: " + conn); - NetworkServer.SetClientReady(conn); - SpawnTrees(); -} - -void SpawnTrees() -{ - int x = 0; - for (int i = 0; i < 5; ++i) - { - GameObject treeGo = Instantiate(treePrefab, new Vector3(x++, 0, 0), Quaternion.identity); - NetworkServer.Spawn(treeGo); - } -} - -void OnServerConnect(NetworkConnection conn, ConnectMessage msg) -{ - Debug.Log("New client connected: " + conn); -} -``` - -The server does not need to register anything, as it knows what game object is being spawned (and the asset ID is sent in the spawn message). The client needs to be able to look up the game object, so it must be registered on the client. - -When writing your own network manager, it’s important to make the client ready to receive state updates before calling the spawn command on the server, otherwise they won’t be sent. If you’re using Mirror’s built-in Network Manager component, this happens automatically. - -For more advanced uses, such as object pools or dynamically created Assets, you can use the `ClientScene.RegisterSpawnHandler` method, which allows callback functions to be registered for client-side spawning. See documentation on Custom Spawn Functions for an example of this. - -If the game object has a network state like synchronized variables, then that state is synchronized with the spawn message. In the following example, this script is attached to the tree Prefab: - -``` cs -using UnityEngine; -using Mirror; - -class Tree : NetworkBehaviour -{ - [SyncVar] - public int numLeaves; - - public override void OnStartClient() - { - Debug.Log("Tree spawned with leaf count " + numLeaves); - } -} -``` - -With this script attached, you can change the `numLeaves` variable and modify the `SpawnTrees` function to see it accurately reflected on the client: - -``` cs -void SpawnTrees() -{ - int x = 0; - for (int i = 0; i < 5; ++i) - { - GameObject treeGo = Instantiate(treePrefab, new Vector3(x++, 0, 0), Quaternion.identity); - Tree tree = treeGo.GetComponent(); - tree.numLeaves = Random.Range(10,200); - Debug.Log("Spawning leaf with leaf count " + tree.numLeaves); - NetworkServer.Spawn(treeGo); - } -} -``` - -Attach the `Tree` script to the `treePrefab` script created earlier to see this in action. - -### Constraints -- A NetworkIdentity must be on the root game object of a spawnable Prefab. Without this, the Network Manager can’t register the Prefab. -- NetworkBehaviour scripts must be on the same game object as the NetworkIdentity, not on child game objects - -## Game Object Creation Flow - -The actual flow of internal operations that takes place for spawning game objects is: -- Prefab with Network Identity component is registered as spawnable. -- game object is instantiated from the Prefab on the server. -- Game code sets initial values on the instance (note that 3D physics forces applied here do not take effect immediately). -- `NetworkServer.Spawn` is called with the instance. -- The state of the SyncVars on the instance on the server are collected by calling `OnSerialize` on [Network Behaviour] components. -- A network message of type `ObjectSpawn` is sent to connected clients that includes the SyncVar data. -- `OnStartServer` is called on the instance on the server, and `isServer` is set to `true` -- Clients receive the `ObjectSpawn` message and create a new instance from the registered Prefab. -- The SyncVar data is applied to the new instance on the client by calling OnDeserialize on Network Behaviour components. -- `OnStartClient` is called on the instance on each client, and `isClient` is set to `true` -- As game play progresses, changes to SyncVar values are automatically synchronized to clients. This continues until game ends. -- `NetworkServer.Destroy` is called on the instance on the server. -- `OnStopServer` is called on the instance on the server -- A network message of type `ObjectDestroy` is sent to clients. -- `OnStopClient` is called on the instance on clients -- The instance is destroyed (or disabled if it is a scene object) - -### Player Game Objects - -Player game objects in the HLAPI work slightly differently to non-player game objects. The flow for spawning player game objects with the Network Manager is: -- Prefab with `NetworkIdentity` is registered as the `PlayerPrefab` -- Client connects to the server -- Client calls `AddPlayer`, network message of type `MsgType.AddPlayer` is sent to the server -- Server receives message and calls `NetworkManager.OnServerAddPlayer` -- game object is instantiated from the Player Prefab on the server -- `NetworkManager.AddPlayerForConnection` is called with the new player instance on the server -- The player instance is spawned - you do not have to call `NetworkServer.Spawn` for the player instance. The spawn message is sent to all clients like on a normal spawn. -- A network message of type `Owner` is sent to the client that added the player (only that client!) -- The original client receives the network message -- `OnStartLocalPlayer` is called on the player instance on the original client, and `isLocalPlayer` is set to true - -Note that `OnStartLocalPlayer` is called after `OnStartClient`, because it only happens when the ownership message arrives from the server after the player game object is spawned, so `isLocalPlayer` is not set in `OnStartClient`. - -Because `OnStartLocalPlayer` is only called for the client’s local player game object, it is a good place to perform initialization that should only be done for the local player. This could include enabling input processing, and enabling camera tracking for the player game object. - -## Spawning Game Objects with Client Authority - -To spawn game objects and assign authority of those game objects to a particular client, use `NetworkServer.Spawn`, which takes as an argument the `NetworkConnection` of the client that is to be made the authority. - -For these game objects, the property `hasAuthority` is true on the client with authority, and `OnStartAuthority` is called on the client with authority. That client can issue commands for that game object. On other clients (and on the host), `hasAuthority` is false. - -Objects spawned with client authority must have `LocalPlayerAuthority` set in their `NetworkIdentity`. - -For example, the tree spawn example above can be modified to allow the tree to have client authority like this (note that we now need to pass in a NetworkConnection game object for the owning client’s connection): - -``` cs -void SpawnTrees(NetworkConnection conn) -{ - int x = 0; - for (int i = 0; i < 5; ++i) - { - GameObject treeGo = Instantiate(treePrefab, new Vector3(x++, 0, 0), Quaternion.identity); - Tree tree = treeGo.GetComponent(); - tree.numLeaves = Random.Range(10,200); - Debug.Log("Spawning leaf with leaf count " + tree.numLeaves); - NetworkServer.Spawn(treeGo, conn); - } -} -``` - -The Tree script can now be modified to send a command to the server: - -``` cs -public override void OnStartAuthority() -{ - CmdMessageFromTree("Tree with " + numLeaves + " reporting in"); -} - -[Command] -void CmdMessageFromTree(string msg) -{ - Debug.Log("Client sent a tree message: " + msg); -} -``` - -Note that you can’t just add the `CmdMessageFromTree` call into `OnStartClient`, because at that point the authority has not been set yet, so the call would fail. diff --git a/doc/Articles/Guides/GameObjects/SpawnObjectCustom.md b/doc/Articles/Guides/GameObjects/SpawnObjectCustom.md deleted file mode 100644 index c23059d73..000000000 --- a/doc/Articles/Guides/GameObjects/SpawnObjectCustom.md +++ /dev/null @@ -1,252 +0,0 @@ -# Custom Spawn Functions - -You can use spawn handler functions to customize the default behavior when creating spawned game objects on the client. Spawn handler functions ensure you have full control of how you spawn the game object, as well as how you destroy it. - -Use `ClientScene.RegisterSpawnHandler` or `ClientScene.RegisterPrefab` to register functions to spawn and destroy client game objects. The server creates game objects directly, and then spawns them on the clients through this functionality. This functions takes either the asset ID or a prefab and two function delegates: one to handle creating game objects on the client, and one to handle destroying game objects on the client. The asset ID can be a dynamic one, or just the asset ID found on the prefab game object you want to spawn. - -The spawn / unspawn delegates will look something like this: - -**Spawn Handler** -``` cs -GameObject SpawnDelegate(Vector3 position, System.Guid assetId) -{ - // do stuff here -} -``` -or -``` cs -GameObject SpawnDelegate(SpawnMessage msg) -{ - // do stuff here -} -``` - -**UnSpawn Handler** -```cs -void UnSpawnDelegate(GameObject spawned) -{ - // do stuff here -} -``` - -When a prefab is saved its `assetId` field will be automatically set. If you want to create prefabs at runtime you will have to generate a new GUID. - -**Generate prefab at runtime** -``` cs -// generate a new unique assetId -System.Guid creatureAssetId = System.Guid.NewGuid(); - -// register handlers for the new assetId -ClientScene.RegisterSpawnHandler(creatureAssetId, SpawnCreature, UnSpawnCreature); -``` - -**Use existing prefab** -```cs -// register prefab you'd like to custom spawn and pass in handlers -ClientScene.RegisterPrefab(coinAssetId, SpawnCoin, UnSpawnCoin); -``` - -**Spawn on Server** -```cs -// spawn a coin - SpawnCoin is called on client -NetworkServer.Spawn(gameObject, coinAssetId); -``` - -The spawn functions themselves are implemented with the delegate signature. Here is the coin spawner. The `SpawnCreature` would look the same, but have different spawn logic: - -``` cs -public GameObject SpawnCoin(SpawnMessage msg) -{ - return Instantiate(m_CoinPrefab, msg.position, msg.rotation); -} -public void UnSpawnCoin(GameObject spawned) -{ - Destroy(spawned); -} -``` - -When using custom spawn functions, it is sometimes useful to be able to unspawn game objects without destroying them. This can be done by calling `NetworkServer.UnSpawn`. This causes the object to be `Reset` on the server and sends a `ObjectDestroyMessage` to clients. The `ObjectDestroyMessage` will cause the custom unspawn function to be called on the clients. If there is no unspawn function the object will instead be `Destroy` - -Note that on the host, game objects are not spawned for the local client, because they already exist on the server. This also means that no spawn or unspawn handler functions are called. - -## Setting Up a Game Object Pool with Custom Spawn Handlers - -Here is an example of how you might set up a simple game object pooling system with custom spawn handlers. Spawning and unspawning then puts game objects in or out of the pool. - -``` cs -using System.Collections.Generic; -using Mirror; -using UnityEngine; - -namespace Mirror.Examples -{ - public class PrefabPoolManager : MonoBehaviour - { - [Header("Settings")] - public int startSize = 5; - public int maxSize = 20; - public GameObject prefab; - - [Header("Debug")] - [SerializeField] Queue pool; - [SerializeField] int currentCount; - - - void Start() - { - InitializePool(); - - ClientScene.RegisterPrefab(prefab, SpawnHandler, UnspawnHandler); - } - - void OnDestroy() - { - ClientScene.UnregisterPrefab(prefab); - } - - private void InitializePool() - { - pool = new Queue(); - for (int i = 0; i < startSize; i++) - { - GameObject next = CreateNew(); - - pool.Enqueue(next); - } - } - - GameObject CreateNew() - { - if (currentCount > maxSize) - { - Debug.LogError($"Pool has reached max size of {maxSize}"); - return null; - } - - // use this object as parent so that objects dont crowd hierarchy - GameObject next = Instantiate(prefab, transform); - next.name = $"{prefab.name}_pooled_{currentCount}"; - next.SetActive(false); - currentCount++; - return next; - } - - // used by ClientScene.RegisterPrefab - GameObject SpawnHandler(SpawnMessage msg) - { - return GetFromPool(msg.position, msg.rotation); - } - - // used by ClientScene.RegisterPrefab - void UnspawnHandler(GameObject spawned) - { - PutBackInPool(spawned); - } - - /// - /// Used to take Object from Pool. - /// Should be used on server to get the next Object - /// Used on client by ClientScene to spawn objects - /// - /// - /// - /// - public GameObject GetFromPool(Vector3 position, Quaternion rotation) - { - GameObject next = pool.Count > 0 - ? pool.Dequeue() // take from pool - : CreateNew(); // create new because pool is empty - - // CreateNew might return null if max size is reached - if (next == null) { return null; } - - // set position/rotation and set active - next.transform.position = position; - next.transform.rotation = rotation; - next.SetActive(true); - return next; - } - - /// - /// Used to put object back into pool so they can b - /// Should be used on server after unspawning an object - /// Used on client by ClientScene to unspawn objects - /// - /// - public void PutBackInPool(GameObject spawned) - { - // disable object - spawned.SetActive(false); - - // add back to pool - pool.Enqueue(spawned); - } - } -} -``` - -To use this manager, create a new empty game object and add the `PrefabPoolManager` component (code above). Next, drag a prefab you want to spawn multiple times to the Prefab field, and set `startSize` and `maxSize` fields. `startSize` is how many will be spawned when your game starts. `maxSize` is the max number that can be spawned, if this number is reached then an error will be given when trying to more new objects. - -Finally, set up a reference to the PrefabPoolManager in the script you are using for player movement: - -``` cs -PrefabPoolManager prefabPoolManager; - -void Start() -{ - prefabPoolManager = FindObjectOfType(); -} -``` - -Your player logic might contain something like this, which moves and fires coins: - -``` cs -void Update() -{ - if (!isLocalPlayer) - return; - - // move - var x = Input.GetAxis("Horizontal") * 0.1f; - var z = Input.GetAxis("Vertical") * 0.1f; - transform.Translate(x, 0, z); - - // shoot - if (Input.GetKeyDown(KeyCode.Space)) - { - // Command function is called on the client, but invoked on the server - CmdFire(); - } -} -``` - -In the fire logic on the player, make it use the game object pool: - -``` cs -[Command] -void CmdFire() -{ - // Set up bullet on server - GameObject bullet = prefabPoolManager.GetFromPool(transform.position + transform.forward, Quaternion.identity); - bullet.GetComponent().velocity = transform.forward * 4; - - // tell server to send SpawnMessage, which will call SpawnHandler on client - NetworkServer.Spawn(bullet); - - // destroy bullet after 2 seconds - StartCoroutine(Destroy(bullet, 2.0f)); -} - -public IEnumerator Destroy(GameObject go, float delay) -{ - yield return new WaitForSeconds(delay); - - // return object to pool on server - prefabPoolManager.PutBackInPool(go); - - // tell server to send ObjectDestroyMessage, which will call UnspawnHandler on client - NetworkServer.UnSpawn(go); -} -``` - -The Destroy method above shows how to return game objects to the pool so that they can be re-used when you fire again diff --git a/doc/Articles/Guides/GameObjects/SpawnObjects.PNG b/doc/Articles/Guides/GameObjects/SpawnObjects.PNG deleted file mode 100644 index 885812038..000000000 Binary files a/doc/Articles/Guides/GameObjects/SpawnObjects.PNG and /dev/null differ diff --git a/doc/Articles/Guides/GameObjects/SpawnPlayer.md b/doc/Articles/Guides/GameObjects/SpawnPlayer.md deleted file mode 100644 index 72565578d..000000000 --- a/doc/Articles/Guides/GameObjects/SpawnPlayer.md +++ /dev/null @@ -1,13 +0,0 @@ -# Player Game Objects - -Mirror’s multiplayer HLAPI system handles player game objects differently to non-player game objects. When a new player joins the game (when a new client connects to the server), that player’s game object becomes a “local player” game object on the client of that player, and Unity associates the player’s connection with the player’s game object. Unity associates one player game object for each person playing the game, and routes networking commands to that individual game object. A player cannot invoke a command on another player’s game object, only their own. - -The NetworkBehaviour class (which you derive from to create your network scripts) has a property called isLocalPlayer. On each client’s player game object, Mirror sets that property to true on the NetworkBehaviour script, and invokes the OnStartLocalPlayer() callback. This means each client has a different game object set up like this, because on each client a different game object is the one that represents the local player. The diagram below shows two clients and their local players. - -![In this diagram, the circles represent the player game objects marked as the local player on each client](NetworkLocalPlayers.png) - -Only the player game object that is “yours” (from your point of view as the player) has the `isLocalPlayer` flag set. Usually you should set this flag in script to determine whether to process input, whether to make the camera track the game object, or do any other client-side things that should only occur for the player belonging to that client. - -Player game objects represent the player (that is, the person playing the game) on the server, and have the ability to run commands from the player’s client. These commands are secure client-to-server remote procedure calls. In this server-authoritative system, other non-player server-side game objects cannot receive commands directly from client-side game objects. This is both for security, and to reduce the complexity of building your game. By routing all incoming commands from users through the player game object, you can ensure that these messages come from the right place, the right client, and can be handled in a central location. - -The Network Manager adds a player every time a client connects to the server. In some situations though, you might want it not to add players until an input event happens - such as a user pressing a “start” button on the controller. To disable automatic player creation, navigate to the Network Manager component’s Inspector and untick the Auto Create Player checkbox. diff --git a/doc/Articles/Guides/GameObjects/SpawnPlayerCustom.md b/doc/Articles/Guides/GameObjects/SpawnPlayerCustom.md deleted file mode 100644 index 4d23c14d8..000000000 --- a/doc/Articles/Guides/GameObjects/SpawnPlayerCustom.md +++ /dev/null @@ -1,122 +0,0 @@ -# Custom Character Spawning - -Many games need character customization. You may want to pick the color of the hair, eyes, skin, height, race, etc. - -By default Mirror will instantiate the player for you. While that is convenient, it might prevent you from customizing it. Mirror provides the option of overriding player creation and customize it. - -1) Create a class that extends `NetworkManager` if you have not done so. For example: - -``` cs -public class MMONetworkManager : NetworkManager -{ - ... -} -``` -and use it as your Network manager. - -2) Open your Network Manager in the inspector and disable the "Auto Create Player" Boolean. - -3) Create a message that describes your player. For example: - -``` cs -public struct CreateMMOCharacterMessage : NetworkMessage -{ - public Race race; - public string name; - public Color hairColor; - public Color eyeColor; -} - -public enum Race -{ - None, - Elvish, - Dwarvish, - Human -} -``` - -4) Create your player prefabs (as many as you need) and add them to the "Register Spawnable Prefabs" in your Network Manager, or add a single prefab to the player prefab field in the inspector. - -5) Send your message and register a player: - -``` cs -public class MMONetworkManager : NetworkManager -{ - public override void OnStartServer() - { - base.OnStartServer(); - - NetworkServer.RegisterHandler(OnCreateCharacter); - } - - public override void OnClientConnect(NetworkConnection conn) - { - base.OnClientConnect(conn); - - // you can send the message here, or wherever else you want - CreateMMOCharacterMessage characterMessage = new CreateMMOCharacterMessage - { - race = Race.Elvish, - name = "Joe Gaba Gaba", - hairColor = Color.red, - eyeColor = Color.green - }; - - conn.Send(characterMessage); - } - - void OnCreateCharacter(NetworkConnection conn, CreateMMOCharacterMessage message) - { - // playerPrefab is the one assigned in the inspector in Network - // Manager but you can use different prefabs per race for example - GameObject gameobject = Instantiate(playerPrefab); - - // Apply data from the message however appropriate for your game - // Typically Player would be a component you write with syncvars or properties - Player player = gameobject.GetComponent(); - player.hairColor = message.hairColor; - player.eyeColor = message.eyeColor; - player.name = message.name; - player.race = message.race; - - // call this to use this gameobject as the primary controller - NetworkServer.AddPlayerForConnection(conn, gameobject); - } -} -``` - -## Ready State - -In addition to players, client connections also have a “ready” state. The host sends clients that are ready information about spawned game objects and state synchronization updates; clients which are not ready are not sent these updates. When a client initially connects to a server, it is not ready. While in this non-ready state, the client can do things that don’t require real-time interactions with the game state on the server, such as loading Scenes, allowing the player to choose an avatar, or fill in log-in boxes. Once a client has completed all its pre-game work, and all its Assets are loaded, it can call `ClientScene.Ready` to enter the “ready” state. The simple example above demonstrates implementation of ready states; because adding a player with `NetworkServer.AddPlayerForConnection` also puts the client into the ready state if it is not already in that state. - -Clients can send and receive network messages without being ready, which also means they can do so without having an active player game object. So a client at a menu or selection screen can connect to the game and interact with it, even though they have no player game object. See documentation on [Network Messages](../Communications/NetworkMessages.md) for more details about sending messages without using commands and RPC calls. - -## Switching Players - -To replace the player game object for a connection, use `NetworkServer.ReplacePlayerForConnection`. This is useful for restricting the commands that players can issue at certain times, such as in a pregame room screen. This function takes the same arguments as `AddPlayerForConnection`, but allows there to already be a player for that connection. The old player game object does not have to be destroyed. The `NetworkRoomManager` uses this technique to switch from the `NetworkRoomPlayer` game object to a game play player game object when all the players in the room are ready. - -You can also use `ReplacePlayerForConnection` to respawn a player or change the object that represents the player. In some cases it is better to just disable a game object and reset its game attributes on respawn. The following code sample demonstrates how to actually replace the player game object with a new game object: - -``` cs -public class MyNetworkManager : NetworkManager -{ - public void ReplacePlayer(NetworkConnection conn, GameObject newPrefab) - { - // Cache a reference to the current player object - GameObject oldPlayer = conn.identity.gameObject; - - // Instantiate the new player object and broadcast to clients - NetworkServer.ReplacePlayerForConnection(conn, Instantiate(newPrefab)); - - // Remove the previous player object that's now been replaced - NetworkServer.Destroy(oldPlayer); - } -} -``` - -If the player game object for a connection is destroyed, then that client cannot execute Commands. They can, however, still send network messages. - -To use `ReplacePlayerForConnection` you must have the `NetworkConnection` game object for the player’s client to establish the relationship between the game object and the client. This is usually the property `connectionToClient` on the `NetworkBehaviour` class, but if the old player has already been destroyed, then that might not be readily available. - -To find the connection, there are some lists available. If using the `NetworkRoomManager`, then the room players are available in `roomSlots`. The `NetworkServer` also has lists of `connections`. diff --git a/doc/Articles/Guides/GameObjects/index.md b/doc/Articles/Guides/GameObjects/index.md deleted file mode 100644 index b299ec698..000000000 --- a/doc/Articles/Guides/GameObjects/index.md +++ /dev/null @@ -1,16 +0,0 @@ -# Networked Game Objects - -Networked game objects are game objects which are controlled and synchronized by Mirror’s networking system. Using synchronized networked game objects, you can create a shared experience for all the players who are playing an instance of your game. They see and hear the same events and actions - even though that may be from their own unique viewpoints within your game. - -Multiplayer games in Mirror are typically built using Scenes that contain a mix of networked game objects and regular (non-networked) game objects. The networked game objects are those which move or change during gameplay in a way that needs to be synchronized across all users who are playing the game together. Non-networked game objects are those which either don’t move or change at all during gameplay (for example, static obstacles like rocks or fences), or game objects which have movement or changes that don’t need to be synchronized across players (for example, a gently swaying tree or clouds passing by in the background of your game). - -A networked game object is one which has a Network Identity component attached. However, a Network Identity component alone is not enough for your game object to be functional and active in your multiplayer game. The Network Identity component is the starting point for synchronization, and it allows the Network Manager to synchronize the creation and destruction of the game object, but other than that, it does not specify *which properties* of your game object should be synchronized. - -What exactly should be synchronized on each networked game object depends on the type of game you are making, and what each game object’s purpose is. Some examples of what you might want to synchronize are: -- The position and rotation of moving game objects such as the players and non-player characters. -- The animation state of an animated game object -- The value of a variable, for example how much time is left in the current round of a game, or how much energy a player has. - -Some of these things can be automatically synchronized by Mirror. The synchronized creation and destruction of networked game objects is managed by the NetworkManager, and is known as Spawning. You can use the Network Transform component to synchronize the position and rotation of a game object, and you can use the Network Animator component to synchronize the animation of a game object. - -To synchronize other properties of a networked game object, you need to use scripting. See State Synchronization for more information about this. diff --git a/doc/Articles/Guides/GameObjects/toc.yml b/doc/Articles/Guides/GameObjects/toc.yml deleted file mode 100644 index 03c897688..000000000 --- a/doc/Articles/Guides/GameObjects/toc.yml +++ /dev/null @@ -1,14 +0,0 @@ -- name: Overview - href: index.md -- name: Spawn Player - href: SpawnPlayer.md -- name: Spawn Player - Custom - href: SpawnPlayerCustom.md -- name: Spawn Object - href: SpawnObject.md -- name: Spawn Object - Custom - href: SpawnObjectCustom.md -- name: Scene Objects - href: SceneObjects.md -- name: Pickups Drops and Child Objects - href: PickupDropChild.md diff --git a/doc/Articles/Guides/HandlingDisconnecting.md b/doc/Articles/Guides/HandlingDisconnecting.md deleted file mode 100644 index b69433f81..000000000 --- a/doc/Articles/Guides/HandlingDisconnecting.md +++ /dev/null @@ -1,59 +0,0 @@ -# Handling client disconnects - -A networked application should implement disconnection functionality - i.e. take the client to an offline scene, for example, and allow for the opportunity to reconnect. - -_In case of a) the client itself terminating a connection or experiencing a disconnection, or b) the server dropping the client, the networked objects of which the client has authority will be destroyed by the server. This is the intended design; keep in mind [Authority](Authority.md) is a way of deciding who owns an object and has control over it; so these objects must have their ownership transferred to the server and/or other clients, if they are to 'survive' when their owner is disconnected._ - - -## Acting on disconnects - -The NetworkManager has a [OnClientDisconnect](https://mirror-networking.com/docs/api/Mirror.NetworkManager.html#Mirror_NetworkManager_OnClientDisconnect_Mirror_NetworkConnection_) method that can be overridden to allow for custom functionality on the client when that client disconnects. For example: - -```cs -public class CustomNetworkManager : NetworkManager -{ - public override void OnClientDisconnect(NetworkConnection conn) - { - /* - * Execute custom functionality to react, client side, to disconnects here. For example, send the client to an offline scene. - */ - - base.OnClientDisconnect(conn); - } -} -``` - -On the server, the [OnServerDisconnect](https://mirror-networking.com/docs/api/Mirror.NetworkManager.html#Mirror_NetworkManager_OnServerDisconnect_Mirror_NetworkConnection_) method can be overridden to allow for custom functionality when any client disconnects. For example: - -```cs -public class CustomNetworkManager : NetworkManager -{ - public override void OnServerDisconnect(NetworkConnection conn) - { - /* - * Execute custom functionality to react, server side, to disconnects here. - */ - - base.OnServerDisconnect(conn); - } -} -``` - -## Default disconnection strategy - -The NetworkManager has settings to control if inactive clients should be automatically disconnected: - -![NetworkManager automatic disconnection settings](NetworkManager_autoDiscnt_settings.jpg) - - -## Deliberately disconnecting the client - -The preferred way for a client to deliberately disconnect itself is to call the [StopClient()](https://mirror-networking.com/docs/api/Mirror.NetworkManager.html#Mirror_NetworkManager_StopClient) function on the NetworkManager. - -For the purpose of disconnecting all clients, the NetworkServer-class has two suitable methods; [DisconnectAll()](https://mirror-networking.com/docs/api/Mirror.NetworkServer.html#Mirror_NetworkServer_DisconnectAll) and [DisconnectAllConnections()](https://mirror-networking.com/docs/api/Mirror.NetworkServer.html#Mirror_NetworkServer_DisconnectAllConnections). The first disconnects all clients. The other disconnects all clients who are not also host. Use DisconnectAllConnections() if in a host+client scenario. - - -## Disconnects at the transport level - -Mirror's high-level API abstracts away the low-level specificities of the selected transport. These transports may offer their own disconnection methods, or disconnection events, that can be handled to further deal with disconnects on a lower level - if, though unlikely, Mirror's high-level approach do not cover a specific scenario. - diff --git a/doc/Articles/Guides/IDs.md b/doc/Articles/Guides/IDs.md deleted file mode 100644 index 575a9d97c..000000000 --- a/doc/Articles/Guides/IDs.md +++ /dev/null @@ -1,17 +0,0 @@ -# Got ID? - -## Asset Id - -Mirror uses GUID for Asset Ids. Every prefab with a NetworkIdentity component has an Asset Id, which is simply Unity's AssetDatabase.AssetPathToGUID converted to 16 bytes. Mirror needs that to know which prefabs to spawn. - -## Scene Id - -Mirror uses uint for Scene Ids. Every game object with a NetworkIdentity in the scene (hierarchy) is assigned a scene id in OnPostProcessScene. Mirror needs that to distinguish scene objects from each other, because Unity has no unique id for different game objects in the scene. - -## Network Instance Id (a.k.a. NetId) - -Mirror uses uint for NetId. Every NetworkIdentity is assigned a NetId in NetworkIdentity.OnStartServer, or after spawning it. Mirror uses the id when passing messages between client and server to tell which object is the recipient of the message. - -## Connection Id - -Every network connection has a connection id, which is assigned by the low level Transport layer. Connection id 0 is reserved for the local connection when the server is also a client (host) diff --git a/doc/Articles/Guides/NetworkBehaviour.md b/doc/Articles/Guides/NetworkBehaviour.md deleted file mode 100644 index e78e6544d..000000000 --- a/doc/Articles/Guides/NetworkBehaviour.md +++ /dev/null @@ -1,125 +0,0 @@ -# NetworkBehaviour - -**See also in the API Reference.** - -Network Behaviour scripts work with game objects that have a NetworkIdentity component. These scripts can perform high-level API functions such as Commands, ClientRpc's, SyncEvents and SyncVars. - -With the server-authoritative system of Mirror, the server must use the `NetworkServer.Spawn` function to spawn game objects with Network Identity components. Spawning them this way assigns them a `netId` and creates them on clients connected to the server. - -**Note:** This is not a component that you can add to a game object directly. Instead, you must create a script which inherits from `NetworkBehaviour` (instead of the default `MonoBehaviour`), then you can add your script as a component to a game object. - -## Properties -- **isServer** - Returns true if this game object is running on the server, and has been spawned. -- **isClient** - Returns true if this game object is on the client and has been spawned by the server. -- **isLocalPlayer** - Returns true if this game object represents the player created for this client. -- **hasAuthority** - Returns true on the client if this client has [authority](Authority.md) over this game object. It is meaningless in server context. -- **netId** - The unique network ID of this game object. The server assigns this at run time. It is unique for all game objects in that network session. -- **netIdentity** - Returns the NetworkIdentity of this object -- **connectionToServer** - The NetworkConnection associated with the Network Identity component attached to this game object. This is only valid for **player objects** on the client. -- **connectionToClient** - The NetworkConnection associated with the Network Identity component attached to this game object. This is only valid for player game objects on the server. - -NetworkBehaviour scripts have the following features: -- Synchronized variables -- Network callbacks -- Server and client functions -- Sending commands -- Client RPC calls -- Networked events - -![Data Flow Graph](UNetDirections.jpg) - -## Network Callbacks - -There are built-in callback functions which are invoked on NetworkBehaviour scripts for various network events. These are virtual functions on the base class, so you can override them in your own code like this: - -```cs -public class SpaceShip : NetworkBehaviour -{ - public override void OnStartServer() - { - // disable client stuff - } - - public override void OnStartClient() - { - // register client events, enable effects - } -} -``` - -The built-in callbacks are: -- **OnStartServer** called on server when a game object spawns on the server, or when the server is started for game objects in the Scene -- **OnStopServer** called on server when a game object is destroyed on the server, or when the server is stopped for game objects in the Scene -- **OnStartClient** called on clients when the game object spawns on the client, or when the client connects to a server for game objects in the Scene -- **OnStopClient** called on clients when the server destroys the game object -- **OnStartLocalPlayer** called on clients for player game objects on the local client (only) -- **OnStartAuthority** called on clients for behaviours that have authority, based on context and hasAuthority. -- **OnStopAuthority** called on clients for behaviours when authority is removed. - -Note that in a peer-hosted setup, when one of the clients is acting as both host and client, both `OnStartServer` and `OnStartClient` are called on the same game object. Both these functions are useful for actions that are specific to either the client or server, such as suppressing effects on a server, or setting up client-side events. - -## Server and Client functions - -You can tag member functions in NetworkBehaviour scripts with custom attributes to designate them as server-only or client-only functions. `Server` and `ServerCallback` return immediately if the client is not active. Likewise, `Client` and `ClientCallback` return immediately if the server is not active. - -The `Server` and `Client` attributes are for your own custom callback functions. They do not generate compile time errors, but they do emit a warning log message if called in the wrong scope. - -The `ServerCallback` and `ClientCallback` attributes are for built-in callback functions that are called automatically by Mirror. These attributes do not cause a warning to be generated. - -For more information, see [Attributes](Attributes.md). - -## Commands - -To execute code on the server, you must use commands. The high-level API is a server-authoritative system, so commands are the only way for a client to trigger some code on the server. - -Only player game objects can send commands. - -When a client player game object sends a command, that command runs on the corresponding player game object on the server. This routing happens automatically, so it is impossible for a client to send a command for a different player. - -To define a command in your code, you must write a function which has: -- A name that begins with `Cmd` -- The `Command` attribute - -Commands are called just by invoking the function normally on the client. Instead of the command function running on the client, it is automatically invoked on the corresponding player game object on the server. - -Commands are type-safe, have built-in security and routing to the player, and use an efficient serialization mechanism for the arguments to make calling them fast. - -See [Communications](Communications/index.md) and related sections for more information. - -## Client RPC Calls - -Client RPC calls are a way for server game objects to make things happen on client game objects. - -Client RPC calls are not restricted to player game objects, and may be called on any game object with a Network Identity component. - -To define a Client RPC call in your code, you must write a function which: -- Has a name that begins with `Rpc` -- Has the `ClientRpc` attribute - -See [Communications](Communications/index.md) and related sections for more information. - -## Networked Events (Obsolete) - -> **IMPORTANT** SyncEvents have been removed in version 18.0.0, see this [Issue](https://github.com/vis2k/Mirror/pull/2178) for more information - -Networked events are like Client RPC calls, but instead of calling a function on the game object, they trigger Events instead. - -This allows you to write scripts which can register for a callback when an event is triggered. - -To define a Networked event in your code, you must write a function which both: -- Has a name that begins with `Event` -- Has the `SyncEvent` attribute - -You can use events to build powerful networked game systems that can be extended by other scripts. This example shows how an effect script on the client can respond to events generated by a combat script on the server. - -SyncEvent is the base class that Commands and ClientRpc calls are derived from. You can use the SyncEvent attribute on your own functions to make your own event-driven networked game play code. Using SyncEvent, you can extend Mirror’s Multiplayer features to better fit your own programming patterns. - -See [SyncEvents](Sync/SyncEvent.md) for more details. diff --git a/doc/Articles/Guides/NetworkManager_autoDiscnt_settings.jpg b/doc/Articles/Guides/NetworkManager_autoDiscnt_settings.jpg deleted file mode 100644 index ee9449bf0..000000000 Binary files a/doc/Articles/Guides/NetworkManager_autoDiscnt_settings.jpg and /dev/null differ diff --git a/doc/Articles/Guides/Profiler.md b/doc/Articles/Guides/Profiler.md deleted file mode 100644 index 07af550b5..000000000 --- a/doc/Articles/Guides/Profiler.md +++ /dev/null @@ -1,44 +0,0 @@ -# Mirror Network Profiler - -The Mirror Profiler is part of the Mirror Pro suit. -As of this writing it is accessible to our [GitHub Sponsors](https://github.com/sponsors/vis2k). - -![Network Profiler](Profiler.png) - -## Installation - -1. Make sure you have the latest version of Mirror. -2. Become a [GitHub Sponsor](https://github.com/sponsors/vis2k) if you haven't. -3. Visit with the Mirror Networking Discord. In the _information_ channel you will learn how to join the _github_sponsors_ channel. -3. In the _github_sponsors_ channel, pinned messages will guide you on how to download the profiler. -4. Install the unity package in your project. - - -## Usage -1. In Unity menu, click on Open Window -> Analysis -> Mirror Network Profiler. The profiler view will appear -2. You may dock the profiler anywhere you want -3. Start your game in the editor -4. Press "Record" in the profiler -5. Begin your game as host, client or server -6. At the top a chart will show messages coming in and out -7. Click the chart to select a frame -8. The profiler will display information about all the messages sent and received in that frame - -Currently the messages display the following fields: - -* In/Out: Whether the message was received (in) or sent (out) -* Name: Short name of the message, if the message was a `[Command]`, `[ClientRpc]`, `[TargetRpc]` or `[TargetEvent]`, this will display the name of the method, otherwise it will display the name of the message class. -* Bytes: The size of the message in bytes -* Count: In the case of out messages, this will contain how many clients the message was sent to. -* Total Bytes: the size of the message multiplied by the amount of clients the message was sent to (Bytes * Count) -* Channel: The channel used to send the message. As of this writing, we cannot determine the channel for inbound messages, so it displays -1. This will be improved in future versions. Transports can use channels for many purposes such as reliable, unreliable, encrypted, compressed, etc. - -## Optimizing bandwidth - -On most transports, the total bandwidth is dominated by the Count column. This is because each message is packaged in a TCP or UDP frame, which have large headers. - -* If you are sending multiple `[Command]` in the same frame, consider consolidating them into a single `[Command]` call if it makes sense -* If you see a large Count number on a specific message, consider adding a NetworkProximityChecker to your object, so that it is only visible to nearby players instead of the entire world. This can dramatically reduce the Count (and total bytes) depending on your game. -* If you are sending a message every single frame, consider changing your logic so that you only send messages when things change, or use a timer. -* Consider using SyncToOwner feature so that only the owner gets a message when private information such as inventory changes. This can dramatically reduce the Count depending on your game. -* If you have a lot of `[ClientRpc]` calls that synchronize data, consider using `[SyncVar]` and synclists instead. They can reduce the amount of messages because they only send deltas when they change, plus they get batched together, so hundreds of variables can be synchronized with a single message. diff --git a/doc/Articles/Guides/Profiler.png b/doc/Articles/Guides/Profiler.png deleted file mode 100644 index e074b1906..000000000 Binary files a/doc/Articles/Guides/Profiler.png and /dev/null differ diff --git a/doc/Articles/Guides/Serialization.md b/doc/Articles/Guides/Serialization.md deleted file mode 100644 index c8e7fde32..000000000 --- a/doc/Articles/Guides/Serialization.md +++ /dev/null @@ -1,217 +0,0 @@ -# Serialization - -This page goes into depth about Serialization, for the basics see [DataTypes](DataTypes.md). - -Mirror creates Serialize and Deserialize functions for types using Weaver. Weaver edits dll after unity compiles them using Mono.Cecil. This allows mirror to have a lot of complex features like SyncVar, ClientRpc and Message Serialization without the user needed to manually set everything up. - -## Rules and tips - -There are some rules and limits for what Weaver can do. Some features add complexity and are hard to maintain so have not been implemented. These features are not impossible to implement and could be added if there is a high demand for them. - -- You should be able to write Custom Read/Write functions for any type, and Weaver will use. - - This means if there is a unsupported type such as `int[,]` creating a custom Read/Write function will allow you to sync `int[,]` in SyncVar/ClientRpc/etc -- If you have a type that has a field that is not able to be Serialize, you can mark that field with `[System.NonSerialized]` and weaver will ignore it - - -### Unsupported Types - -Some of these types are unsupported due to the complexity they would add, as mentioned above. - -> NOTE: Types in this list can have custom writers. - -- Multidimensional array (eg `int[,]`) -- Types that Inherit from `UnityEngine.Component` -- `UnityEngine.Object` -- `UnityEngine.ScriptableObject` -- Generic Types, eg `MyData` - - Custom Read/Write must declare T, eg `MyData` -- Interfaces -- Types that references themselves - -### Built-in Read Write Functions - -Mirror provides some built-in Read/Write Functions. They can be found in `NetworkReaderExtensions` and `NetworkWriterExtensions`. - -This is a Non-compete list of types that have built-in functions, check the classes above to see the full list. - -- Most [c# primitive types](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/built-in-types) -- Common Unity structs - - Vector3 - - Quaternion - - Rect - - Ray - - Guid -- NetworkIdentity, GameObject, Transform - -#### NetworkIdentity, GameObject, Transform - -The `netId` of the Object is sent over the network, and the Object with the same `netId` is returned on the other side. If the `netId` is zero or an object is not found then `null` will be returned. - - -### Generated Read Write Functions - -Weaver will Generate Read Write functions for - -- Classes or Structs -- Enums -- Arrays - - eg `int[]` and `int[][]` -- ArraySegments - - eg `ArraySegment` -- Lists - - eg `List` - -#### Classes and Structs - -Weaver will Read/Write every public field in the type, unless the field is marked with `[System.NonSerialized]`. If there is an unsupported type in the class or struct Weaver will fail to make Read/Write functions for it. - -> NOTE: Weaver does not check properties - -#### Enums - -Weaver will use the underlying Type of an enum to Read and Write them. By default this is `int`. - -For example `Switch` will use the `byte` Read/Write functions to be Serialized -```cs -public enum Switch : byte -{ - Left, - Middle, - Right, -} -``` - - -#### Collections - -Weaver will Generate writes for the collections listed above. Weaver will use the elements Read/Write function. The element must have a Read/Write function so must be a supported type, or have a custom Read/Write function. - -For example: -- `float[]` is a supported type because Mirror has a built-in Read/Write function for `float`. -- `MyData[]` is a supported type as Weaver is able to generate a Read/Write function for `MyData` -```cs -public struct MyData -{ - public int someValue; - public float anotherValue; -} -``` - -## Adding Custom Read Write functions - -Read Write functions are static methods in the form of: -```cs -public static void WriteMyType(this NetworkWriter writer, MyType value) -{ - // write MyType data here -} - -public static MyType ReadMyType(this NetworkReader reader) -{ - // read MyType data here -} -``` - -It is best practice to make Read/Write functions [extension methods](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods) so they can be called like `writer.WriteMyType(value)`. - -It is a good idea to call them `ReadMyType` and `WriteMyType` so it is obvious what type they are for. However the name of the function doesn't matter, weaver should be able to find it no matter what it is called. - -#### Properties Example - -Weaver wont write properties, but a custom writer can be used to send them over the network. - -This can be useful if you want to have private set for your properties - -```cs -public struct MyData -{ - public int someValue { get; private set; } - public float anotherValue { get; private set; } - - public MyData(int someValue, float anotherValue) - { - this.someValue = someValue; - this.anotherValue = anotherValue; - } -} - -public static class CustomReadWriteFunctions -{ - public static void WriteMyType(this NetworkWriter writer, MyData value) - { - writer.WriteInt32(value.someValue); - writer.WriteSingle(value.anotherValue); - } - - public static MyData ReadMyType(this NetworkReader reader) - { - return new MyData(reader.ReadInt32(), reader.ReadSingle()); - } -} -``` - -#### Unsupported type Example - -Rigidbody is an unsupported type because it inherits from `Component`. But a custom writer can be added so that it is synced using a NetworkIdentity if one is attached. - - -```cs -public struct MyCollision -{ - public Vector3 force; - public Rigidbody rigidbody; -} - -public static class CustomReadWriteFunctions -{ - public static void WriteMyCollision(this NetworkWriter writer, MyCollision value) - { - writer.WriteVector3(value.force); - - NetworkIdentity networkIdentity = value.rigidbody.GetComponent(); - writer.WriteNetworkIdentity(networkIdentity); - } - - public static MyCollision ReadMyCollision(this NetworkReader reader) - { - Vector3 force = reader.ReadVector3(); - - NetworkIdentity networkIdentity = reader.ReadNetworkIdentity(); - Rigidbody rigidBody = networkIdentity != null - ? networkIdentity.GetComponent() - : null; - - return new MyCollision - { - force = force, - rigidbody = rigidBody, - }; - } -} -``` - -Above are functions for `MyCollision`, but instead you could add functions for `Rigidbody` and let weaver would generate a writer for `MyCollision`. -```cs -public static class CustomReadWriteFunctions -{ - public static void WriteRigidbody(this NetworkWriter writer, Rigidbody rigidbody) - { - NetworkIdentity networkIdentity = rigidbody.GetComponent(); - writer.WriteNetworkIdentity(networkIdentity); - } - - public static Rigidbody ReadRigidbody(this NetworkReader reader) - { - NetworkIdentity networkIdentity = reader.ReadNetworkIdentity(); - Rigidbody rigidBody = networkIdentity != null - ? networkIdentity.GetComponent() - : null; - - return rigidBody; - } -} -``` - -## Debugging - -You can use tools like [dnSpy](https://github.com/0xd4d/dnSpy) to view the complied code after Weaver has altered it. This can help to understand and debug what Mirror and Weaver does. diff --git a/doc/Articles/Guides/Sync/SyncDictionary.md b/doc/Articles/Guides/Sync/SyncDictionary.md deleted file mode 100644 index 4f3936d40..000000000 --- a/doc/Articles/Guides/Sync/SyncDictionary.md +++ /dev/null @@ -1,65 +0,0 @@ -# SyncDictionary - -A SyncDictionary is an associative array containing an unordered list of key, value pairs. Keys and values can be any [supported mirror type](../DataTypes.md). By default we use .Net [Dictionary](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netcore-3.1) which may impose additional constraints on the keys and values. - -SyncDictionary works much like [SyncLists](SyncLists.md): when you make a change on the server the change is propagated to all clients and the Callback is called. Only deltas are transmitted. - -## Usage - -Add a field to your NetworkBehaviour class fo type `SyncDictionary`. For example: - -> Note that by the time you subscribe to the callback, the dictionary will already be initialized, so you will not get a call for the initial data, only updates.

- ->Note SyncDictionaries must be initialized in the constructor, not in Startxxx(). You can make them readonly to ensure correct usage. - -## Simple Example - -```cs -using UnityEngine; -using Mirror; - -public struct Item -{ - public string name; - public int hitPoints; - public int durability; -} - -public class ExamplePlayer : NetworkBehaviour -{ - public readonly SyncDictionary Equipment = new SyncDictionary(); - - public override void OnStartServer() - { - Equipment.Add("head", new Item { name = "Helmet", hitPoints = 10, durability = 20 }); - Equipment.Add("body", new Item { name = "Epic Armor", hitPoints = 50, durability = 50 }); - Equipment.Add("feet", new Item { name = "Sneakers", hitPoints = 3, durability = 40 }); - Equipment.Add("hands", new Item { name = "Sword", hitPoints = 30, durability = 15 }); - } - - public override void OnStartClient() - { - // Equipment is already populated with anything the server set up - // but we can subscribe to the callback in case it is updated later on - Equipment.Callback += OnEquipmentChange; - } - - void OnEquipmentChange(SyncDictionary.Operation op, string key, Item item) - { - // equipment changed, perhaps update the gameobject - Debug.Log(op + " - " + key); - } -} -``` - -By default, SyncDictionary uses a [Dictionary](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netcore-3.1) to store it's data. If you want to use a different `IDictionary` implementation such as [SortedList](https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist?view=netcore-3.1) or [SortedDictionary](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sorteddictionary-2?view=netcore-3.1), then use `SyncIDictionary` and pass the dictionary instance you want it to use. For example: - -```cs -public class ExamplePlayer : NetworkBehaviour -{ - public readonly SyncIDictionary Equipment = - new SyncIDictionary(new SortedList()); -} - -``` - diff --git a/doc/Articles/Guides/Sync/SyncEvent.md b/doc/Articles/Guides/Sync/SyncEvent.md deleted file mode 100644 index c3af04cfb..000000000 --- a/doc/Articles/Guides/Sync/SyncEvent.md +++ /dev/null @@ -1,45 +0,0 @@ -# SyncEvent (Obsolete) - -> **IMPORTANT** SyncEvents have been removed in version 18.0.0, see this [Issue](https://github.com/vis2k/Mirror/pull/2178) for more information - -This is an attribute that can be put on events in NetworkBehaviour classes to allow them to be invoked on client when the event is called on the server. - -SyncEvent events are called by user code on the server, and then invoked on corresponding client objects on clients connected to the server. The arguments to the Event call are serialized across the network, so that the client event is invoked with the same values as the method on the server. These events must begin with the prefix "Event". - -```cs -using UnityEngine; -using Mirror; - -public class DamageClass : NetworkBehaviour -{ - public delegate void TakeDamageDelegate(int amount, float dir); - - [SyncEvent] - public event TakeDamageDelegate EventTakeDamage; - - [Command] - public void CmdDoMe(int val) - { - EventTakeDamage(val, 1.0f); - } -} - -public class Other : NetworkBehaviour -{ - public DamageClass damager; - int health = 100; - - void Start() - { - if (NetworkClient.active) - damager.EventTakeDamage += TakeDamage; - } - - public void TakeDamage(int amount, float dir) - { - health -= amount; - } -} -``` - -SyncEvents allow networked actions to be propagated to other scripts attached to the object. In the example above, the Other class registers for the TakeDamage event on the DamageClass. When the event happens on the DamageClass on the server, the TakeDamage() method will be invoked on the Other class on the client object. This allows modular network aware systems to be created, that can be extended by new scripts that respond to the events generated by them. diff --git a/doc/Articles/Guides/Sync/SyncHashSet.md b/doc/Articles/Guides/Sync/SyncHashSet.md deleted file mode 100644 index 3f669b295..000000000 --- a/doc/Articles/Guides/Sync/SyncHashSet.md +++ /dev/null @@ -1,69 +0,0 @@ -# SyncHashSet - -`SyncHashSet` are sets similar to C\# [HashSet\](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1) that synchronize their contents from the server to the clients. - -A SyncHashSet can contain any [supported mirror type](../DataTypes.md) - -## Usage - -Add a SyncHashSet field to your NetworkBehaviour class. For example: - -```cs - -public class Player : NetworkBehaviour { - - [SerializeField] - readonly SyncHashSet skills = new SyncHashSet(); - - int skillPoints = 10; - - [Command] - public void CmdLearnSkill(string skillName) - { - if (skillPoints > 1) - { - skillPoints--; - - skills.Add(skillName); - } - } -} -``` - -You can also detect when a SyncHashSet changes. This is useful for refreshing your character in the client or determining when you need to update your database. - -Subscribe to the Callback event typically during `Start`, `OnClientStart` or `OnServerStart` for that. - -> Note that by the time you subscribe, the set will already be initialized, so you will not get a call for the initial data, only updates.

->Note SyncSets must be initialized in the constructor, not in Startxxx(). You can make them readonly to ensure correct usage. - -```cs -public class Player : NetworkBehaviour -{ - [SerializeField] - public readonly SyncHashSet buffs = new SyncHashSet(); - - // this will add the delegate on the client. - // Use OnStartServer instead if you want it on the server - public override void OnStartClient() - { - buffs.Callback += OnBuffsChanged; - } - - void OnBuffsChanged(SyncHashSet.Operation op, string buff) - { - switch (op) - { - case SyncHashSet.Operation.OP_ADD: - // we added a buff, draw an icon on the character - break; - case SyncHashSet.Operation.OP_CLEAR: - // clear all buffs from the character - break; - case SyncHashSet.Operation.OP_REMOVE: - // We removed a buff from the character - break; - } - } -} -``` diff --git a/doc/Articles/Guides/Sync/SyncLists.md b/doc/Articles/Guides/Sync/SyncLists.md deleted file mode 100644 index 1f1d7e444..000000000 --- a/doc/Articles/Guides/Sync/SyncLists.md +++ /dev/null @@ -1,106 +0,0 @@ -# SyncLists - -SyncLists are array based lists similar to C\# [List\](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.7.2) that synchronize their contents from the server to the clients. - -A SyncList can contain any [supported mirror type](../DataTypes.md). - -## Differences with HLAPI - -HLAPI also supports SyncLists, but we have redesigned them to make them more efficient and easier to use. Some of the key differences include: -- In HLAPI, SyncLists were synchronized immediately when they changed. If you add 10 elements, that means 10 separate messages. Mirror synchronizes SyncLists with the SyncVars. The 10 elements and other SyncVars are batched together into a single message. Mirror also respects the sync interval when synchronizing lists. -- In HLAPI if you want a list of structs, you have to use `SyncListStruct`, we changed it to just `SyncList` -- In HLAPI the Callback is a delegate. In Mirror we changed it to an event, so that you can add many subscribers. -- In HLAPI the Callback tells you the operation and index. In Mirror, the callback also receives an item. We made this change so that we could tell what item was removed. -- In HLAPI you must create a class that inherits from SyncList. In Mirror you can just use SyncList directly (starting with version 20.0.0) - -## Usage - -Add a SyncList field to your NetworkBehaviour class. For example: - -```cs -public struct Item -{ - public string name; - public int amount; - public Color32 color; -} - -public class Player : NetworkBehaviour -{ - readonly SyncList inventory = new SyncList(); - - public int coins = 100; - - [Command] - public void CmdPurchase(string itemName) - { - if (coins > 10) - { - coins -= 10; - Item item = new Item - { - name = "Sword", - amount = 3, - color = new Color32(125, 125, 125, 255) - }; - - // during next synchronization, all clients will see the item - inventory.Add(item); - } - } -} -``` - -You can also detect when a SyncList changes in the client or server. This is useful for refreshing your character when you add equipment or determining when you need to update your database. Subscribe to the Callback event typically during `Start`, `OnClientStart`, or `OnServerStart` for that. - - -> Note that by the time you subscribe, the list will already be initialized, so you will not get a call for the initial data, only updates.

-> Note SyncLists must be initialized in the constructor, not in Startxxx(). You can make them readonly to ensure correct usage. - -```cs -class Player : NetworkBehaviour { - - readonly SyncList inventory = new SyncList(); - - // this will add the delegates on both server and client. - // Use OnStartClient instead if you just want the client to act upon updates - void Start() - { - inventory.Callback += OnInventoryUpdated; - } - - void OnInventoryUpdated(SyncList.Operation op, int index, Item oldItem, Item newItem) - { - switch (op) - { - case SyncList.Operation.OP_ADD: - // index is where it got added in the list - // item is the new item - break; - case SyncList.Operation.OP_CLEAR: - // list got cleared - break; - case SyncList.Operation.OP_INSERT: - // index is where it got added in the list - // item is the new item - break; - case SyncList.Operation.OP_REMOVEAT: - // index is where it got removed in the list - // item is the item that was removed - break; - case SyncList.Operation.OP_SET: - // index is the index of the item that was updated - // item is the previous item - break; - } - } -} -``` - -By default, SyncList uses a List to store it's data. If you want to use a different list implementation, pass it to the constructor of of SyncList. For example: - -```cs -class Player : NetworkBehaviour { - public SyncList inventory = new SyncList(new MyItemList()); -} -``` diff --git a/doc/Articles/Guides/Sync/SyncSortedSet.md b/doc/Articles/Guides/Sync/SyncSortedSet.md deleted file mode 100644 index 3fbef42d6..000000000 --- a/doc/Articles/Guides/Sync/SyncSortedSet.md +++ /dev/null @@ -1,65 +0,0 @@ -# SyncSortedSet - -`SyncSortedSet` are sets similar to C\# [SortedSet\](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedset-1) that synchronize their contents from the server to the clients. - -Unlike SyncHashSets, all elements in a SyncSortedSet are sorted when they are inserted. Please note this has some performance implications. - -A SyncSortedSet can contain any [supported mirror type](../DataTypes.md) - -## Usage - -Add a SyncSortedSet field to your NetworkBehaviour class. For example: - -```cs -class Player : NetworkBehaviour { - readonly SyncSortedSet skills = new SyncSortedSet(); - - int skillPoints = 10; - - [Command] - public void CmdLearnSkill(string skillName) - { - if (skillPoints > 1) - { - skillPoints--; - - skills.Add(skillName); - } - } -} -``` - -You can also detect when a SyncSortedSet changes. This is useful for refreshing your character in the client or determining when you need to update your database. Subscribe to the Callback event typically during `Start`, `OnClientStart` or `OnServerStart` for that. - -> Note that by the time you subscribe, the set will already be initialized, so you will not get a call for the initial data, only updates.

-> Note SyncSets must be initialized in the constructor, not in Startxxx(). You can make them readonly to ensure correct usage. - -```cs -class Player : NetworkBehaviour -{ - readonly SyncSortedSet buffs = new SyncSortedSet(); - - // this will add the delegate on the client. - // Use OnStartServer instead if you want it on the server - public override void OnStartClient() - { - buffs.Callback += OnBuffsChanged; - } - - void OnBuffsChanged(SyncSortedSet.Operation op, string buff) - { - switch (op) - { - case SyncSortedSet.Operation.OP_ADD: - // we added a buff, draw an icon on the character - break; - case SyncSortedSet.Operation.OP_CLEAR: - // clear all buffs from the character - break; - case SyncSortedSet.Operation.OP_REMOVE: - // We removed a buff from the character - break; - } - } -} -``` diff --git a/doc/Articles/Guides/Sync/SyncVarHook.md b/doc/Articles/Guides/Sync/SyncVarHook.md deleted file mode 100644 index e9f9b7483..000000000 --- a/doc/Articles/Guides/Sync/SyncVarHook.md +++ /dev/null @@ -1,73 +0,0 @@ -# SyncVar Hook - -The hook attribute can be used to specify a function to be called when the SyncVar changes value on the client. -- The Hook method must have two parameters of the same type as the SyncVar property. One for the old value, one for the new value. -- The Hook is always called after the property value is set. You don't need to set it yourself. -- The Hook only fires for changed values, and changing a value in the inspector will not trigger an update. -- As of version 11.1.4 (March 2020) and later, hooks can be virtual methods and overriden in a derived class. - -Below is a simple example of assigning a random color to each player when they're spawned on the server. All clients will see all players in the correct colors, even if they join later. - -> Note: The signature for hook methods was changed in version 9.0 (Feb 2020) to having 2 parameters (old and new values). If you're on an older version, hook methods just have one parameter (new value). - -```cs -using UnityEngine; -using Mirror; - -public class PlayerController : NetworkBehaviour -{ - [SyncVar(hook = nameof(SetColor))] - Color playerColor = Color.black; - - // Unity makes a clone of the Material every time GetComponent().material is used. - // Cache it here and Destroy it in OnDestroy to prevent a memory leak. - Material cachedMaterial; - - public override void OnStartServer() - { - base.OnStartServer(); - playerColor = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f); - } - - void SetColor(Color oldColor, Color newColor) - { - if (cachedMaterial == null) - cachedMaterial = GetComponent().material; - - cachedMaterial.color = newColor; - } - - void OnDestroy() - { - Destroy(cachedMaterial); - } -} -``` - - -## Hook call order - -Hooks are invoked in the order the syncvars are defined in the file. - - -```cs -public class MyBehaviour : NetworkBehaviour -{ - [SyncVar] - int X; - - [SyncVar(hook = nameof(Hook1))] - int Y; - - [SyncVar(hook = nameof(Hook2))] - int Z; -} -``` - -if X, Y, and Z are all set on the server at the same time then the call order will be: - -1) X value is set -2) Y value is set -3) Hook1 is called -4) Z value is set -5) Hook2 is called diff --git a/doc/Articles/Guides/Sync/SyncVars.md b/doc/Articles/Guides/Sync/SyncVars.md deleted file mode 100644 index d3c8d7499..000000000 --- a/doc/Articles/Guides/Sync/SyncVars.md +++ /dev/null @@ -1,78 +0,0 @@ -# SyncVars - -SyncVars are properties of classes that inherit from NetworkBehaviour, which are synchronized from the server to clients. When a game object is spawned, or a new player joins a game in progress, they are sent the latest state of all SyncVars on networked objects that are visible to them. Use the `SyncVar` custom attribute to specify which variables in your script you want to synchronize. - -The state of SyncVars is applied to game objects on clients before `OnStartClient()` is called, so the state of the object is always up-to-date inside `OnStartClient()`. - -SyncVars can use any [type supported by Mirror](../DataTypes.md). You can have up to 64 SyncVars on a single NetworkBehaviour script, including SyncLists (see next section, below). - -The server automatically sends SyncVar updates when the value of a SyncVar changes, so you do not need to track when they change or send information about the changes yourself. Changing a value in the inspector will not trigger an update. - -> The [SyncVar hook](SyncVarHook.md) attribute can be used to specify a method to be called when the SyncVar changes value on the client. - -## SyncVar Example -Let's say we have a networked object with a script called Enemy: - -``` cs -public class Enemy : NetworkBehaviour -{ - [SyncVar] - public int health = 100; - - void OnMouseUp() - { - NetworkIdentity ni = NetworkClient.connection.identity; - PlayerController pc = ni.GetComponent(); - pc.currentTarget = gameObject; - } -} -``` - -The `PlayerController` might look like this: - -``` cs -public class PlayerController : NetworkBehaviour -{ - public GameObject currentTarget; - - void Update() - { - if (isLocalPlayer) - if (currentTarget != null) - if (currentTarget.tag == "Enemy") - if (Input.GetKeyDown(KeyCode.X)) - CmdShoot(currentTarget); - } - - [Command] - public void CmdShoot(GameObject enemy) - { - // Do your own shot validation here because this runs on the server - enemy.GetComponent().health -= 5; - } -} -``` - -In this example, when a Player clicks on an Enemy, the networked enemy game object is assigned to `PlayerController.currentTarget`. When the player presses X, with a correct target selected, that target is passed through a Command, which runs on the server, to decrement the `health` SyncVar. All clients will be updated with that new value. You can then have a UI on the enemy to show the current value. - -## Class inheritance - -SyncVars work with class inheritance. Consider this example: - -```cs -class Pet : NetworkBehaviour -{ - [SyncVar] - String name; -} - -class Cat : Pet -{ - [SyncVar] - public Color32 color; -} -``` - -You can attach the Cat component to your cat prefab, and it will synchronize both it's `name` and `color`. - -> **Warning** Both `Cat` and `Pet` should be in the same assembly. If they are in separate assemblies, make sure not to change `name` from inside `Cat` directly, add a method to `Pet` instead. diff --git a/doc/Articles/Guides/Sync/index.md b/doc/Articles/Guides/Sync/index.md deleted file mode 100644 index bebf37f06..000000000 --- a/doc/Articles/Guides/Sync/index.md +++ /dev/null @@ -1,216 +0,0 @@ -# State Synchronization - -State synchronization refers to the synchronization of values such as integers, floating point numbers, strings and boolean values belonging to scripts. - -State synchronization is done from the Server to remote clients. The local client does not have data serialized to it. It does not need it, because it shares the Scene with the server. However, SyncVar hooks are called on local clients. - -Data is not synchronized in the opposite direction - from remote clients to the server. To do this, you need to use Commands. - -Changed values are synced in the next LateUpdate as long as it has been atleast `syncInterval` since the last sync. -- [SyncVars](SyncVars.md) - SyncVars are variables of scripts that inherit from NetworkBehaviour, which are synchronized from the server to clients. -- [SyncEvents (Obsolete)](SyncEvent.md) - SyncEvents are networked events like ClientRpc’s, but instead of calling a function on the game object, they trigger Events instead. - **IMPORTANT:** removed in version 18.0.0, see this [Issue](https://github.com/vis2k/Mirror/pull/2178) for more information. -- [SyncLists](SyncLists.md) - SyncLists contain lists of values and synchronize data from servers to clients. -- [SyncDictionary](SyncDictionary.md) - A SyncDictionary is an associative array containing an unordered list of key, value pairs. -- [SyncHashSet](SyncHashSet.md) - An unordered set of values that do not repeat. -- [SyncSortedSet](SyncSortedSet.md) - A sorted set of values that do not repeat. - -## Sync To Owner - -It is often the case when you don't want some player data visible to other players. In the inspector change the "Network Sync Mode" from "Observers" (default) to "Owner" to let Mirror know to synchronize the data only with the owning client. - -For example, suppose you are making an inventory system. Suppose player A,B and C are in the same area. There will be a total of 12 objects in the entire network: - -* Client A has Player A (himself), Player B and Player C -* Client B has Player A , Player B (himself) and Player C -* Client C has Player A , Player B and Player C (himself) -* Server has Player A, Player B, Player C - -each one of them would have an Inventory component - -Suppose Player A picks up some loot. The server adds the loot to Player's A inventory, which would have a [SyncLists](SyncLists.md) of Items. - -By default, Mirror now has to synchronize player A's inventory everywhere, that means sending an update message to client A, client B and client C, because they all have a copy of Player A. This is wasteful, Client B and Client C do not need to know about Player's A inventory, they never see it on screen. It is also a security problem, someone could hack the client and display other people's inventory and use it to their advantage. - -If you set the "Network Sync Mode" in the Inventory component to "Owner", then Player A's inventory will only be synchronized with Client A. - -Now, suppose instead of 3 people you have 50 people in an area and one of them picks up loot. It means that instead of sending 50 messages to 50 different clients, you would only send 1. This can have a big impact in bandwith in your game. - -Other typical use cases include quests, player's hand in a card game, skills, experience, or any other data you don't need to share with other players. - -## Advanced State Synchronization - -In most cases, the use of SyncVars is enough for your game scripts to serialize their state to clients. However in some cases you might require more complex serialization code. This page is only relevant for advanced developers who need customized synchronization solutions that go beyond Mirror’s normal SyncVar feature. - -## Custom Serialization Functions - -To perform your own custom serialization, you can implement virtual functions on NetworkBehaviour to be used for SyncVar serialization. These functions are: - -```cs -public virtual bool OnSerialize(NetworkWriter writer, bool initialState); -``` - -```cs -public virtual void OnDeserialize(NetworkReader reader, bool initialState); -``` - -Use the `initialState` flag to differentiate between the first time a game object is serialized and when incremental updates can be sent. The first time a game object is sent to a client, it must include a full state snapshot, but subsequent updates can save on bandwidth by including only incremental changes. - - -The `OnSerialize` function should return true to indicate that an update should be sent. If it returns true, the dirty bits for that script are set to zero. If it returns false, the dirty bits are not changed. This allows multiple changes to a script to be accumulated over time and sent when the system is ready, instead of every frame. - -The `OnSerialize` function is only called for `initialState` or when the `NetworkBehaviour` is dirty. A `NetworkBehaviour` will only be dirty if a `SyncVar` or `SyncObject` (e.g. `SyncList`) has changed since the last OnSerialize call. After data has been sent the `NetworkBehaviour` will not be dirty again until the next `syncInterval` (set in the inspector). A `NetworkBehaviour` can also be marked as dirty by manually calling `SetDirtyBit` (this does not bypass the syncInterval limit). - -Although this works, it is usually better to let Mirror generate these methods and provide [custom serializers](../DataTypes.md) for your specific field. - -## Serialization Flow - -Game objects with the Network Identity component attached can have multiple scripts derived from `NetworkBehaviour`. The flow for serializing these game objects is: - -On the server: -- Each `NetworkBehaviour` has a dirty mask. This mask is available inside `OnSerialize` as `syncVarDirtyBits` -- Each SyncVar in a `NetworkBehaviour` script is assigned a bit in the dirty mask. -- Changing the value of SyncVars causes the bit for that SyncVar to be set in the dirty mask -- Alternatively, calling `SetDirtyBit` writes directly to the dirty mask -- NetworkIdentity game objects are checked on the server as part of it’s update loop -- If any `NetworkBehaviours` on a `NetworkIdentity` are dirty, then an `UpdateVars` packet is created for that game object -- The `UpdateVars` packet is populated by calling `OnSerialize` on each `NetworkBehaviour` on the game object -- `NetworkBehaviours` that are not dirty write a zero to the packet for their dirty bits -- `NetworkBehaviours` that are dirty write their dirty mask, then the values for the SyncVars that have changed -- If `OnSerialize` returns true for a `NetworkBehaviour`, the dirty mask is reset for that `NetworkBehaviour` so it does not send again until its value changes. -- The `UpdateVars` packet is sent to ready clients that are observing the game object - -On the client: -- an `UpdateVars packet` is received for a game object -- The `OnDeserialize` function is called for each `NetworkBehaviour` script on the game object -- Each `NetworkBehaviour` script on the game object reads a dirty mask. -- If the dirty mask for a `NetworkBehaviour` is zero, the `OnDeserialize` function returns without reading any more -- If the dirty mask is non-zero value, then the `OnDeserialize` function reads the values for the SyncVars that correspond to the dirty bits that are set -- If there are SyncVar hook functions, those are invoked with the value read from the stream. - -So for this script: - -```cs -public class data : NetworkBehaviour -{ - [SyncVar(hook = nameof(OnInt1Changed))] - public int int1 = 66; - - [SyncVar] - public int int2 = 23487; - - [SyncVar] - public string MyString = "Example string"; - - void OnInt1Changed(int oldValue, int newValue) - { - // do something here - } -} -``` - -The following sample shows the code that is generated by Mirror for the `SerializeSyncVars` function which is called inside `NetworkBehaviour.OnSerialize`: - -```cs -public override bool SerializeSyncVars(NetworkWriter writer, bool initialState) -{ - // Write any SyncVars in base class - bool written = base.SerializeSyncVars(writer, forceAll); - - if (initialState) - { - // The first time a game object is sent to a client, send all the data (and no dirty bits) - writer.WritePackedUInt32((uint)this.int1); - writer.WritePackedUInt32((uint)this.int2); - writer.Write(this.MyString); - return true; - } - else - { - // Writes which SyncVars have changed - writer.WritePackedUInt64(base.syncVarDirtyBits); - - if ((base.get_syncVarDirtyBits() & 1u) != 0u) - { - writer.WritePackedUInt32((uint)this.int1); - written = true; - } - - if ((base.get_syncVarDirtyBits() & 2u) != 0u) - { - writer.WritePackedUInt32((uint)this.int2); - written = true; - } - - if ((base.get_syncVarDirtyBits() & 4u) != 0u) - { - writer.Write(this.MyString); - written = true; - } - - return written; - } -} -``` - - -The following sample shows the code that is generated by Mirror for the `DeserializeSyncVars` function which is called inside `NetworkBehaviour.OnDeserialize`: - -```cs -public override void DeserializeSyncVars(NetworkReader reader, bool initialState) -{ - // Read any SyncVars in base class - base.DeserializeSyncVars(reader, initialState); - - if (initialState) - { - // The first time a game object is sent to a client, read all the data (and no dirty bits) - int oldInt1 = this.int1; - this.int1 = (int)reader.ReadPackedUInt32(); - // if old and new values are not equal, call hook - if (!base.SyncVarEqual(num, ref this.int1)) - { - this.OnInt1Changed(num, this.int1); - } - - this.int2 = (int)reader.ReadPackedUInt32(); - this.MyString = reader.ReadString(); - return; - } - - int dirtySyncVars = (int)reader.ReadPackedUInt32(); - // is 1st SyncVar dirty - if ((dirtySyncVars & 1) != 0) - { - int oldInt1 = this.int1; - this.int1 = (int)reader.ReadPackedUInt32(); - // if old and new values are not equal, call hook - if (!base.SyncVarEqual(num, ref this.int1)) - { - this.OnInt1Changed(num, this.int1); - } - } - - // is 2nd SyncVar dirty - if ((dirtySyncVars & 2) != 0) - { - this.int2 = (int)reader.ReadPackedUInt32(); - } - - // is 3rd SyncVar dirty - if ((dirtySyncVars & 4) != 0) - { - this.MyString = reader.ReadString(); - } -} -``` - -If a `NetworkBehaviour` has a base class that also has serialization functions, the base class functions should also be called. - -Note that the `UpdateVar` packets created for game object state updates may be aggregated in buffers before being sent to the client, so a single transport layer packet may contain updates for multiple game objects. diff --git a/doc/Articles/Guides/Sync/toc.yml b/doc/Articles/Guides/Sync/toc.yml deleted file mode 100644 index 2f6f67f6e..000000000 --- a/doc/Articles/Guides/Sync/toc.yml +++ /dev/null @@ -1,16 +0,0 @@ -- name: Overview - href: index.md -- name: SyncVars - href: SyncVars.md -- name: SyncVar Hooks - href: SyncVarHook.md -- name: SyncEvents - href: SyncEvent.md -- name: SyncLists - href: SyncLists.md -- name: SyncDictionary - href: SyncDictionary.md -- name: SyncHashSet - href: SyncHashSet.md -- name: SyncSortedSet - href: SyncSortedSet.md \ No newline at end of file diff --git a/doc/Articles/Guides/UNetDirections.jpg b/doc/Articles/Guides/UNetDirections.jpg deleted file mode 100644 index 9f8889701..000000000 Binary files a/doc/Articles/Guides/UNetDirections.jpg and /dev/null differ diff --git a/doc/Articles/Guides/Visibility.md b/doc/Articles/Guides/Visibility.md deleted file mode 100644 index 8f99cb8fb..000000000 --- a/doc/Articles/Guides/Visibility.md +++ /dev/null @@ -1,71 +0,0 @@ -# Network Visibility - -Multiplayer games use the concept of network visibility to determine which players can see which game objects at any given time during game play. In a game that has a moving viewpoint and moving game objects, it’s common that players cannot see everything that is happening in the game at once. - -If a particular player, at a certain point in time during game play, cannot see most of the other players, non-player characters, or other moving or interactive things in your game, there is usually no need for the server to send information about those things to the player’s client. - -This can benefit your game in two ways: -- It reduces the amount of data sent across the network between players. This can help improve the responsiveness of your game, and reduce bandwidth use. The bigger and more complex your multiplayer game, the more important this issue is. -- It also helps prevent some cheating. Since a player client does not have information about things that can’t be seen, a hack on that player’s computer cannot reveal the information. - -The idea of “visibility” in the context of networking doesn’t necessarily relate to whether game objects are directly visible on-screen. Instead, it relates to whether data should or shouldn’t be sent about the game object in question to a particular client. Put simply, if a client can’t ‘see’ an game object, it does not need to be sent information about that game object across the network. Ideally you want to limit the amount of data you are sending across the network to only what is necessary, because sending large amounts of unnecessary data across the network can cause network performance problems. - -However, it can be also be resource intensive or complex to determine accurately whether a game object truly visible to a given player, so it’s often a good idea to use a more simple calculation for the purposes of determining whether a player should be sent networked data about it - i.e. whether it is ‘Network Visible’. The balance you want to achieve when considering this is between the cost of the complexity of the calculation for determining the visibility, and the cost of sending more information than necessary over the network. A very simple way to calculate this is a distance (proximity) check, and Mirror provides a built-in component for this purpose. - -## Network Proximity Checker Component - -Mirror’s [Network Proximity Checker](../Components/NetworkProximityChecker.md) component is simplest way to implement network visibility for players. It works in conjunction with the physics system to determine whether game objects are close enough (that is, “visible” for the purposes of sending network messages in your multiplayer game). - -## Network Scene Checker Component - -Mirror's [Network Scene Checker](../Components/NetworkSceneChecker.md) component can be used to isolate players and networked objects on the server in additive scene instances. - -## Network Visibility on Remote Clients - -When a player on a remote client joins a networked game, only game objects that are network-visible to the player will be spawned on that remote client. This means that even if the player enters a large world with many networked game objects, the game can start quickly because it does not need to spawn every game object that exists in the world. Note that this applies to networked game objects in your Scene, but does not affect the loading of Assets. Unity still takes time to load the Assets for registered Prefabs and Scene game objects. - -When a player moves within the world, the set of network-visible game objects changes. The player’s client is told about these changes as they happen. The `ObjectHide` message is sent to clients when a game object becomes no longer network-visible. By default, Mirror destroys the game object when it receives this message. When a game object becomes visible, the client receives an `ObjectSpawn` message, as if Mirror has spawned the game object for the first time. By default, the game object is instantiated like any other spawned game object. - -## Network Visibility on the Host - -The host shares the same Scene as the server, because it acts as both the server and the client to the player hosting the game. For this reason, it cannot destroy game objects that are not visible to the local player. - -Instead, there is the virtual method OnSetLocalVisibility in the NetworkVisibility class that is invoked. This method is invoked on all scripts that inherit from `NetworkVisibility` on game objects that change visibility state on the host. - -The default implementation of `OnSetLocalVisibility` disables or enables all renderer components on the game object. If you want to customize this implementation, you can override the method in your script, and provide a new behavior for how the host (and therefore the local client) should respond when a game object becomes network-visible or invisible (such as disabling HUD elements or renderers). - -## Customizing Network Visibility - -Sometimes you might want to use other kinds of visibility check, such as grid-based rules, line-of-sight tests, navigation path tests, or any other type of test that suits your game. - -To do this, you can create your own custom Network Observer from a [script template](../General/ScriptTemplates.md) via the Assets menu by clicking Create -> Mirror -> Network Observer. - -It may be helpful to understand how the Network Proximity Checker works. - -The Network Proximity Checker is implemented using the public visibility interface of Mirror’s HLAPI. Using this same interface, you can implement any kind of visibility rules you desire. Each `NetworkIdentity` keeps track of the set of players that it is visible to. The players that a NetworkIdentity game object is visible to are called the “observers” of the NetworkIdentity. - -The Network Proximity Checker calls the `RebuildObservers` method on the Network Identity component at a fixed interval (set using the “Vis Update Interval” value in the inspector), so that the set of network-visible game objects for each player is updated as they move around. - -In the `NetworkVisibility` class (which your custom observer scripts inherit from), there are some virtual functions for determining visibility. These are: -- **OnCheckObserver** - This method is called on the server, on each networked game object when a new player enters the game. If it returns true, that player is added to the object’s observers. The Network Proximity Checker does a simple distance check in its implementation of this function, and uses `Physics.OverlapSphereNonAlloc` to find the players that are within the visibility distance for this object. -- **OnRebuildObservers** - This method is called on the server when `RebuildObservers` is invoked. This method expects the set of observers to be populated with the players that can see the object. The NetworkServer then handles sending `ObjectHide` and `ObjectSpawn` messages based on the differences between the old and new visibility sets. -- **OnSetHostVisibility** - This method is called on the server by the visibility system for objects on a host. Objects on a host (with a local client) cannot be disabled or destroyed when they are not visibile to the local client. So this function is called to allow custom code to hide these objects. A typical implementation will disable renderer components on the object. This is only called on local clients on a host. - -You can check whether any given networked game object is a player by checking if its `NetworkIdentity` has a valid connectionToClient. For example: - -``` cs -int hitCount = Physics.OverlapSphereNonAlloc(transform.position, visRange, hitsBuffer3D, castLayers); - -for (int i = 0; i < hitCount; i++) -{ - Collider hit = hitsBuffer3D[i]; - - NetworkIdentity identity = hit.GetComponent(); - - if (identity != null && identity.connectionToClient != null) - observers.Add(identity.connectionToClient); -} -``` diff --git a/doc/Articles/Guides/index.md b/doc/Articles/Guides/index.md deleted file mode 100644 index d2b39ee6a..000000000 --- a/doc/Articles/Guides/index.md +++ /dev/null @@ -1,22 +0,0 @@ -# Networking Concepts Overview - -## High level scripting API - -Mirror’s networking has a “high-level” scripting API (which we’ll refer to as the HLAPI). Using this means you get access to commands which cover most of the common requirements for multiuser games without needing to worry about the “lower level” implementation details. The HLAPI allows you to: -- Control the networked state of the game using a “Network Manager”. -- Operate “client hosted” games, where the host is also a player client. -- Serialize data using a general-purpose serializer. -- Send and receive network messages. -- Send networked commands from clients to servers. -- Make remote procedure calls (RPCs) from servers to clients. -- Send networked events from servers to clients. - -## Engine and Editor integration - -Mirror’s networking is integrated into the engine and the editor, allowing you to work with components and visual aids to build your multiplayer game. It provides: -- A NetworkIdentity component for networked objects. -- A NetworkBehaviour for networked scripts. -- Configurable automatic synchronization of object transforms. -- Automatic synchronization of script variables. -- Support for placing networked objects in Unity scenes. -- Network components diff --git a/doc/Articles/Guides/toc.yml b/doc/Articles/Guides/toc.yml deleted file mode 100644 index 9bfd1c088..000000000 --- a/doc/Articles/Guides/toc.yml +++ /dev/null @@ -1,34 +0,0 @@ -- name: Overview - href: index.md -- name: Authority - href: Authority.md -- name: About IDs - href: IDs.md -- name: Network Profiler - href: Profiler.md -- name: Attributes - href: Attributes.md -- name: Network Behaviour - href: NetworkBehaviour.md -- name: Clock Synchronization - href: ClockSync.md -- name: Data Types - href: DataTypes.md -- name: Serialization - href: Serialization.md -- name: Visibility - href: Visibility.md -- name: Development Servers - href: DevServer/toc.yml - topicHref: DevServer/index.md -- name: Synchronization - href: Sync/toc.yml - topicHref: Sync/index.md -- name: Communications - href: Communications/toc.yml - topicHref: Communications/index.md -- name: GameObjects - href: GameObjects/toc.yml - topicHref: GameObjects/index.md -- name: Best Practices - href: BestPractices.md diff --git a/doc/Articles/Resources.md b/doc/Articles/Resources.md deleted file mode 100644 index be92aaf35..000000000 --- a/doc/Articles/Resources.md +++ /dev/null @@ -1,30 +0,0 @@ -# Resources - -This page has a collection of links for learning and using mirror. - -Some things this page includes -- Video tutorials -- Other guides -- Example scripts - -Anything to add to this list? Please make a PR or ask in the discord. - -## Video Tutorials Playlists - -- **[Unity - Mirror Networking by First Gear Games](https://www.youtube.com/playlist?list=PLkx8oFug638oBYF5EOwsSS-gOVBXj1dkP) -** - Short tutorials that explain the basics and shows example code for Mirror. Also includes paid tutorials with more advanced features and extensions to mirror. - -- **[Mirror Multiplayer by Dapper Dino](https://www.youtube.com/playlist?list=PLS6sInD7ThM1aUDj8lZrF4b4lpvejB2uB) -** - Tutorials that explain how to implement different features using Mirror. - -- **[Unity + Mirror Networking Tutorials by Shrine Wars](https://www.youtube.com/playlist?list=PLXEG2omgKgCapAmGe20XBgd87rmxFdKhK) -** - Explains the basics about Networking with Unity and Mirror. - -- **[Mirror Networking Tutorials by Jared Brandjes](https://www.youtube.com/playlist?list=PLDI3FQoanpm1X-HQI-SVkPqJEgcRwtu7M) -** - Long tutorials explaining how to set up lobbies and matchmaking with Mirror. - -## Object Pooling - -- [Simple object pooling script](https://gist.github.com/James-Frowen/46ca5e8fd76d62527be7b958ca8dbaf1) -- [Advanced object pooling scripts](https://gist.github.com/James-Frowen/c2ab4cdc96165298518bd2db0781bbe6) - diff --git a/doc/Articles/Transports/Fallback.PNG b/doc/Articles/Transports/Fallback.PNG deleted file mode 100644 index 460bca30a..000000000 Binary files a/doc/Articles/Transports/Fallback.PNG and /dev/null differ diff --git a/doc/Articles/Transports/Fallback.md b/doc/Articles/Transports/Fallback.md deleted file mode 100644 index 1c76a5207..000000000 --- a/doc/Articles/Transports/Fallback.md +++ /dev/null @@ -1,20 +0,0 @@ -# Fallback Transport - -The FallbackTransport can be used to work around transport platform limits. - -For example, our Apathy transport is currently only available on Windows, Mac and Linux where as Telepathy is available on all Platforms. Apathy has significant performance improvements, and ideally we would want Mirror to use Apathy if on Windows/Mac/Linux and fall back to Telepathy otherwise. - -This is what the FallbackTransport allows us to do. - -Usage: - -1. Add a gameobject with a NetworkManager to your scene if you have not done so -2. By default, Unity will add TelepathyTransport to your NetworkManager game object -3. Add a FallbackTransport component to the gameobject -4. Assign the FallbackTransport component in your NetworkManager's transport -5. Add a ApathyTransport component to the gameobject -6. Add both ApathyTransport and TelepathyTransport to the FallbackTransport's transport property. - -Important: all fallback transport need to be binary compatible with each other. For example, it might happen that the server runs Apathy and a client connects to it with Telepathy. - -![The Fallback Transport](Fallback.PNG) diff --git a/doc/Articles/Transports/FizzyFacepunch.PNG b/doc/Articles/Transports/FizzyFacepunch.PNG deleted file mode 100644 index ae605a60e..000000000 Binary files a/doc/Articles/Transports/FizzyFacepunch.PNG and /dev/null differ diff --git a/doc/Articles/Transports/FizzyFacepunch.md b/doc/Articles/Transports/FizzyFacepunch.md deleted file mode 100644 index d0639e58d..000000000 --- a/doc/Articles/Transports/FizzyFacepunch.md +++ /dev/null @@ -1,19 +0,0 @@ -# FizzyFacepunch Transport - -FizzyFacepunch is a Steam P2P transport for Mirror, it utilizes Steam's P2P service to directly connect or relay your connection to another player. FizzyFacepunch is based on the [Facepunch.Steamworks](https://github.com/Facepunch/Facepunch.Steamworks) wrapper. - -You can get the release **[Here](https://github.com/Chykary/FizzyFacepunch/releases)** or you can clone the repo **[Here](https://github.com/Chykary/FizzyFacepunch)**. - -## Features - -* Multiple Customizable Channels : You can customize the channels in the transport, whether you want just 1 or 5 channels that are unreliable or reliable (best to leave channel 0 as reliable). -* Steam Nat Punching & Relay : The transport will use Steam to do Nat Punching to your destination, and if that doesn't work, steam's relay Server will be used to ensure you can always connect (latency may vary). -* No Code Changes Needed : If you Already use Mirror, you just need to slap this transport in (maybe add your steam App ID in your build), and everything should work the same like any other Mirror Transport. "It Just Works" -Todd Howard - -![The FizzySteamworks Transport component in the Inspector window](FizzyFacepunch.PNG) - -## Credits -* [Chykary](https://github.com/Chykary/FizzyFacepunch) : The author of this Transport. -* [Facepunch](https://github.com/Facepunch) : Creator of Facepunch.Steamworks. -* [vis2k](https://github.com/vis2k) : Creator of Mirror. -* Valve : Steam diff --git a/doc/Articles/Transports/FizzySteamworks.PNG b/doc/Articles/Transports/FizzySteamworks.PNG deleted file mode 100644 index 557c0c27e..000000000 Binary files a/doc/Articles/Transports/FizzySteamworks.PNG and /dev/null differ diff --git a/doc/Articles/Transports/FizzySteamworks.md b/doc/Articles/Transports/FizzySteamworks.md deleted file mode 100644 index dbb0c5c67..000000000 --- a/doc/Articles/Transports/FizzySteamworks.md +++ /dev/null @@ -1,20 +0,0 @@ -# FizzySteamworks Transport - -FizzySteamworks is a Steam P2P transport for Mirror, it utilizes Steam's P2P service to directly connect or relay your connection to another player. FizzySteamworks is based on the [Steamworks.Net](https://github.com/rlabrecque/Steamworks.NET) wrapper. - -You can get the release **[Here](https://github.com/Chykary/FizzySteamworks/releases)** with the latest version of Steamworks.Net included or you can clone the repo **[Here](https://github.com/Chykary/FizzySteamworks)**. - -## Features - -* Multiple Customizable Channels : You can customize the channels in the transport, whether you want just 1 or 5 channels that are unreliable or reliable (best to leave channel 0 as reliable). -* Steam Nat Punching & Relay : The transport will use Steam to do Nat Punching to your destination, and if that doesn't work, steam's relay Server will be used to ensure you can always connect (latency may vary). -* No Code Changes Needed : If you Already use Mirror, you just need to slap this transport in (maybe add your steam App ID in your build), and everything should work the same like any other Mirror Transport. "It Just Works" -Todd Howard - -![The FizzySteamworks Transport component in the Inspector window](FizzySteamworks.PNG) - -## Credits -* [Fizz Cube](https://github.com/FizzCube) : Original author for this Transport. -* [Chykary](https://github.com/Chykary/FizzySteamworks) : The current maintainer for this Transport. -* [rlabrecque](https://github.com/rlabrecque) : Creator of Steamworks.Net. -* [vis2k](https://github.com/vis2k) : Creator of Mirror. -* Valve : Steam diff --git a/doc/Articles/Transports/Ignorance.md b/doc/Articles/Transports/Ignorance.md deleted file mode 100644 index 13939b68d..000000000 --- a/doc/Articles/Transports/Ignorance.md +++ /dev/null @@ -1,62 +0,0 @@ -# Ignorance - -## What is Ignorance? -Ignorance is a reliable UDP transport layer that utilizes the native ENET C Networking library via a [custom fork of ENet-CSharp](https://github.com/SoftwareGuy/ENet-CSharp) providing an reliable and unreliable sequenced UDP transport for both 64Bit desktop operating systems (Windows, Mac OS and Linux) and Mobile OSes (Apple iOS and Android). It also supports up to 255 channels and 4096 clients connected at one time. - -ENET is a solid reliable UDP C++ network library that is mature and stable. Unity's LLAPI needs a replacement. Ignorance was designed with that goal in mind - fill the gap and provide a solid, performant RUDP transport for Mirror. - -## Why Ignorance over the Unity LLAPI? -Unity's old LLAPI was horridly inefficient, and lots of testing has shown that you will get reduced performance using Unity LLAPI in your project. This is due to the design of the old networking code - Unity Tech made "by design" decisions and poor bug fixes that were seen to other developers as band-aids over a gaping wound. They did not care about performance or bug fixes. - -Unity LLAPI was also closed source, meaning the Mirror developers could not take a knife to it and make it better. This is where the concept of Ignorance took shape. - -## Who develops Ignorance? -[Coburn](http://github.com/softwareguy) is the lead developer of the transport. Oiran Studio actively uses this transport for networked game projects. It is currently also being utilized by some game projects, where you can find on the Mirror Discord server. - -## Why would I want to use reliable UDP over TCP? -- if you have realtime communications that you need speed over reliability (VoIP...) -- if you need channels -- if you need custom channel send types -- if you need a data hose for your game (a first person shooter, racing game, etc) - -## Why wouldn't I want to use reliable UDP over TCP? -- if you have **mission critical** things (as in, data **NEEDS** to go from A and B, no exceptions) -- if you need fully reliable network protocol -- if you're paranoid -- if you're making a Minecraft-like game and need to keep everyone in sync - -## I want to know more about reliable UDP... -A little explanation is required. UDP is best described as a "shattershot" data transmission protocol, which means you just spray and pray that packets at a destination and hope for the best. The remote destination may or may not receive those packets, nor are they going to be in order. For example, if you have a packet stream that is: -``` -1 2 3 4 5 6 7 -``` -...then it may end up like any of the following on the other end due to packets arriving out of order. A dot in the following example means that packet went missing. -``` -7 6 1 3 2 4 5 -7 6 . . 4 . 1 -. . . . 1 2 3 -1 2 3 5 4 6 7 -``` - -For example, say you lost a packet and that contained a player's health update. Everyone else might know they took 69 damage, but that client will still have the old value of say, 72 health. Without reliable UDP, you can become out of sync very quickly. When you're out of sync, the game is over - everything will start operating very strangely. - -## Sequencing and Reliable Delivery - -### Sequencing -**Sequencing** basically tags packets so they know what number they are when being dispatched. So if you send packets `100, 101, 102` to the remote destination, the other end will reconstruct the packet in that order rather than in a different order (like `101, 100, 102`). If a packet is missing, it'll be skipped but the network library will take note that it's missing and compensate. - -**Reliable** mode just tells ENET to send this while waiting for the remote to acknowledge packet reception, before claiming it was 'lost'. ENET will still classify said packets as lost if it doesn't hear back from the remote, but it will retransmit them to compensate for lossy connections or high latency situations. Reliable mode tries to emulate some of TCP's resending if not acknowledged in time, but as UDP does not have all the overhead TCP protocol has, it adds some packet overhead. - -Ignorance comes with two channels in both Reliable and Unreliable mode by default. There are other channel modes that developers can test as different ones might suit different loads, but the average person does not need to worry about this. Ignorance comes with sane defaults out of the box. - -## Does Ignorance support Websockets? -No, it does not. Mirror comes with built-in websockets support. - -## Where can I get Ignorance? -[Grab the latest build from the releases page on the Ignorance repository](https://github.com/SoftwareGuy/Ignorance). Simply import the Unity Package from the release you downloaded. - -## Where can I get support? -You can get support by opening a issue ticket on the [Ignorance repository issue tracker](https://github.com/SoftwareGuy/Ignorance/issues) or the #ignorance channel in the Mirror Discord server. - -## I still don't understand what this transport is, my head is spinning, help! -Come by the Discord and we'll do our best to explain it in plain English. diff --git a/doc/Articles/Transports/IgnoranceTransport.PNG b/doc/Articles/Transports/IgnoranceTransport.PNG deleted file mode 100644 index 3f6767e8a..000000000 Binary files a/doc/Articles/Transports/IgnoranceTransport.PNG and /dev/null differ diff --git a/doc/Articles/Transports/KCP.PNG b/doc/Articles/Transports/KCP.PNG deleted file mode 100644 index 36dc5289d..000000000 Binary files a/doc/Articles/Transports/KCP.PNG and /dev/null differ diff --git a/doc/Articles/Transports/KCPTransport.md b/doc/Articles/Transports/KCPTransport.md deleted file mode 100644 index 7ca61837b..000000000 --- a/doc/Articles/Transports/KCPTransport.md +++ /dev/null @@ -1,33 +0,0 @@ -# KCP Transport - -**KCP transport for Mirror.** - -![The KCP Transport component in the Inspector window](KCP.PNG) - -## About this transport -kcp2k[https://github.com/vis2k/kcp2k] is the new default Transport for Mirror. - -Why KCP: https://github.com/skywind3000/kcp/blob/master/README.en.md - -+ 100% C#. -+ Works on all platforms except WebGL. -+ Heavy test coverage (83.5%). -+ Extremely fast. -+ Extremely simple. -+ Nearly allocation free*. - -"KCP is a fast and reliable protocol that can achieve the transmission effect of a reduction of the average latency by 30% to 40% and reduction of the maximum delay by a factor of three, at the cost of 10% to 20% more bandwidth wasted than TCP. It is implemented by using the pure algorithm, and is not responsible for the sending and receiving of the underlying protocol (such as UDP), requiring the users to define their own transmission mode for the underlying data packet, and provide it to KCP in the way of callback. Even the clock needs to be passed in from the outside, without any internal system calls." - -We are very excited about KCP and highly recommend trying it in your project. -=> Previously we had pure C# transports that were slow -=> And native C transports that were fast, but hard to maintain. - -KCP brings us the best of both worlds: it's as fast as our native C transports, while still being easy to maintain because it's 100% pure C#! - -## Usage -Add the KCPTransport component to your NetworkManager. - -## Credits -skywind3000 for original kcp.c (https://github.com/skywind3000/kcp) -kcp-csharp for first C# port (https://github.com/limpo1989/kcp-csharp) -paul/lymdum/uwee for connection handling. diff --git a/doc/Articles/Transports/Libuv2k.PNG b/doc/Articles/Transports/Libuv2k.PNG deleted file mode 100644 index 62daafc77..000000000 Binary files a/doc/Articles/Transports/Libuv2k.PNG and /dev/null differ diff --git a/doc/Articles/Transports/Libuv2k.md b/doc/Articles/Transports/Libuv2k.md deleted file mode 100644 index a2ac0a9d5..000000000 --- a/doc/Articles/Transports/Libuv2k.md +++ /dev/null @@ -1,19 +0,0 @@ -# Libuv2k Transport - -**Libuv2k transport for Mirror.** - -![The Libuv2k Transport component in the Inspector window](Libuv2k.PNG) - -## About this transport -libuv2k is a TCP transport using libuv(https://github.com/libuv/libuv). -libuv is the native C networking backend behind Node.js. -It's battle tested and extremely fast. - -## Usage -Add the component to your NetworkManager. - -## Features -* TCP - -## Credits -libuv(https://github.com/libuv/libuv) diff --git a/doc/Articles/Transports/LiteNetLib4Mirror.md b/doc/Articles/Transports/LiteNetLib4Mirror.md deleted file mode 100644 index a9884c943..000000000 --- a/doc/Articles/Transports/LiteNetLib4Mirror.md +++ /dev/null @@ -1,47 +0,0 @@ -# LiteNetLib4Mirror Transport - -**LiteNetLib based transport for Mirror.** - -## Usage -1. Download the unity package from [Releases](https://github.com/MrGadget1024/LiteNetLib4Mirror/releases) and import it to your project (it does not contain Mirror) -2. Put LiteNetLib4MirrorTransport component on gameobject with NetworkManager and assign it there -3. (Optional) Make your NetworkManager derrive from LiteNetLib4MirrorNetworkManager and use optional overloads from it - -## Features -- UDP -- Built-in Network Discovery and UPnP -- Fully managed code -- Small CPU and RAM usage -- Small packet size overhead ( 1 byte for unreliable, 3 bytes for reliable packets ) -- Different send mechanics -- Reliable with order -- Reliable without order -- Ordered but unreliable with duplication prevention -- Simple UDP packets without order and reliability -- Automatic small packets merging -- Automatic fragmentation of reliable packets -- Automatic MTU detection -- NTP time requests -- Packet loss and latency simulation -- IPv6 support (dual mode) -- Connection statisitcs (need DEBUG or STATS_ENABLED flag) -- Multicasting (for discovering hosts in local network) - -## IL2CPP Warning! -With IL2CPP, IPv6 is only supported on Unity 2018.3.6f1 and later because of this: -[Unity ChangeLog](https://unity3d.com/unity/whats-new/2018.3.6) -> IL2CPP: Added protocol support for IPv6 on Windows. (1099133) -> -> IL2CPP: Correctly indicate that IPv6 is not supported on non-IPv6 platforms. (1108823) - -Also, socket Reuse Address option isn't available in IL2CPP. - -## Credits -RevenantX - for [LiteNetLib](https://github.com/RevenantX/LiteNetLib/releases) -vis2k & Paul - for [Mirror](https://assetstore.unity.com/packages/tools/network/mirror-129321) -Coburn - for [Ignorance](https://github.com/SoftwareGuy/Ignorance) which i've used as an example -Dankrushen - for helping me find one small mistake which i couldn't find for two days -Lucas Ontivero - for [Open.Nat](https://github.com/lontivero/Open.NAT/releases), used for UPnP -shiena - for NetworkDiscoveryHUD - -![The LiteNetLib4Mirror Transport component in the Inspector window](LiteNetLibTransport.PNG) diff --git a/doc/Articles/Transports/LiteNetLibTransport.PNG b/doc/Articles/Transports/LiteNetLibTransport.PNG deleted file mode 100644 index a65ab03e0..000000000 Binary files a/doc/Articles/Transports/LiteNetLibTransport.PNG and /dev/null differ diff --git a/doc/Articles/Transports/LiteNetLibTransport.md b/doc/Articles/Transports/LiteNetLibTransport.md deleted file mode 100644 index 630a0a67d..000000000 --- a/doc/Articles/Transports/LiteNetLibTransport.md +++ /dev/null @@ -1,29 +0,0 @@ -# LiteNetLib Transport - -**[LiteNetLib](https://github.com/RevenantX/LiteNetLib) based transport for Mirror.** - -Source code: [LiteNetLibTransport](https://github.com/MirrorNetworking/LiteNetLibTransport) - -*Old version (not maintained) [LiteNetLib4Mirror](./LiteNetLib4Mirror.md)* - -![Inspector](./LiteNetLibTransportInspector.jpg) - -## Usage - -1) Download the code from the source folder or package on [Release](https://github.com/MirrorNetworking/LiteNetLibTransport/releases) page. -2) Put the code somewhere in your Assets folder -3) Replace your existing Transport with LiteNetLibTransport on your NetworkManager - - -## Features - -- UDP -- Fully managed code -- Small CPU and RAM usage - -see full features of LiteNetLib [here](https://github.com/RevenantX/LiteNetLib) - - -## Bugs? - -Please report any bugs or issues [Here](https://github.com/MirrorNetworking/LiteNetLibTransport/issues) diff --git a/doc/Articles/Transports/LiteNetLibTransportInspector.jpg b/doc/Articles/Transports/LiteNetLibTransportInspector.jpg deleted file mode 100644 index 44c5f667a..000000000 Binary files a/doc/Articles/Transports/LiteNetLibTransportInspector.jpg and /dev/null differ diff --git a/doc/Articles/Transports/MultiplexSample.png b/doc/Articles/Transports/MultiplexSample.png deleted file mode 100644 index 900e12fa1..000000000 Binary files a/doc/Articles/Transports/MultiplexSample.png and /dev/null differ diff --git a/doc/Articles/Transports/Multiplexer.md b/doc/Articles/Transports/Multiplexer.md deleted file mode 100644 index d3091c5b4..000000000 --- a/doc/Articles/Transports/Multiplexer.md +++ /dev/null @@ -1,23 +0,0 @@ -# Multiplex Transport - -The MultiplexTransport is not a transport itself, but it allows you to combine other transports so that your clients can connect to your servers via either one of them. - -A common use case for the MultiplexTransport is a server listening to both websockets and TCP. Your webgl clients can connect to the server using websockets and your mobile or desktop clients can connect to the same server via TCP. In HLAPI, you had to chose between websockets and UDP, but you cannot use both at the same time. You can configure any number of transports in the MultiplexTransport. - -To use the MultiplexTransport follow these steps: - -1. Add a gameobject with a NetworkManager to your scene if you have not done so -2. By default, Unity will add TelepathyTransport to your NetworkManager game object -3. Add a MultiplexTransport component to the gameobject -4. Assign the MultiplexTransport component in your NetworkManager's transport -5. Add a WebsocketTransport component to the gameobject -6. Add the TelepathyTransport component to the MultiplexTransport as the first transport -7. Add the WebsocketTransport component to the MultiplexTransport as the second transport - -Please note that Telepathy and WebsocketTransport cannot listen to the same port. By default Telepathy listens to 7777 and the websocket transport listens to 7778. - -If you build your game as a webgl game, the TelepathyTransport will be skipped and your client will use the websocket transport. If you build your game as a mobile or desktop app, it will choose TelepathyTransport. The server will happily accept connections from both. - -Here is what the configuration should look like: - -![Multiplex Example](MultiplexSample.png) diff --git a/doc/Articles/Transports/SimpleWebTransport.md b/doc/Articles/Transports/SimpleWebTransport.md deleted file mode 100644 index d5fa3f183..000000000 --- a/doc/Articles/Transports/SimpleWebTransport.md +++ /dev/null @@ -1,47 +0,0 @@ -# Simple Web Transport - -Transport that uses the websocket protocol. This allows this transport to be used in WebGL builds of unity. - -Source code: [SimpleWebTransport](https://github.com/MirrorNetworking/SimpleWebTransport) - -![Inspector](./SimpleWebTransportInspector.jpg) - -## Usage - -1) Download the code from the source folder or package on [Release](https://github.com/MirrorNetworking/SimpleWebTransport/releases) page. -2) Put the code somewhere in your Assets folder -3) Replace your existing Transport with SimpleWebTransport on your NetworkManager - - -## Bugs? - -Please report any bugs or issues [Here](https://github.com/MirrorNetworking/SimpleWebTransport/issues) - -# Websocket Secure - -This transport supports the wss protocol which is required for https pages. - -## How to create and setup an SSL Cert - -If you host your webgl build on a https domain you will need to use wss which will require a ssl cert. - -[See this page](https://github.com/MirrorNetworking/SimpleWebTransport/blob/master/HowToCreateSSLCert.md) - - -# Logging - -Log levels can be set using the dropdown on the transport or or setting `Mirror.SimpleWeb.Log.level`. - -The transport applies the dropdown value in its `Awake` and `OnValidate` methods. - -### Log methods - -Log methods in this transport use the [ConditionalAttribute](https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute?view=netstandard-2.0) so they are removed depending on the preprocessor defines. - -These preprocessor defines effect the logging -- `DEBUG` allows warn/error logs -- `SIMPLEWEB_LOG_ENABLED` allows all logs - -Without `SIMPLEWEB_LOG_ENABLED` info or verbose logging will never happen even if log level allows it. - -See the [Unity docs](https://docs.unity3d.com/Manual/PlatformDependentCompilation.html) on how set custom defines. diff --git a/doc/Articles/Transports/SimpleWebTransportInspector.jpg b/doc/Articles/Transports/SimpleWebTransportInspector.jpg deleted file mode 100644 index c72adc76a..000000000 Binary files a/doc/Articles/Transports/SimpleWebTransportInspector.jpg and /dev/null differ diff --git a/doc/Articles/Transports/Telepathy.md b/doc/Articles/Transports/Telepathy.md deleted file mode 100644 index 1c8cb0aa7..000000000 --- a/doc/Articles/Transports/Telepathy.md +++ /dev/null @@ -1,26 +0,0 @@ -# Telepathy Transport - -Simple, message based, MMO Scale TCP networking in C\#. And no magic. -- Telepathy was designed with the [KISS Principle](https://en.wikipedia.org/wiki/KISS_principle) in mind. -- Telepathy is fast and extremely reliable, designed for [MMO](https://assetstore.unity.com/packages/templates/systems/ummorpg-51212) scale Networking. -- Telepathy uses framing, so anything sent will be received the same way. -- Telepathy is raw C\# and can be used in Unity3D too. -- Telepathy is available on [GitHub](https://github.com/vis2k/Telepathy) - -## What makes Telepathy special? - -Telepathy was originally designed for [uMMORPG](https://assetstore.unity.com/packages/templates/systems/ummorpg-51212) after 3 years in UDP hell. - -We needed a library that is: -- Stable & Bug free: Telepathy uses only 400 lines of code. There is no magic. -- High performance: Telepathy can handle thousands of connections and packages. -- Concurrent: Telepathy uses one thread per connection. It can make heavy use of multi core processors. -- Simple: Telepathy takes care of everything. All you need to do is call Connect/GetNextMessage/Disconnect. -- Message based: if we send 10 and then 2 bytes, then the other end receives 10 and then 2 bytes, never 12 at once. - -MMORPGs are insanely difficult to make and we created Telepathy so that we would never have to worry about low level Networking again. - -## What about... -- Async Sockets: didn't perform better in our benchmarks. -- ConcurrentQueue: .NET 3.5 compatibility is important for Unity. Wasn't faster than our SafeQueue anyway. -- UDP vs. TCP: Minecraft and World of Warcraft are two of the biggest multiplayer games of all time and they both use TCP networking. There is a reason for that. diff --git a/doc/Articles/Transports/index.md b/doc/Articles/Transports/index.md deleted file mode 100644 index ec765a955..000000000 --- a/doc/Articles/Transports/index.md +++ /dev/null @@ -1,27 +0,0 @@ -# Transports Overview - -Mirror is a high level Networking Library that can use several different low level transports. To use a transport, simply add it as component to the NetworkManager and drag it into the NetworkManager's Transport field. - -- [KCP - KCP Transport](KCPTransport.md) based on kcp.c v1.7, nearly translated 1:1. - -- [TCP - Libuv2k](Libuv2k.md) based on Native C networking backend used by Node.js. - -- [TCP - Telepathy](Telepathy.md) Simple, message based, MMO Scale TCP networking in C\#. And no magic. - -- [TCP - Apathy](https://mirror-networking.com/apathy/) Apathy is a fast, lightweight, allocation-free low level TCP library for Unity developed by vis2k. Apathy was developed in native C for maximum MMO Scale networking performance. - -- [TCP - Booster](https://mirror-networking.com/booster/) The Mirror Booster uncorks your multiplayer game by moving the Networking load out of Unity! - -- [WebSockets - SimpleWebTransport](SimpleWebTransport.md) WebSockets transport layer for Mirror that target WebGL clients. - -- [Multiplexer](Multiplexer.md) Multiplexer is a bridging transport to allow a server to handle clients on different transports concurrently, for example desktop clients using Telepathy together with WebGL clients using Websockets. - -- [Fallback](Fallback.md) Fallback is a compatibility transport for transports that don't run on all platforms and need fallback options to cover all other platforms. - -- [UDP - Ignorance](Ignorance.md) Ignorance implements a reliable and unreliable sequenced UDP transport based on ENet. - -- [UDP - LiteNetLibTransport](LiteNetLibTransport.md) LiteNetLibTransport implements a UDP transport based on [LiteNetLib](https://github.com/RevenantX/LiteNetLib). - -- [Steam - FizzySteamworks](FizzySteamworks.md) Transport utilising Steam P2P network, building on Steamworks.NET. - -- [Steam - FizzyFacepunch](FizzyFacepunch.md) Transport utilising Steam P2P network, building on Facepunch.Steamworks. diff --git a/doc/Articles/Transports/toc.yml b/doc/Articles/Transports/toc.yml deleted file mode 100644 index 80ce8d658..000000000 --- a/doc/Articles/Transports/toc.yml +++ /dev/null @@ -1,22 +0,0 @@ -- name: Overview - href: index.md -- name: KCP - KCP Transport - href: KCPTransport.md -- name: TCP - Libuv2k - href: Libuv2k.md -- name: TCP - Telepathy - href: Telepathy.md -- name: WebGL - SimpleWebTransport - href: SimpleWebTransport.md -- name: Multiplexer - href: Multiplexer.md -- name: Fallback - href: Fallback.md -- name: UDP - Ignorance - href: Ignorance.md -- name: UDP - LiteNetLibTransport - href: LiteNetLibTransport.md -- name: Steam - FizzySteamworks - href: FizzySteamworks.md -- name: Steam - FizzyFacepunch - href: FizzyFacepunch.md diff --git a/doc/Articles/toc.yml b/doc/Articles/toc.yml deleted file mode 100644 index 4181d1d9b..000000000 --- a/doc/Articles/toc.yml +++ /dev/null @@ -1,22 +0,0 @@ -- name: General - href: General/toc.yml - topicHref: General/ -- name: Guides - href: Guides/toc.yml - topicHref: Guides/ -- name: Components - href: Components/toc.yml - topicHref: Components/ -- name: Transports - href: Transports/toc.yml - topicHref: Transports/ -- name: Examples - href: Examples/toc.yml - topicHref: Examples/ -- name: Community Guides - href: CommunityGuides/toc.yml - topicHref: CommunityGuides/index.md -- name: Resources - href: Resources.md -- name: FAQ - href: FAQ.md diff --git a/doc/images/video_tutorial.png b/doc/images/video_tutorial.png deleted file mode 100644 index 6482809c8..000000000 Binary files a/doc/images/video_tutorial.png and /dev/null differ diff --git a/doc/index.md b/doc/index.md index 442ff79a3..b4f76b5bb 100644 --- a/doc/index.md +++ b/doc/index.md @@ -1,53 +1 @@ -# Mirror Networking for Unity - -**Mirror is the most compatible direct replacement for the deprecated Unity Networking API.** - -Mirror has nearly all of the components and features from UNet, making networking easy, concise and maintainable, whether you're starting from scratch or converting an existing project. We even have a [Migration Tool](Articles/General/Migration.md) to do most of the work for you! - -Built to support games of any scale, from LAN party games to dedicated high-volume authoritative servers running hundreds of players, Mirror is the core networking solution for [uMMORPG](https://assetstore.unity.com/packages/templates/systems/ummorpg-51212), [uSurvival](https://assetstore.unity.com/packages/templates/systems/usurvival-95015), [Cubica](https://www.cubica.net/), and [more](https://mirror-networking.com/showcase/)! - -uMMORPG was possible with \<6000 lines of code. We needed a networking library that allows us to launch our games, period! -- **Full Source included** for debugging convenience -- Several working examples included -- Active [Discord](https://discord.gg/2BvnM4R) for prompt support -- **Requires Unity 2018.4 LTS and Runtime .Net 4.x (default in Unity 2019) and .Net 2.0 Compatibility is recommended** -- Alpha / Beta Unity versions cannot be supported - -**Multiple Transports Available:** -- **TCP** ([Telepathy](Articles/Transports/Telepathy.md) and [Apathy](https://mirror-networking.com/apathy/) and [Booster](https://mirror-networking.com/booster/)) -- **UDP** ([ENet](Articles/Transports/Ignorance.md) and [LiteNetLib](Articles/Transports/LiteNetLibTransport.md)) -- **WebGL** ([Secure Web Sockets](Articles/Transports/SimpleWebTransport.md)) -- **Steam** ([Steamworks.Net](Articles/Transports/FizzySteamworks.md)) and ([FacePunch](Articles/Transports/FizzyFacepunch.md)) -- **Multiplexer** ([Multiplexer](Articles/Transports/Multiplexer.md)) -- **Fallback** ([Fallback](Articles/Transports/Fallback.md)) - -**List Server** - -We've developed a [List Server](https://mirror-networking.com/list-server/) where game servers can register and clients can connect to find those servers to play on them. - -**Key Features & Components:** -- [Transports](Articles/Transports/index.md) are interchangeable components -- Additive Scene handling -- Single and separated Unity projects supported -- [Network Authenticators](Articles/Components/Authenticators/index.md) to manage access to your game -- [Network Discovery](Articles/Components/NetworkDiscovery.md) to easily connect LAN players to a LAN Server or Host -- [Network Manager](Articles/Components/NetworkManager.md) and [HUD](Articles/Components/NetworkManagerHUD.md) -- [Network Room Manager](Articles/Components/NetworkRoomManager.md) and [Room Player](Articles/Components/NetworkRoomPlayer.md) -- [Network Identity](Articles/Components/NetworkIdentity.md) -- [Network Transform](Articles/Components/NetworkTransform.md) to sync position, rotation, and scale with interpolation -- [Network Animator](Articles/Components/NetworkAnimator.md) with 64 parameters -- [Network Proximity Checker](Articles/Components/NetworkProximityChecker.md) to help with Area of Interest -- [Network Scene Checker](Articles/Components/NetworkSceneChecker.md) to isolate players and networked objects to Additive scene instances -- [Network Match Checker](Articles/Components/NetworkMatchChecker.md) to isolate players and networked objects by [Network Visibility](Articles/Guides/Visibility.md) -- [SyncVar](Articles/Guides/Sync/SyncVars.md), [SyncList](Articles/Guides/Sync/SyncLists.md), [SyncDictionary](Articles/Guides/Sync/SyncDictionary.md), and [SyncHashSet](Articles/Guides/Sync/SyncHashSet.md) - -**Integrations** -- [Dissonance Voice Chat](https://assetstore.unity.com/packages/tools/audio/dissonance-voice-chat-70078) -- [Network Sync Transform](https://github.com/emotitron/NetworkSyncTransform) -- [Noble Connect Free](https://assetstore.unity.com/packages/tools/network/noble-connect-free-141599) -- [Rucksack](https://assetstore.unity.com/packages/templates/systems/rucksack-multiplayer-inventory-system-114921) -- [RTS Engine](https://assetstore.unity.com/packages/templates/packs/rts-engine-79732) -- [Smooth Sync](https://assetstore.unity.com/packages/tools/network/smooth-sync-96925) -- [Weather Maker](https://assetstore.unity.com/packages/tools/particles-effects/weather-maker-unity-weather-system-sky-water-volumetric-clouds-a-60955) -- [Steamworks Networking](https://assetstore.unity.com/packages/tools/integration/steamworks-networking-151300) -- [Master Audio Multiplayer](https://assetstore.unity.com/packages/tools/audio/master-audio-multiplayer-69547) +Documentation moved to https://mirror-networking.gitbook.io/docs/ \ No newline at end of file diff --git a/doc/toc.yml b/doc/toc.yml index d73d288c6..521650daa 100644 --- a/doc/toc.yml +++ b/doc/toc.yml @@ -1,7 +1,3 @@ -- name: Home - href: index.md -- name: Articles - href: Articles/ - name: API Reference href: xref:Mirror - name: Sponsor Us!