GithubHelp home page GithubHelp logo

mirrornetworking / mirror Goto Github PK

View Code? Open in Web Editor NEW
4.9K 98.0 742.0 381.89 MB

#1 Open Source Unity Networking Library

Home Page: https://mirror-networking.com

License: MIT License

C# 99.87% PowerShell 0.01% JavaScript 0.09% ShaderLab 0.03%
unity unet hlapi networking udp tcp mirror telepathy mmo mmorpg

mirror's Introduction

Mirror Logo

Download Showcase Documentation Forum Roadmap
License: MIT Build release Discord

It's only the dreamers who ever move mountains.

Mirror Networking

The #1 free open source game networking library for Unity 2019 / 2020 / 2021 / 2022 LTS.

Used in production by major hits like Population: ONE and many more.

Originally based on UNET: battle tested since 2014 for 9 years and counting!

Mirror is stable, modular & easy to use for all types of games, even small MMORPGs ๐ŸŽฎ.

Made in ๐Ÿ‡ฉ๐Ÿ‡ช๐Ÿ‡บ๐Ÿ‡ธ๐Ÿ‡ฌ๐Ÿ‡ง๐Ÿ‡ธ๐Ÿ‡ฌ๐Ÿ‡น๐Ÿ‡ผ with โค๏ธ.


Features

Mirror comes with a wide variety of features to support all game genres.
Many of our features quickly became the norm across all Unity netcodes!

Feature Description Status
๐ŸŽ› Transports UDP, TCP, Websockets, Steam, Relay and more. Stable
๐Ÿชœ Interest Management Spatial Hashing & Distance Checker to partition the world. Stable
โ†—๏ธ SyncDirection Server & Client Authority - per component with one click. Stable
๐ŸŒ Latency Simulation Simulate latency, packet loss & jitter locally. Stable
๐Ÿงฒ Batching Minimize message overhead via batching automatically. Stable
๐Ÿ’Œ RPCs & SyncVars Synced vars and remote function calls built in & safe. Stable
๐Ÿ™…โ€โ™€๏ธAllocation Free Free of runtime allocations and no GC (except Transports). Stable
๐Ÿ›ž Transform & Physics Transform & Physics sync built in. Stable
๐Ÿ‘ฉโ€๐Ÿผ Child Components Put networked components on anything. Stable
๐Ÿชš๏ธ IL Post Processing Zero overhead [Rpcs] and [Commands] via IL post processing! Stable
โ˜๏ธ Two Click Hosting (Optional) Build & Push directly from Unity Editor to the Cloud. Preview
๐Ÿ“ Snapshot Interp. Perfectly smooth movement for all platforms and all games. Stable
๐ŸŽ Fast Prediction Simulate Physics locally & apply server corrections [VR ready] Beta
๐Ÿ”ซ Lag Compensation Roll back state to see what the player saw during input. Beta
๐Ÿง™โ€โ™‚๏ธ General Purpose Mirror supports all genres for all your games!
๐Ÿง˜โ€โ™€๏ธ Stable API Long term (10 years) stability instead of new versions!
๐Ÿ”ฌ Battle Tested Mirror servers over 100 million players. It just works!
๐Ÿ’ด Free & Open Source MIT licensed without any restrictions to minimize risk!
โค๏ธ Community Join our Discord with nearly 15.000 developers world wide!
๐Ÿงœ๐Ÿปโ€โ™€๏ธ Long Term Support Maintained since 2014 with optional LTS version!
๐Ÿ”’ Encryption Secure communication with end-to-end encryption. Preview
๐Ÿ“ Bitpacking Optimized compression (bools as 1 bit etc.) Researching

Architecture

The Server & Client are ONE project in order to achieve maximum productivity.

Simply use NetworkBehaviour instead of MonoBehaviour.

Making multiplayer games this way is fun & easy:

public class Player : NetworkBehaviour
{
    // Synced automatically
    [SyncVar] public int health = 100;
    
    // Lists, Dictionaries, Sets too
    SyncList<Item> inventory = new SyncList<Item>();
    
    // Server/Client-only code
    [Server] void LevelUp() {}
    [Client] void Animate() {}
    
    void Update()
    {
        // isServer/isClient for runtime checks
        if (isServer) Heal();
        if (isClient) Move();
    }
    
    // Zero overhead remote calls
    [Command]   void CmdUseItem(int slot) {} // Client to Server
    [ClientRpc] void RpcRespawn() {}         // Server to all Clients
    [TargetRpc] void Hello() {}              // Server to one Client
}

There's also NetworkServer & NetworkClient.
And that's about it ๐Ÿคฉ


Free, Open Source & Community Focused

Mirror is free & open source (MIT Licensed).

๐Ÿบ "Free" as in free beer, and freedom to use it any way you like.

  • Host Game Servers anywhere!
  • Customize anything freely!
  • No paywalls, no CCU costs, no strings attached!

๐Ÿค We are a team of professional game developers, who are paid to use Mirror in production. Our incentives will always align with the community, because we are Mirror users just like you!

โค๏ธ Our fantastic community of over 14,000 users contributes feedback & improvements every day. Please join us on our journey, help others, and consider a Donation if you love our work!

The top quote is from Fitzcarraldo, which is quite reminiscent of this project.


Getting Started

Get Unity 2019 / 2020 / 2021 / 2022 LTS, Download Mirror, open one of the examples & press Play!

Check out our Documentation to learn how it all works.

If you are migrating from UNET, then please check out our Migration Guide.


Mirror LTS (Long Term Support)

Mirror LTS is available on the Asset Store.

Mirror LTS gives you peace of mind to run your game in production. Without any breaking changes, ever!

  • Bug fixes only.
  • Consistent API: update any time, without any breaking features.
  • Lives along side Unity 2019/2020/2021 LTS.
  • Supported for two years at a time.

Made with Mirror

Population: ONE The BigBoxVR team started using Mirror in February 2019 for what eventually became one of the most popular Oculus Rift games.

In addition to 24/7 support from the Mirror team, BigBoxVR also hired one of our engineers.

Population: ONE was acquired by Meta in June 2021, and they've just released a new Sandbox addon in 2022!

Zooba Wildlife Studio's hit Zooba made it to rank #5 of the largest battle royal shooters in the U.S. mobile market.

The game has over 100 million downloads on Google Play, with Wildlife Studios as one of the top 10 largest mobile gaming companies in the world.

swarmvr_compressed SPIDER-MAN WITH GUNS!

SWARM is a fast-paced, arcade-style grapple shooter, with quick sessions, bright colorful worlds and globally competitive leaderboards that will take you back to the glory days of Arcade Games.

Available for the Meta Quest, made with Mirror.

Castaways Castaways is a sandbox game where you are castaway to a small remote island where you must work with others to survive and build a thriving new civilization.

Castaway runs in the Browser, thanks to Mirror's WebGL support.

nimoyd_smaller Nudge Nudge Games' first title: the colorful, post-apocalyptic open world sandbox game Nimoyd is being developed with Mirror.

Soon to be released for PC & mobile!

unleashed From original devs of World of Warcraft, Kingdoms of Amalur, and EverQuest comes a new family friendly fantasy adventure. Fight against the forces of darkness, explore a world consumed by wild magic, and build a stronghold with your friends to increase your power in a new world.

Lead by industry veterans Brian Birmingham & Irena Pereira, Unleashed is developing their next gen adventure game made with Mirror!

Follow them on X: https://twitter.com/UnleashingGames/

dinkum Set in the Australian Outback, Dinkum is a relaxing farming & survival game. Made by just one developer, Dinkum already reached 1000+ "Overwhelmingly Positive" reviews 1 week after its early access release.

James Bendon initially made the game with UNET, and then switched to Mirror in 2019.

a glimpse of luna A Glimpse of Luna - a tactical multiplayer card battle game with the most beautiful concept art & soundtrack.

Made with Mirror by two brothers with no prior game development experience.

havoc fps game Havoc is a tactical team-based first-person shooter with a fully destructible environment and a unique art style. Havoc has been one of our favorite made-with-Mirror games for a few years now, and we are excited to finally see it up there on Steam.

sun haven Sun Haven - A beautiful human town, a hidden elven village, and a monster city filled with farming, magic, dragons, and adventure.

After their successful Kickstarter, Sun Haven was released on Steam in 2021 and later on ported to Mirror in 2022.

A Township Tale A Township Tale is an immersive VR experience, where you can build towns and explore worlds with your friends.

Made with our KCP transport, available on the Meta Quest Store with over 6000+ ratings.

Inferna MMORPG One of the first MMORPGs made with Mirror, released in 2019.

An open world experience with over 1000 CCU during its peak, spread across multiple server instances.

samutale A sandbox survival samurai MMORPG, originally released in September 2016.

Later on, the Netherlands based Maple Media switched their netcode to Mirror.

image Pixel Art Dungeon MMORPG reaching 5000 CCU at peak times.

Originally developed as a single-player idle game, it underwent a transition to an MMORPG three months before release thanks to Mirror!

Untamed Isles The turn based, monster taming MMORPG Untamed Isles is currently being developed by Phat Loot Studios.

After their successful Kickstarter, the New Zealand based studio is aiming for a 2022 release date.

Portals Animal Crossing meets Yakuza meets Minecraft โ€” a city builder with a multiplayer central hub. Gather, trade and build โ€” all in the browser!

scp - secret laboratory_smaller Northwood Studios' first title: the multiplayer horror game SCP: Secret Laboratory was one of Mirror's early adopters.

Released in December 2017, today it has more than 140,000 reviews on Steam.

Naica Online Naรฏca is a beautiful, free to play 2D pixel art MMORPG.

The France based team was one of Mirror's early adopters, releasing their first public beta in November 2020.

Laurum Online Laurum Online - a 2D retro mobile MMORPG with over 500,000 downloads on Google Play.

Empires Mobile Empires Mobile - Retro mobile MMORPG for Android and iOS, reaching 5000 CCU at times. Check out their video for some early MMORPG nostalgia.

Overpowered Overwpowered, the exciting new card game that combines strategy, myth, and fun into one riveting web-based experience. Launched in 2023, made with Mirror!

And many more...

Modular Transports

Mirror uses KCP (reliable UDP) by default, but you may use any of our community transports for low level packet sending:

Benchmarks

Development & Contributing

Mirror is used in production by everything from small indie projects to million dollar funded games that will run for a decade or more.

We prefer to work slow & thoroughly in order to not break everyone's games ๐ŸŒ.

Therefore, we need to KISS ๐Ÿ˜—.


Information Security

Mirror alternative Logo

Mirror-Networking follows common information security industry standards & best practices.

Mirror is free open source software (MIT Licensed), with over 80% test coverage. The company is located in Germany. We do not collect any user data, impose no restrictions on users & developers, or rely on any closed source dependencies other than Unity.

This makes Mirror an attractive choice for government agencies and large corporations with strict information security requirements.

Feel free to reach out to business [at] mirror-networking.com if you have any questions, or need to review any of our policies:

  • Development best Practices and SDLC.pdf
  • Disaster Recovery Procedure.pdf
  • Document Retention and Destruction Policy.pdf
  • Encryption Policy.pdf
  • Information Security Guidelines.pdf
  • Privacy Policy
  • Security Policy
  • Vulnerability Management Policy.pdf

Please reach out if you decide to use Mirror.

We are excited to hear about your project, and happy to help if needed!


Incident Response & Bug Bounty

A lot of projects use Mirror in production. If you found a critical bug / exploit in Mirror core, please follow the steps outlined in our Security Policy.

Credits / past findings / fixes:


Credits & Thanks ๐Ÿ™

๐Ÿชž Alexey Abramychev (UNET)
๐Ÿชž Alan
๐Ÿชž c6burns
๐Ÿชž Coburn
๐Ÿชž cooper
๐Ÿชž FakeByte
๐Ÿชž fholm
๐Ÿชž Gabe (BigBoxVR)
๐Ÿชž imer
๐Ÿชž James Frowen
๐Ÿชž JesusLuvsYooh
๐Ÿชž Mischa
๐Ÿชž Mr. Gadget
๐Ÿชž NinjaKickja
๐Ÿชž Paul Pacheco
๐Ÿชž Sean Riley (UNET)

mirror's People

Contributors

aallbrig avatar apkd avatar atikadze avatar atlv24 avatar beguiled avatar callumferguson avatar cxxpxr avatar dmerner avatar fakebyte avatar hyouuu avatar icezman001 avatar imerr avatar james-frowen avatar jesusluvsyooh avatar katori avatar konstantin890 avatar lumeriith avatar lymdun avatar michalpetryka avatar miwarnec avatar mrgadget1024 avatar mukaschultze avatar ninjakickja avatar paulpach avatar rxmarccall avatar shulinnn avatar softwareguy avatar timpickup avatar tomkrikorian avatar uweeby avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mirror's Issues

Two NetworkClients in Mirror

Describe the bug
Unable to use two NetworkClients in Mirror. Works in UNet

Repro project
https://github.com/uweenukr/MultipleNetworkClientTest

To Reproduce
Steps to reproduce the behavior:

  1. Open the attached project in Unity
  2. Click on Tool>Build All
  3. Launch in the order: 1. Master 2. Zone 3. Client
  4. When using UNet the proper Message Handlers are utilized. When using Mirror they are not. In my full project this leads to Messages being sent to a totally to the Master instead of the Client upon Client connection to the Zone.

Note: Can switch between UNet and Mirror by changing the 'using' in the 3 NetworkManager scripts and rebuilding.

Expected behavior
Message Handling similar to UNet that would allow the use of both NetworkClients

Screenshots
https://imgur.com/a/6WXisQI

Desktop (please complete the following information):

  • OS: Windows 10
  • Build target: Standalone
  • Unity version: 2017.4
  • HLAPI CE branch: NA?

Using my full project I get this Behaviour:
Login and Client without 2nd NetworkClient = Works
Login and Client both with 2nd NetworkClient = Broke
Login Off Client On = Broke
Login On Client Off = Broke

The Client sent the LoginMsg. The server handled it properly. But when it went to reply it sent to the MasterServer.
During this test the LoginServer was set to start the 2nd NetworkClient after the NetworkManager.

This next test I set it to start the 2nd NetworkClient before the NetworkManager. Same result.
The LoginMsg is handled on the LoginServer but its reply is sent to the MasterServer.

Roslyn Incremental compiler issue

Describe the bug
Starting a project/building it or entering playmode drops warning when using the Roslyn incremental compiler (v0.0.42) in Unity 2018.2.14f (same with 2018.1+). Even with this warning all the functionality of Mirror seems to be fine

Unable to delete file Library/ScriptAssemblies/Assembly-CSharp.pdb: Sharing violation on path Library/ScriptAssemblies/Assembly-CSharp.pdb UnityEngine.Debug:LogWarning(Object) Mirror.Weaver.Weaver:Weave(String, IEnumerable1, IAssemblyResolver, String, String, String)
Mirror.Weaver.Weaver:WeaveAssemblies(IEnumerable1, IEnumerable1, IAssemblyResolver, String, String, String)
Mirror.Weaver.Program:Process(String, String, String, String[], String[], IAssemblyResolver, Action1, Action1)
Mirror.Weaver.<>c:<.cctor>b__0_0(String, CompilerMessage[])
UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface:TickCompilationPipeline(EditorScriptCompilationOptions, BuildTargetGroup, BuildTarget)`

To Reproduce
Just put Mirror into an empty project with the Roslyn Incremental compiler enabled (2018.1+/0.0.42)
Installation instructions for the compiler: https://goo.gl/6FmREG (first post)

Expected behavior
The warning not to appear

Desktop:

  • OS: Windows
  • Build target: Standalone
  • Unity version: 2018.1+ (not tested in the 2018.3 beta)
  • Latest Mirror 495

Encryption

Add an encrypted transport such as TLS 1.3.

Migration issue, missing properties

Describe the bug
I'm trying to migrate from unet to Mirror and i'm having a couple errors where I'm not sure how to fix them. (Unity 2018.2.6f1)

Mirror doesn't appear to provide:

  • NetworkConnection::lastError
  • NetworkServer::active
  • Network::isServer (i'm an idiot)

Granted using 2018.2.6f1 I thought i could still try and see what happens, I hope this helps.

which NetworkIdentity to replace UNet NetworkIdendity, Runtime or Runtime-Editor?

In the Migrations Guide, no instruction was given about where are these NetworkIdentity Component, I only found it's in the Runtim.dll and Runtime-Editor.dll by watching the video.

So there comes the question, Which one to use? or more generally speaking, if the Editor version is attached to a game object in unity editor, will it automatically linked to Runtime version when build? what's the different between these two dlls?

Can't send message immediately after client connected callback

Describe the bug

You can't Send a message from within the ClientConnected callback (MsgType.Connect) as it will return the error "NetworkClient Send when not connected to a server". But it does work if you wait a bit (Probably next frame).

Expected behavior
You should be able to send a message when you get the "I'm connected callback"

Desktop (please complete the following information):
Unity 2017.4

Unstable client connection causing server freezes

Describe the bug
When a client completely shuts off their internet, other users experience a complete drop in server response. The server produces no error logs and in the case that the client reconnects in a timely manner, everything resumes back to normal. This shutting off of the internet is not equivalent to force closing the game, where that still acts like a clean break from the server.

Desktop (please complete the following information):

  • OS: windows and osx
  • Build target: standalone and editor
  • Unity version: 2018.2

Weaver problem when using UnityEngine.UI namespace

Description
When using the UnityEngine.UI namespace the Weaver gets confused and an error is shown in the unity log:
UNetWeaver error: Exception :Mono.Cecil.AssemblyResolutionException: Failed to resolve assembly: 'UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' at Mono.Cecil.BaseAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference name, Mono.Cecil.ReaderParameters parameters) [0x000ff] in C:\buildslave\cecil\build\Mono.Cecil\BaseAssemblyResolver.cs:169 at Mono.Cecil.BaseAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference name) [0x00000] in C:\buildslave\cecil\build\Mono.Cecil\BaseAssemblyResolver.cs:115 at Mono.Cecil.DefaultAssemblyResolver.Resolve (Mono.Cecil.AssemblyNameReference name) [0x0001d] in C:\buildslave\cecil\build\Mono.Cecil\DefaultAssemblyResolver.cs:35 at Mono.Cecil.MetadataResolver.Resolve (Mono.Cecil.TypeReference type) [0x00038] in C:\buildslave\cecil\build\Mono.Cecil\MetadataResolver.cs:101 at Mono.Cecil.ModuleDefinition.Resolve (Mono.Cecil.TypeReference type) [0x00000] in C:\buildslave\cecil\build\Mono.Cecil\ModuleDefinition.cs:754 at Mono.Cecil.TypeReference.Resolve () [0x0000f] in C:\buildslave\cecil\build\Mono.Cecil\TypeReference.cs:280 at Mirror.Weaver.NetworkBehaviourProcessor.ProcessSyncVars () [0x00000] in <filename unknown>:0 at Mirror.Weaver.NetworkBehaviourProcessor.Process () [0x00000] in <filename unknown>:0 at Mirror.Weaver.Weaver.ProcessNetworkBehaviourType (Mono.Cecil.TypeDefinition td) [0x00000] in <filename unknown>:0 at Mirror.Weaver.Weaver.CheckNetworkBehaviour (Mono.Cecil.TypeDefinition td) [0x00000] in <filename unknown>:0 at Mirror.Weaver.Weaver.Weave (System.String assName, IEnumerable1 dependencies, IAssemblyResolver assemblyResolver, System.String unityEngineDLLPath, System.String unityUNetDLLPath, System.String outputDir) [0x00000] in <filename unknown>:0 UnityEngine.Debug:LogError(Object) Mirror.Weaver.Log:Error(String) Mirror.Weaver.Weaver:WeaveAssemblies(IEnumerable1, IEnumerable1, IAssemblyResolver, String, String, String) Mirror.Weaver.Program:Process(String, String, String, String[], String[], IAssemblyResolver, Action1, Action1) Mirror.Weaver.<>c:<.cctor>b__0_0(String, CompilerMessage[]) UnityEditor.Scripting.ScriptCompilation.EditorCompilationInterface:TickCompilationPipeline(EditorScriptCompilationOptions, BuildTargetGroup, BuildTarget)

Repro project
https://github.com/divieirasilva/mirror-weaver-repro-project

To Reproduce
Steps to reproduce the behavior:
1 - Build the Offline Scene (when this scene starts, it will connect automatically)
2 - Open the Server Scene on Unity and just click Play
3 - When the client connects on server you will see a "Called the wrong OnServerAddPlayer" error log on Unity.

Networked Objects In Additive Scenes Not Enabled

Describe the bug
When child scenes are loaded additive, objects with network identities don't appear in client or server.

Repro project
https://www.dropbox.com/s/orq17qrsug7hjsi/Test%20Mirror.zip?dl=0

To Reproduce
Steps to reproduce the behavior:

  1. Open the attached project.
  2. Run in Editor.
  3. Click Start as LAN Server Only.
  4. Observe child scenes loaded.
  5. Build to desktop and run the EXE as LAN Server Only.
  6. In Editor, Play as LAN Client.
  7. With WASD move the player to where ZoneA or ZoneB are located.
  8. Observe child scene(s) loaded.
  9. Observe child scene networked objects remain disabled.

Expected behavior
Child scene networked objects should be visible.

Desktop (please complete the following information):

  • OS: Windows
  • Build target: Windows Desktop
  • Unity version: 2017.4.12f1
  • Mirror Release: Pull Request #109

Additional context
No warnings or errors in console or output_log.txt but debug msgs are logged as expected.

In the _Prefabs folder, find Cubes, Cylinders, and Spheres prefabs.
Remove the Network Identity components from Cylinders, and Spheres to see what it should look like.
The Cubes in ZoneC are not networked objects and they work correctly when ZoneC is entered / exited.

  • _Scripts/ServerStartup is what loads all child scenes on server when started.
  • _Scripts/ZoneHandler is attached to the 3 Zone prefabs (Server Only) and has OnTriggerEnter/Exit handlers.
  • _Scripts/SceneLoader is attached to the Player prefab and has the ClientRPC's to do the actual loading of child scenes.

If you do a build, make sure to include MainScene and SceneA, SceneB, and SceneC.

Find MrGadget in Discord if you need more info.

Mirror fails to cleanup after server shutdown

Describe the bug
Shutting down the server does not destroy all player objects

Repro project
https://drive.google.com/open?id=1Kf0QOjPN9ljDOm7nQVJPA8f2zx72h7My

To Reproduce
Steps to reproduce the behavior:

  1. Open the attached project
  2. Build a standalone executable
  3. Start the standalone
  4. Hit play in the editor
  5. Click "Lan Server Only" in the editor
  6. Click "Lan Client" in the standalone
  7. Client will connect to the server, and you will see a "P 1:x" player in both editor and standalone
  8. Click "Stop" in the editor.
  9. Player object remains in the editor

Expected behavior
I expect the player object to be destroyed in the editor.

Screenshots
If applicable, add screenshots to help explain your problem.

screen shot 2018-12-03 at 10 32 02 am

Desktop (please complete the following information):

  • OS: MacOS
  • Build target: standalone + editor
  • Unity version: 2017.4, 2018.2
  • HLAPI CE branch: mirror

SyncToOwner

Provide a mechanism to synchronize data only with the owner of the object.

This would typically apply to quests, inventory, and other properties that other players don't see. It can significantly reduce the amount of messages sent near NPC when people are trading and crafting.

Simplify [Command], [ClientRpc] and [TargetRpc]

Is your feature request related to a problem? Please describe.
The attributes are inconsistently named, hard to learn and awkward to use.

  • [Command] - requires Cmd prefix
  • [ClientRpc] - requires Rpc prefix
  • [TargetRpc] - requires Target prefix

(Beginning to see a pattern? I'm not.)

Describe the solution you'd like

  • Rename [Command] to [Cmd].
  • Rename [ClientRpc] to [Rpc].
  • Remove [TargetRpc]. Simply use [Rpc] with a NetworkConnection parameter. (NetworkConnection parameters are already disallowed outside of [TargetRpc] methods.)

Now the required name prefix matches the attribute.

Additional context
This change would require additional steps during migration, but can easily be done using a simple search-and-replace, or even automated in a migration tool.

NPE calling numPlayers at server

Describe the bug
I am getting this error in my server log:
NullReferenceException: Object reference not set to an instance of an object at Mirror.NetworkManager+<>c.<get_numPlayers>b__66_0 (Mirror.NetworkConnection conn) [0x00000] in <filename unknown>:0 at System.Linq.Enumerable.Count[NetworkConnection] (IEnumerable1 source, System.Func`2 selector) [0x00000] in :0
at Mirror.NetworkManager.get_numPlayers () [0x00000] in :0
at NetworkManagerMMO.WorldStats () [0x00000] in :0

`

SyncList Operation OP_ADD always passes index of the first item in the list

Describe the bug
In SyncList callbacks (including SyncListInt, SyncListSTRUCT, etc. etc.), if the SyncListOperation is OP_ADD, then the value passed to the callback corresponds to the first value in the list, not the item that was just added to the list.

Repro project
https://www.dropbox.com/s/zlkel1maw7c8zny/Mirror%20SyncList%20Operation%20OP_ADD%20Bug%20Repro.zip?dl=0

To Reproduce
Steps to reproduce the behavior:

  1. Open two instances of the attached project.
  2. On one, start a LAN Host.
  3. On the other, start a LAN Client.
  4. On the LAN Host, click the "Add Random Number" button several times. Observe how the values do not sync properly across the network to the LAN Client.
  5. On the LAN Host, click the "Update Random Number" and "Remove Random Number" buttons. Observe how these actions/values do sync properly over the network.

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: Tested on MacOS
  • Build target: Tested on standalone for MacOS
  • Unity version: Tested on 2018.2.9f1
  • HLAPI CE branch: Tested on Mirror-545

Additional context
This bug first appeared in early October, or thereabouts, around the time that changes were made to the way SyncList bundling is handled. Prior to that time, the bug did not occur.

Investigate why spawning objects causes AddObserver already added message

Describe the bug
When spawning objects into the scene when connected, sometimes you can get a message that says "AddObserver: Already added observer to (gameobject). Maybe the function was called twice. Or perhaps the connection layer assigned the same ID twice ....." or something along those lines. We need to investigate why that's happening and stop emitting that warning unless people are actually deliberately trying to mess things up.

To Reproduce
Most of the time it's triggered when the player prefab is spawned by AddPlayerForConnection I believe. Can also be triggered if you use Auto Create Player option in the Network Manager.

Expected behavior
We should make sure that when objects are spawned that AddObserver functions are called once, and not multiple times.

I will investigate this further and see if there's any leads I can bring up.

Source Instead of Prebaked Assemblies

Hi there,

We have an idea on how to improve Mirror by removing the need to build assemblies externally.
The main benefit we get from not building them outside of Unity, is being able to step through the code at runtime, setting break points, etc.
Also, adapting the code would be naturally easier and quicker that way.

To achieve this, we imported the source into our Unity project, and wrote .asmdef files to let Unity build the assemblies for us.
This works perfectly fine with Weaver and Cecil as well.

Is that something you'd be interested in integrating?
If so, we'd be ready to start a pull request to get this into the repo.

Cheers,
Andi

Building your own NetworkClient

Consider the following file:

using System;
using UnityEngine;
using Mirror;

public class GameServerConnectionToMasterBehaviour : MonoBehaviour
{
    public bool AutoStartServer = true;
    public string AutoStartMasterIP = "10.1.10.65";
    public int AutoStartMasterPort = 7777;

    private NetworkClient Client;

    private void Awake()
    {
        if (AutoStartServer)
        {
            DontDestroyOnLoad(gameObject);
            Client = new NetworkClient();
            Client.hostPort = 7778;
            RegisterClientMessages();
            Client.Connect(AutoStartMasterIP, AutoStartMasterPort);
        }
    }

    private void RegisterClientMessages()
    {
        Client.RegisterHandler(MsgType.Connect, OnClientConnectInternal);
        Client.RegisterHandler(MsgType.Disconnect, OnClientDisconnectInternal);
        Client.RegisterHandler(MsgType.NotReady, OnClientNotReadyMessageInternal);
        Client.RegisterHandler(MsgType.Error, OnClientErrorInternal);
        Client.RegisterHandler(MsgType.Scene, OnClientSceneInternal);
    }

    private void OnClientSceneInternal(NetworkMessage netMsg)
    {
        throw new NotImplementedException();
    }

    private void OnClientErrorInternal(NetworkMessage netMsg)
    {
        throw new NotImplementedException();
    }

    private void OnClientNotReadyMessageInternal(NetworkMessage netMsg)
    {
        throw new NotImplementedException();
    }

    private void OnClientDisconnectInternal(NetworkMessage netMsg)
    {
        throw new NotImplementedException();
    }

    private void OnClientConnectInternal(NetworkMessage netMsg)
    {
        throw new NotImplementedException();
    }
}

This file is pretty similar to the basics of the NetworkManager, yet it throws an error on Client.Connect(). The following error occurs whether or not there is a NetworkManager in the scene:
NullReferenceException: Object reference not set to an instance of an object

Any ideas? The Master Server in this case does not throw any errors or output any messages (it is using a NetworkManager).

Desktop:

  • OS: Windows
  • Build target: Windows
  • Unity version: 2018.2.14
  • Mirror branch: mirror

Server Shutdown, reconnect

Hi, thanks for this project! Mirror is awesome but we do need relay servers for our project so we are implementing a Transportlayer for the Photon Realtime API and came around an issue concerning the shutdown of a host.

After shutting down the server and reconnecting/rehosting, Mirror thinks that the old clients are still connected.

When calling NetworkServer.Shutdown Mirror calls ServerStop and we generate disconnect messages for every client still connected, but immediately stops polling these messages.

Those messages aren't getting polled cause s_ServerHostId is set to -1.

https://github.com/vis2k/Mirror/blob/6d33fae44f66c52062cc5db4136cfe4c7c7a12f7/Mirror/Runtime/NetworkServer.cs#L70-L71

https://github.com/vis2k/Mirror/blob/6d33fae44f66c52062cc5db4136cfe4c7c7a12f7/Mirror/Runtime/NetworkServer.cs#L350-L353

Starting the as host again NetworkServer.connections still includes old client connections.

What is the right way to tell mirror that there are no more clients connected?

Thanks in advance!
Greets, Andi

Missed synchronization

Describe the bug
HLAPI may fail to synchronize existing clients when a new client joins and an existing object is sent to him.

This is very hard to reproduce in real life, however I managed to reproduce it by doing data change inside "OnRebuildObservers" which happens to execute at the right time. In theory, if a new client connect between 2 synchronizations this can happen.

To Reproduce
Steps to reproduce the behavior:

  1. Download the repro project
  2. Import in a new unity project
  3. Make a build
  4. Run 2 or 3 stand alone instances.
  5. Hit play in the editor
  6. Start the editor as server only
  7. Connect the 3 standalone instances as clients
  8. Observe the 3 instances get different values (see screenshot)

Expected behavior
All 3 instances should have the same values

Screenshots
screen shot 2018-08-02 at 5 58 49 pm

Desktop (please complete the following information):

  • OS: MacOS (should work everywhere)
  • Build target: standalone
  • Unity version: 2017.4.7
  • HLAPI CE branch: improvements

Additional context
The root cause is: when a client connects, a spawn message will be sent for that client for any existing object. This will clear the dirty bits of existing objects. Any other client that was observing them will not be updated because the object will be considered clean.

The fix is not trivial at all. It is fixed in synctoowner because there is a fundamentally different way of handling dirty bits.

Error when building for Universal Windows Platform

Hy,
when I try to build a project for UWP, there are always 3 errors showing up, after the build finished successfully. I'll just attach text files containing the error messages, to keep this post readable. Nevertheless the build succeeded and I'm also able to deploy to Hololens, but these errors are confusing and maybe they'll cause errors in future development.

Is there something I'm missing or doing wrong?

Best regards :)

Operation system and version numbers

OS: Windows 10 x64
Unity: 2018.1.6f1, BuildTarget UWP
HLAPI Community Edition: 2018.1

LogFiles

ReferenceRewriterFoundSomeErrors.txt
ReferenceRewriterErrorMethodSystem.Void.txt
ReferenceRewriterErrorMethodSystem.UInt64.txt

unityconsolecapture

Lift message size limit

Currently we cannot send message larger than 65Kb
This is a problem that we inherited from UNET.

This limit is too small in some cases, such as sending images. We need to lift this limit to allow much larger message sizes.

Transport.layer is null

Describe the bug
When i try to start a server or quit my application i have this kind of error :

Mirror.NetworkServer.InternalListen (System.String ipAddress, System.Int32 serverPort, System.Int32 maxConnections) (at <91ed777b83ab48fba45ddff3b3dfe8ed>:0)

Or

Mirror.NetworkManager.OnApplicationQuit () (at <91ed777b83ab48fba45ddff3b3dfe8ed>:0)

I had a previous version of mirror from early september working.
I upgraded the files to the last one and now i have this error.

In these two functions there is Transport.layer called i suppose it isn't set properly.

Expected behavior
No error.

Desktop (please complete the following information):

  • OS: windows 100
  • Build target: in editor
  • Unity version: 2018.2.10f1
  • HLAPI CE branch: mirror-467

Maybe it's my fault, for upgrading i just closed the project and replaced the mirror files in the folder, like that i didn't lost any prefab with mirror component on it.

InvalidDataException breaks Unity builds

  1. use commit: 470afff
  2. copy dlls into Mirror asset store project
  3. open the Mirror project from asset store, open the movement demo scene with the green robot
  4. ctrl+b build
  5. in build, select host mode
    => see how robot doesn't spawn (it spawns in editor host mode, but not in build host mode)

open networkreader, change InvalidDataExceptions to IndexOutOfRangeException
rebuild
repeat
it works

wtf

we might need to report this to unity..

Duplicate initialize

I just noticed a bug in Mirrors code when reading it.. ill do a bug report. Its Very minor and not really having an effect but it could in future and its a 1 line correction.

Its simply NetworkServer.cs @ line ~ 113 / 118 "Initialize();"is called twice in a row if s_DontListen is false.. which is usually.

I would imagine remove the 1st one on line 113. Its not currently major as inside Initialize(); there is a check to make sure its not run again.. but no never a need to call it twice and ... oh it does nothing of note in Initialize but still shoudln't be called twice.

internal static bool InternalListen(string ipAddress, int serverPort, int maxConnections)
        {
            Initialize();

            // only start server if we want to listen
            if (!s_DontListen)
            {
                Initialize();

AssetIDs on Objects given with NetworkIdentities are zeroed out

Describe the bug
You'd think that when you place a NetworkIdentity script on a object on the scene, for example a cube that a AssetID is generated and assigned to the object so it can identify itself over the network, right? Well, apparently it's broken somehow in the latest versions of Mirror. See for yourself, this was a Cube that was created by the "Create -> Cube" menu option and I slapped a NetworkIdentity component on it to replicate this behaviour. AssetID should NOT be zeroed out.

image

In my network stress test project which makes simple capsules on an AI navmesh to emulate some network load you can see that this bug also causes OnObjSpawn errors.

image

Repro project
Downloadable from my OneDrive: Removed since it's obsolete (new project in thread below)

To Reproduce
Steps to reproduce the behavior:

  1. Open the attached project in Unity 2017.4.x
  2. Look in the inspector for the project items, you'll see a Cube prefab. Click and at the bottom of the inspector, look at the dropdown's Network Information option. Notice that assetID is all zeros.
  3. Drag this into the scene. Look again at the asset ID on the dragged in object.
  4. Now make another empty game object and give it Mirror's Network Manager. Assign this cube as the player prefab object. Also attach NetworkManagerHUD to the same game object as Network Manager.
  5. Start the play mode and click Host, you'll see the cube spawns without any error.
  6. Stop play mode, build a development mode standalone client. Run that and start the editor as the host, and connect the client to the editor.
  7. Boom, you will get the "OnObjSpawn: netID X has invalid asset ID" error as per screenshot 2 above (or there abouts)

Expected behavior
AssetIDs should be properly assigned per GameObject (not zeroed out) and not cause the OnObjSpawn error to occur when trying to spawn them in a network test environment.

Screenshots
See bug description.

Desktop (please complete the following information):

  • OS: Windows 10 Pro x64
  • Build target: Desktop Windows & Linux
  • Unity version: 2017.4.10f1
  • Branch: Mirror Bleeding Edge

Additional context
Have not tested with it in Unity 2018.x.

Handling multiple instances of component in same game object

Describe the bug
Having the following setup in the player prefab:
image

Will cause only the top (first) component of the same type to execute the command on the server when the client does the RPC.

Repro project
repro.zip

1- Run one editor instance in server mode.
2- Run one editor instance in client mode.
3- Press editor button in the second instance of the component.

Expected behavior
The same instance should receive the command and the bool should switch, not the first one of the game object.

Additional context
UNET behaves the same way. If this is expected behaviour would a fixed implementation be merged into mirror?

Add channels

Mirror should have a way to send messages in an unreliable channel.

This helps when doing voice or movement.

Incremental compiler

Describe the bug
Using the incremental compiler in unity 2018.2 causes this error
image

Repro project
Just import mirror into any project and install the incremental compiler. Once done create a network behaviour and the error will be thrown on compile.

To Reproduce
Steps to reproduce the behavior:

  1. import mirror into any project and install the incremental compiler.
  2. Create a network behaviour and the error will be thrown on compile.

Expected behavior
Weave to complete correctly and allow for continued development.

Desktop (please complete the following information):

  • OS: Windows
  • Build target: Standalone
  • Unity version: [e.g. 2018.2]
  • Master branch

Create a migration tool

Is your feature request related to a problem? Please describe.

From the migration guide:

Every networked prefab and scene object needs to be adjusted. They will be using NetworkIdentity from Unet, and you need to replace that componenent 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.

This is a difficult and error-prone process that could easily be automated with a search-and-replace script. I migrated my project with the search-and-replace function in VSCode and it worked really well.

Describe the solution you'd like

Create a program/script that goes through all prefab/scene files replaces all instances of the UnityEngine.Networking.NetworkIdentity script GUID with the Mirror.NetworkIdentity GUID. This can also be applied to other Mirror components, as well as certain required code changes:

  • using UnityEngine.Networking; -> using Mirror;
  • [Command(channel.*)]) -> [Command]
  • SyncListStruct -> SyncListSTRUCT
  • etc

Additional context
Obviously, users should be prompted to backup their project before migration.

One easy way to implement this would be as a PowerShell script:

# replace UnityEngine.Networking namespace usings
Get-ChildItem -recurse '*.cs' | ForEach {(Get-Content $_ | ForEach { $_ -replace '^[ \t]*using UnityEngine\.Networking;', 'using Mirror;' }) | Set-Content $_}
# remove command channels
Get-ChildItem -recurse '*.cs' | ForEach {(Get-Content $_ | ForEach { $_ -replace '^([ \t]*)\[Command\(channel.*\)\]', '$1[Command]' }) | Set-Content $_}
# ...

Migration of existing projects from UNET to Mirror

Is your feature request related to a problem? Please describe.
To make it easier to migrate existing projects from UNET to Mirror, it is necessary for existing prefabs, that their UNET components (NetworkIdentity, NetworkTransform, etc...) are replaced. As there are often a lot of different settings, it would be nice, if all properties would keep their values.

Describe the solution you'd like
Please have a look at the attached editor script for easier replacement of the UNET components.

Describe alternatives you've considered

Additional context

using System.IO;
using UnityEditor;
using UnityEngine;
using UnetNetworkIdentity = UnityEngine.Networking.NetworkIdentity;
using UnetNetworkTransform = UnityEngine.Networking.NetworkTransform;
using MirrorNetworkIdentity = Mirror.NetworkIdentity;
using MirrorNetworkTransform = Mirror.NetworkTransform;
using System;
using System.Reflection;

public class UnetToMirrorEditor : EditorWindow {
    [MenuItem("Window/Mirror/Replace UNET components")]
    private static void ReplaceComponents() {
        FindAndReplaceUnetComponents();
    }

    private static void FindAndReplaceUnetComponents() {

        int gameObjectCount = 0, netIdComponentsCount = 0, netTransformComponentCount = 0, fileCounter = 0;

        string[] files = Directory.GetFiles(Application.dataPath, "*.prefab", SearchOption.AllDirectories);
        gameObjectCount = files.Length;

        foreach (string file in files) {

            fileCounter++;
            EditorUtility.DisplayProgressBar("Mirror Migration Progress", string.Format("{0} of {1} files scanned...", fileCounter, files.Length), fileCounter / files.Length);

            string relativepath = "Assets" + file.Substring(Application.dataPath.Length);
            GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(relativepath);

            // replace UNET components with their mirror counterpart
            netTransformComponentCount = ReplaceNetworkComponent<UnetNetworkTransform, MirrorNetworkTransform>(prefab);

            // always replace NetworkIdentity as last element, due to dependencies
            netIdComponentsCount = ReplaceNetworkComponent<UnetNetworkIdentity, MirrorNetworkIdentity>(prefab);
        }

        EditorUtility.ClearProgressBar();
        Debug.Log(string.Format("Searched {0} GameObjects, found {1} UNET NetworkIdentity, {2} NetworkTransform components and replaced them with Mirror components.", gameObjectCount, netIdComponentsCount, netTransformComponentCount));
    }

    private static int ReplaceNetworkComponent<TSource, TDestination>(GameObject prefab) 
        where TSource : Component
        where TDestination : Component {

        int netTransformComponentCount = 0;
        TSource unetNetworkComponent = prefab.GetComponent<TSource>();
        if (unetNetworkComponent != null) {
            netTransformComponentCount++;

            // check for mirror component
            TDestination mirrorNetworkComponent = prefab.AddComponent<TDestination>();
            if (mirrorNetworkComponent == null) {
                mirrorNetworkComponent = prefab.GetComponent<TDestination>();
            }

            // copy values
            CopyProperties(unetNetworkComponent, mirrorNetworkComponent);

            // destroy UNET component
            DestroyImmediate(unetNetworkComponent, true);
        }

        return netTransformComponentCount;
    }

    // source: https://stackoverflow.com/questions/930433/apply-properties-values-from-one-object-to-another-of-the-same-type-automaticall
    private static void CopyProperties(object source, object destination) {

        // If any this null throw an exception
        if (source == null || destination == null)
            throw new Exception("Source or/and Destination Objects are null");

        // Getting the Types of the objects
        Type typeDest = destination.GetType();
        Type typeSrc = source.GetType();

        // Iterate the Properties of the source instance and  
        // populate them from their desination counterparts  
        PropertyInfo[] srcProps = typeSrc.GetProperties();
        foreach (PropertyInfo srcProp in srcProps) {
            if (!srcProp.CanRead) {
                continue;
            }

            PropertyInfo targetProperty = typeDest.GetProperty(srcProp.Name, 
                BindingFlags.DeclaredOnly |
                BindingFlags.Public |
                BindingFlags.Instance);

            if (targetProperty == null) {
                continue;
            }
            if (!targetProperty.CanWrite) {
                continue;
            }
            if (targetProperty.GetSetMethod(true) != null && targetProperty.GetSetMethod(true).IsPrivate) {
                continue;
            }
            if ((targetProperty.GetSetMethod().Attributes & MethodAttributes.Static) != 0) {
                continue;
            }
            if (!targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType)) {
                continue;
            }

            // Passed all tests, lets set the value
            targetProperty.SetValue(destination, srcProp.GetValue(source, null), null);
        }
    }
}

NetworkIdentity is not recognized when using a child of NetworkManager

Hello!

First, thank you for this project because it gives me hope! I was unhappy to hear that Unity was no longer taking care of UNET...

Unfortunately, I'm boring you with a bug report.

It seems to have a problem with the NetworkManager when I try to extend these features. Indeed, when I use a script that inherits from the NetworkManager and I try to fill it with a GameObject with a NetworkIdentity, the component does not seem to be recognized (it works on another project that does not use Mirror).

Thank you in advance for your work! :)

Best regards.

NB: I use Mirror 517 & Unity 2018.2.14f1

(Click the GIF to enlarge it)
networkmanagerfailed

NetworkTransformPreview NullReferenceException

Describe the bug
Selecting a GameObject with NetworkTransform causes null ref errors to pop up.
NetworkTransformPreview is accessing null properties of NetworkTransform (m_RigidBody2D, m_RigidBody3D) inside OnPreviewGUI method.

To Reproduce

  1. Open new project
  2. Import Mirror
    asset store (ver. 1.0) or latest git releases (333, 332, 313, 312 - didn't test further)
  3. Create gameobject, add rigidbody3d and network transform
  4. Unselect gameobject and select it again

Quick and dirty fix with dnspy

I'm storing references to all components inside GetNetworkInformation method, in OnPreviewGUI these are get by m_ReferenceTargetIndex and null checked.

[SyncVar] GameObject race condition

Just gathering my findings here.

The bug:
Player.cs has [SyncVar] GameObject pet;
Pet.cs has [SyncVar] GameObject owner;

In other words: circular references.

Now this player+pet are spawned at another client, here is what happens:

  1. Player component is spawned. pet is set to that pet, which doesn't exist yet (hence null)
  2. Pet component is spawned. owner is set to that player, which exists (see 1.). hence not null.

so instead of Player knowing Pet and Pet knowing Player, only Pet knows Player because it was spawned after Player. Player was spawned before Pet, so it doesn't know Pet.

What weaver does right now:
for every [SyncVar] GameObject player; it creates:

  1. a uint ___playerNetId;
  2. a Networkplayer property that does this:
public GameObject Networkplayer
  {
    get
    {
      return this.player;
    }
    [param: In] set
    {
      this.SetSyncVarGameObject(value, ref this.player, 8388608UL, ref this.____playerNetId);
    }
  }

The get just returns the original variable. The set sets calls SetSyncVarGameObject which sets dirty and then sets the original variable.
3. replaces all player = ... (writes) in code with NetworkPlayer = ....
4. In PreStartClient() assigns Networkplayer = ClientScene.FindLocalObject(__playerNetId)

Solution 1
What it should do is to also replace all ... = player (reads) with ... = Networkplayer and in Networkplayer get return ClientScene.FindLocalObject(___playerNetId)

In other words: for every [SyncVar] GameObject test variable it should wrap get/set around the __testNetId field. The netId is just an int, it doesn't matter when we receive it. The 'get' will simply return objects[netId] which is null if not spawned yet, or != null if spawned yet.

Solution 2
Spawn everything first. Then assign. Perhaps it's already meant to do that but it doesn't for some reason. The NetworkPlayer field is assigned in 'PreStartClient()' after all.

Syncvar hook function never called

Describe the bug
The hook function of a syncvar it's not called.

To Reproduce
Easy, create some syncvar.
Example:

[SyncVar(hook="OnHealthChange")] public float health;

,then the function
private void OnHealthChange(float theAmount) { health = theAmount; healthBar.SetValue (theAmount); }

final, change the health var value in server side and the OnHealthChange function never is called.

  • OS: Windows
  • Build target: editor
  • Unity version: 2017.4.7f1
  • HLAPI CE branch: last one

NetworkManager not designed well for inheritance.

When inheriting from NetworkManager (e.g. MyNetworkManager : NetworkManager), the base network manager's Awake function is not called, which is suppose to call private InitializeSingleton and public InitializeTransport.

Steps to reproduce the behaviour:

  1. Create class MyNetworkManager : NetworkManager.
  2. Attach to gameobject.

Expected behavior
Network transport and singleton should initialise. "Thank you for using Mirror" message should be logged.

Using Release: mirror-397

I solved this myself for the time being by calling base.awake via reflection in my own awake.

Using Mirror

So i fix my last problem but now i have problem with p2p

        public override bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error)
        {
            EP2PSend eP2PSendType = EP2PSend.k_EP2PSendReliable;

            var hostTopology = NetworkServer.active ? NetworkServer.hostTopology : NetworkManager.singleton.client.hostTopology;

            QosType qos = hostTopology.DefaultConfig.Channels[channelId].QOS;
            if (qos == QosType.Unreliable || qos == QosType.UnreliableFragmented || qos == QosType.UnreliableSequenced)
            {
                eP2PSendType = EP2PSend.k_EP2PSendUnreliableNoDelay;
            }

            if (SteamNetworking.SendP2PPacket(remoteSteamId, bytes, (uint)numBytes, eP2PSendType))
            {
                error = (byte)NetworkError.Ok;
                return true;
            }
            else
            {
                P2PSessionState_t state;
                if (SteamNetworking.GetP2PSessionState(remoteSteamId, out state))
                {
                    if (state.m_eP2PSessionError == (byte)EP2PSessionError.k_EP2PSessionErrorTimeout)
                    {
                        error = (byte)NetworkError.Timeout;
                    }
                    else
                    {
                        error = (byte)NetworkError.WrongHost;
                    }
                }
                else
                {
                    error = (byte)NetworkError.WrongConnection;
                }

                return false;
            }
        }
    }

and that was really good, now i don't have functions like numBytes or QosType and dunno how to fix this. Could you help me? Thanks!

Bug?

When i put all files on the unity editor and created server is all working but when client want join i've got error 'OnObjSpawn netId: 2 has invalid asset Id' why?

ClientScene::InternalAddPlayer: playerControllerId higher than expected: 0

I get a warning "ClientScene::InternalAddPlayer: playerControllerId higher than expected: 0" when NetworkManager has set Auto Create Player to false and you then spawn a player on the server.

Although its only a warning there is a simple fix in NetworkManager.cs :

        public override void OnClientConnect(NetworkConnection conn)
        {
            if (!clientLoadedScene)
            {
                // Ready/AddPlayer is usually triggered by a scene load completing. if no scene was loaded, then Ready/AddPlayer it here instead.
                if (autoCreatePlayer)
                {
                    ClientScene.Ready(conn);
                    ClientScene.AddPlayer(0);
                }
                else
                {
                    ClientScene.localPlayers.Add(new Mirror.PlayerController());
                    ClientScene.Ready(conn);
                }
            }
        }

        public override void OnClientSceneChanged(NetworkConnection conn)
        {
            if (autoCreatePlayer)
            {
                // always become ready.
                ClientScene.Ready(conn);

                // vis2k: replaced all this weird code with something more simple
                // add player if all existing ones are null (or if list is empty, then .All returns true)
                if (ClientScene.localPlayers.All(pc => pc.gameObject == null))
                {
                    ClientScene.AddPlayer(0);
                }
            }
            else
            {
                ClientScene.localPlayers.Add(new Mirror.PlayerController());
                ClientScene.Ready(conn);
            }
        }


Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.