Coder Social home page Coder Social logo

miragenet / mirage Goto Github PK

View Code? Open in Web Editor NEW
485.0 13.0 65.0 65.94 MB

Easy to use high performance Network library for Unity 3d

Home Page: https://miragenet.github.io/Mirage/

License: MIT License

C# 100.00% JavaScript 0.01%
unity unity3d game networking udp mirror mirror-networking mmo mmorpg webgl

mirage's People

Contributors

apkd avatar atikadze avatar atlv24 avatar beguiled avatar callumferguson avatar dependabot[bot] avatar dmerner avatar dragonslaya-ss avatar dragonslaya84 avatar erikas-taroza avatar hertzole avatar icezman001 avatar imerr avatar james-frowen avatar katori avatar konstantin890 avatar lymdun avatar michalpetryka avatar miwarnec avatar mrgadget1024 avatar paulohmattos avatar paulpach avatar phodoval avatar rxmarccall avatar semantic-release-bot avatar shulinnn avatar softwareguy avatar soren025 avatar timpickup 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

mirage's Issues

The automated release is failing 🚨

🚨 The automated release from the semver branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the semver branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


An error occurred while running git-snapshot

To https://github.com/MirrorNG/MirrorNG
! [rejected] e93232c0223b5fe8f775011868f2513d -> undefined (non-fast-forward)
error: failed to push some refs to 'https://github.com/MirrorNG/MirrorNG'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. Check out this branch and integrate the remote changes
hint: (e.g. 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details..


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

breaking: Adopt C# coding conventions

This will require changes in your game.

Official conventions can be found here:

The goal of this feature is to adopt official c# coding conventions. A good summary can be found here:

The goal is consistency, any code that does not adhere to these convention is to be considered a defect.

Some things where Mirror violate conventions include

  • use var when type is obvious from right hand side
  • use PascalCase for public fields and properties

This is a very easy way to get started, find a public field that violates the convention and open a pull request.

Direct Transport Send

Feature request from Discord:

JamesFrowen: speaking of relays, does NG have a way to send to multiple connections at once?
JamesFrowen: ye, like if a host wants to send the same message to 6 players, does it need to send 6 message or can it just be 1 message and the relay then does the 6 sends

tests: Improve test coverage

After the singletons are gone, the goal is to develop a comprehensive test suite that ensures the quality of the code.

Coverage will be tracked and reports should be produced automatically with every commit.

remove offline/online scene

This part is very complicated and none of us is using it.

Let's remove it so that we can continue our refactoring. We can revisit this (admittedly useful) feature after the dust settles.

NetworkClient spawn handlers are not being called

Describe the bug
Registering a spawn handler on NetworkClient using the RegisterPrefab method will not call the spawn handler when it needs to.

To Reproduce

  1. Create a script and register a prefab with a spawn handler and an unspawn handler to the NetworkClient in the scene.
  2. Add a Debug.Log message for each handler.
  3. Add a way to spawn said prefab.
  4. Build the project and start a server.
  5. Connect through the editor and notice how it doesn't log a message when you spawn an object.

Expected behavior
The spawn handler method should be called.

Desktop (please complete the following information):

  • OS: Windows 64-bit
  • Build target: Windows 64-bit
  • Unity version: 2020.1b12
  • Mirror branch: UPM

Additional context
This is the important part! I've already found a way to seemingly solve the issue. In the SpawnPrefab method in NetworkClient it tries to get the prefab first using the GetPrefab method. If it succeeds, it will return and stop there. If it doesn't succeed it will go to the spawn handler. Most of the time it will succeed and never call the spawn handler. If you switch the two ifs around so the
if (spawnHandlers.TryGetValue(...
is first the spawn handler will be called. If there's no spawn handler it should spawn the object like normal.
Usually, when you provide a spawn handler you want it to be called, so I don't see an issue with checking for the spawn handler first.

Since the solution and issue have already been figured out I didn't provide a project to reproduce it with.

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


Invalid npmPublish option.

The npmPublish option option, if defined, must be a Boolean.

Your configuration for the npmPublish option is false,.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

NRE in [SyncVar] NetworkIdentity when set for a newly instantiated GameObject

Describe the bug
Instantiating a go, setting a [SyncVar] NetworkIdentity on one of its components, and then Using Server.Spawn(go); causes NullReferenceException

System.NullReferenceException: Object reference not set to an instance of an object
at Mirror.NetworkBehaviour.GetSyncVarNetworkIdentity (System.UInt32 netId, Mirror.NetworkIdentity& identityField) [0x00011] in C:\Unity\MirrorNG - SyncVar initialization bug\Assets\Mirror\Runtime\NetworkBehaviour.cs:397 
at TestComp.get_NetworkIdentity () <0x1756d80e490 + 0x00072> in <157148441a354f5e811588a77f5b3f35>:0 
at TestComp.set_NetworkIdentity (Mirror.NetworkIdentity value) [0x0000d] in <157148441a354f5e811588a77f5b3f35>:0 
at Test.TestSpawn () [0x0000d] in C:\Unity\MirrorNG - SyncVar initialization bug\Assets\Test.cs:33 

To Reproduce

  • Create a server in Host mode
  • Spawn a GameObject - use NetworkServer.Authenticated UnityEvent to call the spawn function:
//code in spawn function
var go = GameObject.Instantiate(prefab);
go.GetComponent<TestComp>().Identity = NetIdentity;
Server.Spawn(go);
  • press Play and check Console for NRE

Desktop (please complete the following information):

  • OS: Windows
  • Build target: Unity Editor
  • Unity version: 2019.4.10f1
  • MirrorNG version: v49.2.1

Additional context
The problem is the same with a remote client instead of host mode

Missing meta file for Packages/com.mirrorng.mirrorng/CHANGELOG.md

Describe the bug
The branch upm missing Packages/com.mirrorng.mirrorng/CHANGELOG.md.meta file (and all release tags based on it). When install package via registry, the package is read only. So Unity will keep complains the error without creating a meta file.

Read only asset Packages/com.mirrorng.mirrorng/CHANGELOG.md has no meta file.

Solution

  1. add the missing CHANGELOG.md.meta
    2. Because of the upm branch is changed, the [publish_upm.sh](https://github.com/MirrorNG/MirrorNG/blob/master/publish_upm.sh) will fail
    git subtree push --prefix=Assets/Mirror origin upm
     ! [rejected] ...
    
    Workaround
    git checkout upm
    git merge -s subtree master --allow-unrelated-histories -q
    git push -u origin upm
    
    other scripts...
    

Server Event Listener's

Describe the bug
I have gotten messages and d/c issues for a script that attaches itself to netidentity.server.onstart. The script itself is a server command label with [Server] above the method. The method it hand on my side is registered to a listener of health change event. Both server and client register to this on my end. I placed a if(!IsServer) check before the netidentity.server.OnstartServer listener and it solved the issue.

Expected behavior
I expected that if i am registering to a listener for server that it only ever will get fired on the server. But current behavior tells me that this also fires on the client when client receives a message that he has started up on server or something?

Failure to get NetworkIdentity of scene objects during OnDestroy

I'm getting an error if one of my script is trying to access the NetworkIdentity of the same scene object while not connected to any server yet.
I suspect 266dc8d being the cause, since GetComponent should be able to grab the NI component.

Errors being "There is no NetworkIdentity on X. Please add one." (while there is one already) & the following NRE
Mirror.NetworkBehaviour:get_NetIdentity() (at Library/PackageCache/[email protected]/Runtime/NetworkBehaviour.cs:153)

To Reproduce

  • Create a scene object with a Network Identity component
  • Add a script which uses NetIdentity from its NetworkBehaviour to this scene object
  • Play game, stop, get errors

Tests Failing In CI/CD Pipeline

SetUp : System.AggregateException : One or more errors occurred.
----> System.NullReferenceException : Object reference not set to an instance of an object

--SetUp
at Mirror.Tests.AsyncUtil+d__0.MoveNext () [0x0006e] in /github/workspace/Assets/Mirror/Tests/Common/AsyncUtil.cs:16
at UnityEngine.TestTools.BeforeAfterTestCommandBase1+<ExecuteEnumerable>d__9[T].MoveNext () [0x00121] in /github/workspace/Library/PackageCache/[email protected]/UnityEngine.TestRunner/NUnitExtensions/Commands/BeforeAfterTestCommandBase.cs:62 --NullReferenceException at Mirror.Tests.ClientServerSetup1+<b__14_0>d[T].MoveNext () [0x003ef] in /github/workspace/Assets/Mirror/Tests/Runtime/ClientServerSetup.cs:82

SetUp : System.AggregateException : One or more errors occurred.
----> System.NullReferenceException : Object reference not set to an instance of an object

--SetUp
at Mirror.Tests.AsyncUtil+d__0.MoveNext () [0x0006e] in /github/workspace/Assets/Mirror/Tests/Common/AsyncUtil.cs:16
at UnityEngine.TestTools.BeforeAfterTestCommandBase1+<ExecuteEnumerable>d__9[T].MoveNext () [0x00121] in /github/workspace/Library/PackageCache/[email protected]/UnityEngine.TestRunner/NUnitExtensions/Commands/BeforeAfterTestCommandBase.cs:62 --NullReferenceException at Mirror.Tests.ClientServerSetup1+<b__14_0>d[T].MoveNext () [0x003ef] in /github/workspace/Assets/Mirror/Tests/Runtime/ClientServerSetup.cs:82

MirrorNG meets OpenUPM

Please explain the suggested feature in detail.

Hi @paulpach,

I have followed a few threads on the upstream repo, then I found your MirrorNG fork. A great move! I'm the creator of OpenUPM, a public upm registry with automatic build pipelines that publish new package bundle based on valid git tags. You can read the announcement on medium to get the basic idea, so far it hosts 100+ packages as of Jan 2020.

UPM offering better version and dependency management, is the future to delivery reusable component in the Unity Engine. I have added your work to the platform. To make it useful, could you please create a GitHub release 4.0.0 from the upm branch?

Or maybe to make the version string different enough from the original mirror project, try out something bigger than 6.x.y? I will suggest a pattern like mirror: x.y.z => mirrorng: 1x.y.z, i.e. 6.x.y => 16.x.y

Thought?

NetworkServer does not call SpawnObjects

Describe the bug
Currently NetworkManager (via StartHost/StartServer) and NetworkSceneManager (via Scene changing) are required to get objects to spawn. Adding SpawnObjects() to the Started event does not currently work as it fires too early. The server is not actually started yet.

Can you suggest a possible solution?
Started.Invoke() could be moved to fire later in the startup process allowing it to call SpawnObjects() once the Server is actually started. But I cannot find a location any later in NetworkServer than where it exists currently.

Issue when doing StartHost after a StopHost call.

Describe the bug
When stopping the server and then starting it again causes all scene objects with network behaviours to get destroyed.

And when running the project in the Unity Editor.
All scene objects with network behaviours get destroyed on the first StartHost call instead. To fix this you have either restarted unity or force a script compile.

Repro project
https://drive.google.com/file/d/1T-wNEG8RdG-I30N9prCUU2WQdF707kvm/view?usp=sharing

To Reproduce
Steps to reproduce the behavior:

  1. Open the attached project
  2. Open Scenes/SampleScene
  3. Enter play mode
  4. Look at the NetworkBehaviour GameObject being destroyed on StartHost the second time.

Expected behavior
Scene Objects with Network Behaviours should not be deleted when doing StopHost.

Desktop:

  • OS: [Windows]
  • Unity version: [2020.2.1f1]
  • Mirror branch: [master]

Weaver does not appear to run in-editor after PR #537

Describe the bug
PR #537 breaks custom network messages in the editor

Repro project
https://github.com/VirtualBrightPlayz/MirrorNGBug

To Reproduce
Steps to reproduce the behavior:
Install com.unity.nuget.mono-cecil via git URL
Install UniTask via git URL. via git URL.
Install MirrorNG from source.
Send a custom message struct.
An error or two should then be outputted to the console.

Expected behavior
Custom network messages send without error.

Screenshots
image

Desktop (please complete the following information):

  • OS: Windows 10 64-bit
  • Build target: Standalone
  • Unity version: 2020.1.17
  • Mirror branch: master/any version after PR #537

Additional context
Setting line 51 of MirrorILPostProcessor.cs to return usesMirror; instead of return usesMirror && !usesMirrorEditor; seems to fix the issue.

Hidden exception is being thrown if local player object has owned objects when closing server

Describe the bug
If your local player object (that's spawned by the PlayerSpawner script) is spawning objects that have the local player as the owner and the server stops, a hidden NullReferenceException is being thrown in the DestroyOwnedObjects method in the NetworkConnection class. It seems to be because it's destroying itself first and calling the Reset method on itself before destroying the child objects. This causes the Identity.Server property to be null, thus causing the NullReferenceException.

The NullReferenceException is also being thrown silently. It is never shown (probably due to Async methods), so a way to bring them forward to the main thread probably wouldn't hurt, in case something goes wrong.

Due to this, the rest of the code isn't being called in the NetworkServer.OnDisconnected method. That means the LocalConnection isn't being reset and this stops you from properly hosting another server.

Repro project
Mirror Hosting Bug.zip

To Reproduce
Steps to reproduce the behavior:

  1. Open the attached project that you can get above.
  2. Go into Scenes/SampleScene.scene
  3. Enter play mode and start hosting. Notice how the prefab 'Network Player' is being spawned.
  4. Right after stop hosting and then try again. Notice how this time it isn't being spawned. That's because the server hasn't been started properly, as mentioned above.

Expected behavior
Every object is destroyed properly and that you can start hosting again.

Desktop (please complete the following information):

  • OS: Windows 64-bit
  • Build target: Windows 64-bit
  • Unity version: 2020.1b12
  • Mirror branch: master

Server | Client On NetIdentities Null

We use the netidentity.start and netidentity.client to register for listener's in onenable. This causes alot of headache at times its fine other times it is not. I do have a static manager for network manager so its easily resolved for me because server and client variables on the networkmanager are set up before anything else.

I use object pooling so I must disable and enable objects on the fly with it and I need to know when it starts up on server or client to setup different data and this causes issues because 4/10 the client and server variable under netidentity has not been setup.

I have not had chance look at code yet to know when mirrorng setups these variables but will do so. Placing this here for future people until this can be resolved. The variables should be populated on awake or start before enable gets fired.

Message serialization error

Describe the bug
Sending custom message is throwning errors also writing custom serialization/deserialization methods is not working.

"No writer found for SimulationSettings. See https://mirrorng.github.io/MirrorNG/Articles/General/Troubleshooting.html for details
UnityEngine.Debug:AssertFormat(Boolean, String, Object[])"

Expected behavior
Serialization methods to be autogenerated and custom serializers to be used when they are declared.

Additional context
I even get this from the BasicAuthenticator

ServerObjectManager fails to instantiate prefabs on client

Describe the bug
Upgrading my project to v56.3.4 I had to replace Server.Spawn etc with serverObjectManager.Spawn etc
After doing that I noticed on a remote client (server in host mode) the prefabs don't show up as GameObjects (also not shown in Hierarchy).
There were no errors and no related warnings as usually expected.

My Code
In my project multiple Spawn commands didn't seem to have any effect on the client.

  • one Spawn called by NetworkServer.Authenticated UnityEvent
  • and the other inside Update loop
    I hope you can make sure both cases work properly

Additional info
It is possible I didn't have the Spawn Prefabs referenced. I noticed those were deleted when I reverted to a version before ServerObjectManager was introduced. So perhaps v56.3.4 failed to show related errors/warnings. (possible bug)
After reverting everything and adding the Spawn Prefabs everything worked properly again.

In case the Spawn Prefabs were referenced then the bug is that the prefabs weren't instantiated on the remote client.

InvalidMessageException after v62.5.3 (PR 537)

Describe the bug
Using v62.5.3 or later causes InvalidMessageException when client connects. Tested with 2019.4.18f1 LTS, using Basic sample scene.

  • v62.5.2 works
  • v62.5.3 doesn't (tested with v62.9.1 as well)

To Reproduce

  1. In a blank project, follow standard installation: https://github.com/MirrorNG/MirrorNG#installation
  2. Add sample: Basic
  3. Follow Basic setup steps (build example scene)
  4. Play standalone build & editor, using one as host and the other as client (doesn't matter which).
  5. Observe InvalidMessageException on client.

Desktop (please complete the following information):

  • OS: Windows 10
  • Build target: standalone
  • Unity version: 2019.4.18f1 LTS
  • Mirror branch: MirrorNG

Exception

: Closed connection: connection([::1]:7777). Invalid message Mirror.InvalidMessageException: OnDeserialize failed for: object=Player(Clone) component=Mirror.Examples.Basic.Player sceneId=0. Possible Reasons:
  * Do Mirror.Examples.Basic.Player's OnSerialize and OnDeserialize calls write the same amount of data? 
  * Was there an exception in Mirror.Examples.Basic.Player's OnSerialize/OnDeserialize code?
  * Are the server and client the exact same project?
  * Maybe this OnDeserialize call was meant for another GameObject? The sceneIds can easily get out of sync if the Hierarchy was modified only in the client OR the server. Try rebuilding both.


  at Mirror.NetworkIdentity.OnDeserializeSafely (Mirror.NetworkBehaviour comp, Mirror.NetworkReader reader, System.Boolean initialState) [0x00021] in A:\unity_tests\net_test_2019_4_LTS\Library\PackageCache\[email protected]\Runtime\NetworkIdentity.cs:898 
  at Mirror.NetworkIdentity.OnDeserializeAllSafely (Mirror.NetworkReader reader, System.Boolean initialState) [0x0002a] in A:\unity_tests\net_test_2019_4_LTS\Library\PackageCache\[email protected]\Runtime\NetworkIdentity.cs:915 
  at Mirror.ClientObjectManager.ApplySpawnPayload (Mirror.NetworkIdentity identity, Mirror.SpawnMessage msg) [0x000db] in A:\unity_tests\net_test_2019_4_LTS\Library\PackageCache\[email protected]\Runtime\ClientObjectManager.cs:339 
  at Mirror.ClientObjectManager.OnSpawn (Mirror.SpawnMessage msg) [0x00118] in A:\unity_tests\net_test_2019_4_LTS\Library\PackageCache\[email protected]\Runtime\ClientObjectManager.cs:374 
  at Mirror.NetworkConnection+<>c__DisplayClass24_0`1[T].<RegisterHandler>b__0 (Mirror.INetworkConnection _, T value) [0x00001] in A:\unity_tests\net_test_2019_4_LTS\Library\PackageCache\[email protected]\Runtime\NetworkConnection.cs:152 
  at Mirror.NetworkConnection+<>c__DisplayClass22_0`1[T].<MessageHandler>g__AdapterFunction|0 (Mirror.INetworkConnection conn, Mirror.NetworkReader reader, System.Int32 channelId) [0x00025] in A:\unity_tests\net_test_2019_4_LTS\Library\PackageCache\[email protected]\Runtime\NetworkConnection.cs:121 
  at Mirror.NetworkConnection.InvokeHandler (System.Int32 msgType, Mirror.NetworkReader reader, System.Int32 channelId) [0x00014] in A:\unity_tests\net_test_2019_4_LTS\Library\PackageCache\[email protected]\Runtime\NetworkConnection.cs:259 
  at Mirror.NetworkConnection.TransportReceive (System.ArraySegment`1[T] buffer, System.Int32 channelId) [0x00011] in A:\unity_tests\net_test_2019_4_LTS\Library\PackageCache\[email protected]\Runtime\NetworkConnection.cs:295 
UnityEngine.Logger:LogError(String, Object)
Mirror.ILoggerExtensions:LogError(ILogger, Object) (at Library/PackageCache/[email protected]/Runtime/LogFactory.cs:43)
Mirror.NetworkConnection:TransportReceive(ArraySegment`1, Int32) (at Library/PackageCache/[email protected]/Runtime/NetworkConnection.cs:303)
Mirror.<ProcessMessagesAsync>d__40:MoveNext() (at Library/PackageCache/[email protected]/Runtime/NetworkConnection.cs:352)
Cysharp.Threading.Tasks.CompilerServices.AsyncUniTask`1:Run() (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/CompilerServices/StateMachineRunner.cs:189)
Cysharp.Threading.Tasks.AwaiterActions:Continuation(Object) (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/UniTask.cs:21)
Cysharp.Threading.Tasks.UniTaskCompletionSourceCore`1:TrySetResult(Int32) (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/UniTaskCompletionSource.cs:139)
Cysharp.Threading.Tasks.CompilerServices.AsyncUniTask`2:SetResult(Int32) (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/CompilerServices/StateMachineRunner.cs:328)
Cysharp.Threading.Tasks.CompilerServices.AsyncUniTaskMethodBuilder`1:SetResult(Int32) (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/CompilerServices/AsyncUniTaskMethodBuilder.cs:201)
Mirror.KCP.<ReceiveAsync>d__35:MoveNext() (at Library/PackageCache/[email protected]/Runtime/Transport/Kcp/KcpConnection.cs:248)
Cysharp.Threading.Tasks.CompilerServices.AsyncUniTask`2:Run() (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/CompilerServices/StateMachineRunner.cs:313)
Cysharp.Threading.Tasks.AwaiterActions:Continuation(Object) (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/UniTask.cs:21)
Cysharp.Threading.Tasks.UniTaskCompletionSourceCore`1:TrySetResult(AsyncUnit) (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/UniTaskCompletionSource.cs:139)
Cysharp.Threading.Tasks.AutoResetUniTaskCompletionSource:TrySetResult() (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/UniTaskCompletionSource.cs:386)
Mirror.KCP.KcpConnection:InputReliable(Byte[], Int32) (at Library/PackageCache/[email protected]/Runtime/Transport/Kcp/KcpConnection.cs:161)
Mirror.KCP.KcpConnection:RawInput(Byte[], Int32) (at Library/PackageCache/[email protected]/Runtime/Transport/Kcp/KcpConnection.cs:135)
Mirror.KCP.<ReceiveLoop>d__7:MoveNext() (at Library/PackageCache/[email protected]/Runtime/Transport/Kcp/KcpClientConnection.cs:51)
Cysharp.Threading.Tasks.CompilerServices.AsyncUniTaskVoid`1:Run() (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/CompilerServices/StateMachineRunner.cs:104)
Cysharp.Threading.Tasks.AwaiterActions:Continuation(Object) (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/UniTask.cs:21)
Cysharp.Threading.Tasks.UniTaskCompletionSourceCore`1:TrySetResult(Object) (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/UniTaskCompletionSource.cs:139)
Cysharp.Threading.Tasks.DelayPromise:MoveNext() (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/UniTask.Delay.cs:520)
Cysharp.Threading.Tasks.Internal.PlayerLoopRunner:RunCore() (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/Internal/PlayerLoopRunner.cs:175)
Cysharp.Threading.Tasks.Internal.PlayerLoopRunner:Update() (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/Internal/PlayerLoopRunner.cs:145)
Cysharp.Threading.Tasks.Internal.PlayerLoopRunner:Run() (at Library/PackageCache/com.cysharp.unitask@7d21a75ea8/Runtime/Internal/PlayerLoopRunner.cs:104)

Client unable to connect host using MultiplexTransport

Describe the bug

As the title says, I got this exception while trying to connect a host using MultiplexTransport

NetworkServer is not active. Cannot spawn objects without an active server

Repro project
https://github.com/JeffersonFerreira/MirrorNG_WebsocketTest

To Reproduce

  1. Open the project
  2. Make a build for desktop
  3. Play the game in editor
  4. Open the game build
  5. See exception on console

Expected behavior
2 dummy players should appear on both Host and Client

Screenshots
Apparently the first exception is just UniTask giving an extra information

Multiplex Exception

Desktop (please complete the following information):

  • OS: Windows 10
  • Build target: Windows
  • Unity version: 2019.4.6f1
  • Mirror branch: Master

Additional context
There is not button to start host / client, ConnectionController script will handle it automatically

OnEnable/OnDisable

Describe the bug
Since going to events. Most events usually sit in OnEnable / OnDisable. Thats where i put most of the events to tap into for OnStartServer or OnStartClient etc. Some of the objects like my bullets and smooth sync seem to not like it. It randomly at times fires the OnEnable before Server is set inside of the NetworkBehaviour.

Repro project
My Project is huge. I will try to setup something with examples.

To Reproduce
Place a Server.Active check inside of OnEnable of a NetworkBehaviour script of an object being spawned in. It will give errors.

Expected behavior
Expected behaviour would be to have the setting of variables way before OnEnable and OnDisable ever fires off like in awake or Start. Im not sure how or where the Server variable gets set inside of NetworkIdentity.

Screenshots
@uweenukr Was helping me and saw most of my screenshots if need be I can take more.

Desktop (please complete the following information):

  • Windows 10 x64
  • standalone unity editor
  • 2019.4.0f1
  • MirrorNG upm

Scene Switch Causing Null Client Connection

Describe the bug
When changing from one scene to another the client connection in NetMan is null throwing this error:

NullReferenceException: Object reference not set to an instance of an object
Mirror.NetworkManager.RegisterClientMessages (Mirror.NetworkConnection connection) (at Assets/Mirror/Runtime/NetworkManager.cs:671)
Mirror.NetworkManager.StartHostClient () (at Assets/Mirror/Runtime/NetworkManager.cs:332)
Mirror.NetworkManager.FinishStartHost () (at Assets/Mirror/Runtime/NetworkManager.cs:323)
Mirror.NetworkManager.FinishLoadSceneHost () (at Assets/Mirror/Runtime/NetworkManager.cs:575)
Mirror.NetworkManager.FinishLoadScene () (at Assets/Mirror/Runtime/NetworkManager.cs:545)
Mirror.NetworkManager.UpdateScene () (at Assets/Mirror/Runtime/NetworkManager.cs:530)
Mirror.NetworkManager.LateUpdate () (at Assets/Mirror/Runtime/NetworkManager.cs:165)

Breakpoint on NetworkManager.cs:332

When the first StartHost load is done the connection is NOT null.

Once a scene switch is made it fires again. This time the client connection IS null.

Repro project
branch: sceneSwitchExample

To Reproduce
Steps to reproduce the behavior:

  1. Open the Main scene
  2. Click on Play > StartHost
  3. Click on Room1 or Room2
  4. See error

Expected behavior
Should move to either seem seamlessly

Desktop (please complete the following information):

  • OS: Windows
  • Build target: Editor
  • Unity version: 2019.3.7
  • Mirror branch: Master

Networked objects not being destroyed after StopHost in host mode

Describe the bug
After stopping the host mode via StopHost, the objects spawned by the server in host scene are not properly destroyed. Their "Is Server" and "Is Client" properties are both set to false though.

Repro project
Attached a simple repro project.

To Reproduce
Steps to reproduce the behavior:

  1. Open the attached project '...'
  2. Start the game
  3. Spawn some networked objects by the player by clicking left mouse button
  4. Click Stop Host in top left corner
  5. Observe the objects not being destroyed in the scene.

Expected behavior
There should be no networked objects left after the server is stopped.

Desktop:

  • OS: Windows 10 64bit
  • Build target: Windows standalone
  • Unity version: 2020.1.11
  • Mirror branch: latest master
    MirrorNGReproNoDestroy.zip

manager.client.Disconnected is raised twice

Confirmed on hostmode, not in server only mode.

Stacktraces:

UnityEngine.Events.UnityEvent:Invoke()
Mirror.NetworkClient:HandleClientDisconnect() (at Library/PackageCache/com.mirrorng.mirrorng@29.1.0/Runtime/NetworkClient.cs:489)
Mirror.ULocalConnectionToServer:DisconnectInternal() (at Library/PackageCache/com.mirrorng.mirrorng@29.1.0/Runtime/LocalConnections.cs:114)
Mirror.ULocalConnectionToClient:Disconnect() (at Library/PackageCache/com.mirrorng.mirrorng@29.1.0/Runtime/LocalConnections.cs:43)
Mirror.NetworkServer:RemoveLocalConnection() (at Library/PackageCache/com.mirrorng.mirrorng@29.1.0/Runtime/NetworkServer.cs:234)
Mirror.NetworkClient:Disconnect() (at Library/PackageCache/com.mirrorng.mirrorng@29.1.0/Runtime/NetworkClient.cs:283)
Mirror.NetworkManager:StopClient() (at Library/PackageCache/com.mirrorng.mirrorng@29.1.0/Runtime/NetworkManager.cs:407)
Mirror.NetworkManager:StopHost() (at Library/PackageCache/com.mirrorng.mirrorng@29.1.0/Runtime/NetworkManager.cs:376)```


UnityEngine.Events.UnityEvent:Invoke()
Mirror.NetworkClient:HandleClientDisconnect() (at Library/PackageCache/com.mirrorng.mirrorng@29.1.0/Runtime/NetworkClient.cs:489)
Mirror.NetworkClient:Disconnect() (at Library/PackageCache/com.mirrorng.mirrorng@29.1.0/Runtime/NetworkClient.cs:293)
Mirror.NetworkManager:StopClient() (at Library/PackageCache/com.mirrorng.mirrorng@29.1.0/Runtime/NetworkManager.cs:407)
Mirror.NetworkManager:StopHost() (at Library/PackageCache/com.mirrorng.mirrorng@29.1.0/Runtime/NetworkManager.cs:376)

ServerOnly does not clean up network objects on StopServer

Please explain the suggested feature in detail.
ServerOnly does not clean up network objects on StopServer. Can be seen in the ChangeScene example. Start as ServerOnly. StopServer. See the network objects remain.

How exactly does this keep you from releasing your game right now?
May be part of the cause of #235

Can you suggest a possible solution?
Use similar logic to what the client is using to loop through the Spawned collection and destroy

ServerSceneChanged event invoked twice on server start

Describe the bug
ServerSceneChanged event on NetworkSceneManager gets invoked twice when starting the server.

Repro project
Add a Game object to Basic example with the following script.

To Reproduce
Steps to reproduce the behavior:

  1. Open Basic example.
  2. Add empty game object.
  3. App CallbackTest.
  4. Enter playmode

Expected behavior
ServerSceneChanged gets fired once.

Actual behavior
ServerSceneChanged gets fired twice.

Desktop

  • OS: Windows 10
  • Build target: Standalone x64
  • Unity version: 2020.1
  • Mirror branch: 59.2.0

Batch Messaging/Tick Based

Many users and onlookers have requested the ability to batch outgoing msgs together. Somewhat related to the changes required to make that happen would provide support for Tick Based instead of sending as soon as the msg is generated.

Below I will paste some of the discussion from Discord:

[3:22 AM] Coburn: You can use FixedUpdate, but you need to ensure you don't multi-update the network if it's doing catchup
[3:23 AM] Coburn: I've done that in my transport - just flick a bool in Fixed Update once it's done, then skip all FU calls until LateUpdate fires and resets the bool
[3:23 AM] Coburn: LateUpdate applies stuff too late - the simulation would have already changed and you're applying changes on that
[3:23 AM] Coburn: FixedUpdate in the pipeline fires before Update when it's called from top-to-bottom
[3:24 AM] Coburn: If you're sending stuff to the transport, you could do LateUpdate
[3:24 AM] Coburn: use FixedUpdate for applying things to the simulation, LateUpdate for pushing the shit out

[10:09 AM] uwee: Thoughts on batch/tick msgs by using the included TcpTransport as a first test.

  1. TcpTransport : Transport is a MonoBehaviour which means it gives access to XUpdate for this change. But the Transport class does not handle any of the actual msg processing. So its of no use.
  2. That Transport is handed to the NetworkClient or NetworkServer during connect and used to create an INetworkConnection (NetworkConnection by default). This is not a Monobehaviour so it has no access to XUpdate. New constructors could be made to pass in the NC or NS creating the NetworkConnection (or alternate derived from interface) but that is not ideal.
  3. The NetworkConnection does all of the msg packing but the final 'across the network' call is inside the NetworkConnections IConnection which for the TcpTransport is a class called TcpConnection. This is also not a MonoBehaviour so there is no access to XUpdate.

Currently not sure where to approach this from. I tried creating an alternative NetworkConnection (BatchedNetworkConnection) but as mentioned above I had no way to pull XUpdate for timing. NetworkConnection does reference and Identity that would have its own access to XUpdate but the Identity does not exist before spawning so it cant be used.
[10:22 AM] uwee: doing it at NetworkConnection is the only option that would mean its Transport agnostic
[1:11 PM] uwee: Doing it a layer higher at NetworkClient/NetworkServer is that the NetworkConnection.Send is publicly accessable and classes like NetworkBehaviour, NetworkSceneManager, NetworkTime user the NetworkConnection.Send instead of the one provided in NC/NS for various ease of use reasons. While its probably possible to change those references to use NC/NS instead it would not prevent a user from doing the same.

The visibility of NetworkConnection.Send could also be changed to internal to fix the user accessibility concerns. But that seems like the wrong way to go about this.

Also it would mean that the implementation would differ between NC and NS as NS has to keep track of which connection specifically its being targeted where NC only has one.
[1:12 PM] uwee: Although there is a potential benefit of batching SendToAll and SendToReady at this layer. Since all of those targets would be getting the exact same information. you could cache it and not pack individual msgs

StopClient() is causing crash

Describe the bug
When calling StopClient(), the entire game is crashing. Also the client isn't properly disconnected from the server.

Expected behavior
Client should be properly disconnected from the server, and no crash should be involved.

breaking: error handling

Mirror does a poor job at handling errors.

Many methods return false if they fail... and we don't check the results.
Other methods return null when there is an error, and we fail to check for null, which means a NullReferenceException waiting to happen.

Any such case will be considered a defect.

A method should either succeed or throw an exception. No other result should be possible.
It is valid to return true, false or null if those are valid responses, not to signal errors.

NetworkServer.Disconnect() never calls NetworkServer.Cleanup() and NetworkServer.Active remains true

Describe the bug
Upon calling Server.Disconnect() on an active server, Server.Active is never set to false. Internal Server.Cleanup() is never called.

Repro project
MirrorNG Server Disconnect Test.zip

To Reproduce
Steps to reproduce the behavior:

  1. Open the attached project.
  2. Open 'Example' scene.
  3. Enter play mode.
  4. Note "Server Active: False" in the middle of the game view.
  5. Press "Start Host".
  6. Note "Server Active: True".
  7. Press "Stop network".
  8. Note "Server Active: True" still.

Expected behavior
Label should read "Server Active: False" since Server.Active should return false after the server has been disconnected.

Desktop:

  • OS: Windows 10
  • Build target: Editor
  • Unity version: 2020.1
  • Mirror branch: master

Additional context
I'm using KCP Transport.

You get the same result from "Start Server Only".

The server bug could not be reproduced with v51.1.4 using TCP Transport.

Similarly, using "Start Client Only" and then disconnecting, you still get "Client Active: True". But that only happens in Client-Only mode, not in Host mode. This one, however, could be reproduced with TCP Transport. This one is most likely a separate issue.

bug: ServerOnly still sends data to Client

NetworkIdeneity set to ServerOnly will still send SyncVars to clients. Repro via the ChangeScene example where the client is in editor (to easily view the warnigns) and the server is in standalone.

image

ServerOnly only checked in 2 places:

image

NetowkrIdentity.cs:116
public bool IsClient => Client != null && Client.Active && NetId != 0 && !serverOnly;

NetworkServer.cs:914

internal void SendSpawnMessage(NetworkIdentity identity, INetworkConnection conn)
{
    if (identity.serverOnly)

bug: ambiguous ready

first use case: ready = player is done with the lobby and wants to start a match. What is the current code doing, and what needs changing?
Second use case: player enters a house, we need to load the scene with the house interior. What is the current code doing, what needs changing, and maybe some proposal flows for this.

Based on conversation from Discord. Initially about the usage of NetworkConnection.Ready. Should it be for SceneLoading only or also player/state management? Both are valid use cases that should coexist so additional code will need to be added somewhere.

Client not properly changing scenes/spawning objects in Unity Editor

Client not properly changing scenes/spawning objects in Unity Editor

Repro project and To Reproduce

  1. Open the ChangeScenes Example.
  2. Add the 3 scenes in the example to a build.
  3. Run that build as a Server or Host.
  4. Run the Editor as a Client and connect.
  5. use the buttons on the SERVER SIDE to change the scene.

Expected behavior
The client should load a new player object and the scene object from the scene. Instead more than 50% of the time it gives a spawning error and the client disconnects itself.

If you run the Client in the standalone build and the Server in the editor it works fine. If you run both in standalone it works fine. If you use breakpoints on the Client while in editor it works fine.

Desktop:

  • OS: Windows
  • Build target: Standalone
  • Unity version: 2019.3.10
  • Mirror branch: Master

Server doesn't work after re-entering play mode with Fast Domain Reload

Describe the bug
After hosting the server, disconnecting, exiting play mode, and then entering play mode again, the server fails to work correctly again until a domain reload has been triggered or editor is restarted.

While broken, Server.Active will go true, but PlayerSpawner does not spawn the player, and after disconnecting again, Server.Active will incorrectly stay true.

I've tried with Kcp, IgnoranceNG, and Websocket. The bug happens to the first two, but not to Websocket. From what I can tell, the bug is identical between Kcp and IgnoranceNG. However, if one triggers the bug with either of those two, and then switches to Websocket, then it will also be broken. But Websocket never triggers the bug itself.

Repro project
MirrorNG Test.zip

Simple project with three scenes (based on Mirror's "Basic" example), one for each transport, but otherwise identical.

To Reproduce
Steps to reproduce the behavior:

  1. Open the attached project.
  2. Open the "Kcp" scene.
  3. Enter play mode.
  4. Click "Start Host" button and notice "Server Active: True" and the "Player 01" UI element.
  5. Click "Stop Network" and notice "Server Active: False".
  6. Exit and re-enter play mode.
  7. Click "Start Host" button and notice "Server Active: True", but no "Player 01".
  8. Click "Stop Network" and notice "Server Active" is still "True".

Expected behavior
Starting host should spawn a player every time, and stopping network should set "Server Active" to False every time.

Desktop (please complete the following information):

  • OS: Windows 10
  • Build target: Editor
  • Unity version: 2020.1.16

Semantic SyncList events

Currently, synclist callback looks like this:

class Player : NetworkBehaviour {

    readonly SyncListItem inventory = new SyncListItem();

    // 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(SyncListItem.Operation op, int index, Item oldItem, Item newItem)
    {
        switch (op)
        {
            case SyncListItem.Operation.OP_ADD:
                // index is where it got added in the list
                // item is the new item
                break;
            case SyncListItem.Operation.OP_CLEAR:
                // list got cleared
                break;
            case SyncListItem.Operation.OP_INSERT:
                // index is where it got added in the list
                // item is the new item
                break;
            case SyncListItem.Operation.OP_REMOVEAT:
                // index is where it got removed in the list
                // item is the item that was removed
                break;
            case SyncListItem.Operation.OP_SET:
                // index is the index of the item that was updated
                // item is the previous item
                break;
        }
    }
}

This is super gross, index, olditem and new item mean different things depending on op, sometimes they are used sometimes they are not, and this is a blatant violation of SRP.

A better way is to have semantic events like this:

class Player : NetworkBehaviour {

    readonly SyncListItem inventory = new SyncListItem();

    // 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.OnAdd += (index, item) => 
       {
           // item  was added at the end of the list
       };

      inventory.OnClear += () =>
      {
          // list has been cleared
      }

      inventory.OnSet += (index, prevItem, newItem) =>
      {
            // new item has been set at index,  prevItem is what was there before
      }

      inventory.OnRemove += (index, prevItem) =>
      {
            // prevItem has been removed at the given index
      }

      inventory.OnChange += () => 
      {
           // brand new event,  called after the list has changed 
           // if multiple changes,  this is called after all changes are applied
           // useful for refreshing your UI after data changes.
      }
    }

}

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.