diff --git a/docs/advanced-topics/inscene_parenting_player.md b/docs/advanced-topics/inscene_parenting_player.md index 290e3fcab..f95b93437 100644 --- a/docs/advanced-topics/inscene_parenting_player.md +++ b/docs/advanced-topics/inscene_parenting_player.md @@ -49,8 +49,9 @@ public class ParentPlayerToInSceneNetworkObject : NetworkBehaviour // As long as the client (player) is in the connected clients list if (NetworkManager.ConnectedClients.ContainsKey(clientId)) { - // Set the player as a child of this in-scene placed NetworkObject - NetworkManager.ConnectedClients[clientId].PlayerObject.transform.parent = transform; + // Set the player as a child of this in-scene placed NetworkObject + // We parent in local space by setting the WorldPositionStays value to false + NetworkManager.ConnectedClients[clientId].PlayerObject.TrySetParent(NetworkObject, false); } } } @@ -83,5 +84,5 @@ You should place this script on your in-scene placed `NetworkObject` (i.e. the f :::note -Remove any parenting code you might have had from your player prefab before using the above script. +Remove any parenting code you might have had from your player prefab before using the above script. Depending upon your project's goals, you might be parenting all players under the same in-scene placed `NetworkObject` or you might intend to have each player parenting unique. If you want each player to be parented under a unique in-scene placed `NetworkObject` then you will need to have the same number of in-scene placed `NetworkObject`s as your maximum allowed players per game session. The above example will only parent all players under the same in-scene placed `NetworkObject`. You could extend the above example by migrating the scene event code into an in-scene placed `NetworkObject` that manages the parenting of players (i,e. name it something like `PlayerSpawnManager`) as they connect, make the `SetPlayerParent` method public, and add all in-scene placed `NetworkObject`s to a public list of GameObjects that the `PlayerSpawnManager` will reference and assign player's to as they connect while also freeing in-scene placed `NetworkObject`s as players disconnect during a game session. ::: \ No newline at end of file diff --git a/docs/advanced-topics/networkobject-parenting.md b/docs/advanced-topics/networkobject-parenting.md index d209eafc4..d2aa66c25 100644 --- a/docs/advanced-topics/networkobject-parenting.md +++ b/docs/advanced-topics/networkobject-parenting.md @@ -151,7 +151,7 @@ Vehicle (GameObject->NetworkObject) This would be considered an invalid parenting and would be reverted. ### Mildly Complex Valid Example: -In order to resolve the previous invalid parenting issue, we would need to add a `NetworkObjet` component to the seats. This means we would need to: +In order to resolve the previous invalid parenting issue, we would need to add a `NetworkObject` component to the seats. This means we would need to: 1. Spawn the vehicle and the seats: ``` Sun @@ -185,8 +185,18 @@ Vehicle (GameObject->NetworkObject) └─Seat2 (GameObject->NetworkObject) ``` +### Parenting & Transform Synchronization +It is important to understand that without the use of a `NetworkTransform` clients are only synchronized with the transform values when: +- A client is being synchronized with the NetworkObject in question: + - During the client's first synchronization after a client has their connection approved. + - When a server spawns a new `NetworkObject`. +- A `NetworkObject` has been parented _(or a parent removed)_. + - The server can override the `NetworkBehaviour.OnNetworkObjectParentChanged` method and adjust the transform values when that is invoked. + - These transform changes will be synchronized with clients via the `ParentSyncMessage` + + :::note Optional Auto Synchronized Parenting -The Auto Object Parent Sync property of NetworkObject, enabled by default, allows you to disable automatic parent change synchronization in the event you want to implement your own parenting solution for one or more NetworkObjects. +The Auto Object Parent Sync property of a `NetworkObject`, enabled by default, allows you to disable automatic parent change synchronization in the event you want to implement your own parenting solution for one or more NetworkObjects. It is important to understand that disabling the Auto Object Parent Sync option of a `NetworkObject` will treat the `NetworkObject`'s transform synchronization with *clients* as if its parent is the hierarchy root _(i.e. null)_. ::: diff --git a/docs/basics/scenemanagement/inscene-placed-networkobjects.md b/docs/basics/scenemanagement/inscene-placed-networkobjects.md index e3e758380..c1997e0c2 100644 --- a/docs/basics/scenemanagement/inscene-placed-networkobjects.md +++ b/docs/basics/scenemanagement/inscene-placed-networkobjects.md @@ -231,6 +231,30 @@ In-scene placed `NetworkObject`s follow the same parenting rules as [dynamically - Under this scenario, you would want to use a hybrid approach where the in-scene placed `NetworkObject` dynamically spawns the item to be picked up. - If you plan on using a bootstrap scene usage pattern where you use additive scene loading and unloading with no full scene-migration(s), then it is "OK" to parent in-scene placed NetworkObjects. -:::warning -Parenting in-scene placed `NetworkObject`s under `GameObject`s with no `NetworkObject` component will currently synchronize the child `NetworkObject` as if it is in world space on the client side. To work around this particular issue you should add a `NetworkTransform` to the child and enable local space synchronization. -::: \ No newline at end of file +### Auto Object Parent Sync Option & Parenting + Already parented in-scene placed `NetworkObject`s Auto Object Parent Sync Usage: + +- When disabled, the NetworkObject ignores its parent and considers all of its transform values as being world space synchronized (i.e. no matter where you move or rotate its parent, it will maintain its current position and rotation) + - Typically, when disabling this you need to handle synchronizing the client either through your own custom messages or RPCS or add a NetworkTransform component to it. This is only useful if you want to have some global parent that might shift or have transform values that you don't want to impact the `NetworkObject` in question. +- When enabled, the NetworkObject is aware of its parent and will treat all of its transform values as being local space synchronized. + - _This also applies to being pre-parented under a `GameObject` with no `NetworkObject` component._ + +:::note +_**The caveat to the above is scale**:_ +Scale is treated always as local space relative for pre-parented in-scene placed `NetworkObjects`.
+ +*For dynamically spawned NetworkObjects:*
+It depends upon what WorldPositionStays value you use when parenting the NetworkObject in question.
+WorldPositionStays = true: Everything is world space relative. _(default)_
+WorldPositionStays = false: Everything is local space relative. _(children offset relative to the parent)_
+::: + + +### Parenting & Transform Synchronization +It is important to understand that without the use of a `NetworkTransform` clients are only synchronized with the transform values when: +- A client is being synchronized with the NetworkObject in question: + - During the client's first synchronization after a client has their connection approved. + - When a server spawns a new NetworkObject. +- A NetworkObject has been parented (or a parent removed). + - The server can override the `NetworkBehaviour.OnNetworkObjectParentChanged` method and adjust the transform values when that is invoked. + - These transform changes will be synchronized with clients via the `ParentSyncMessage` \ No newline at end of file diff --git a/docusaurus.config.js b/docusaurus.config.js index a85f0fecb..d111489a6 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -340,9 +340,13 @@ module.exports = { lastVersion: "current", versions: { current: { - label: '1.0.0', + label: '1.1.0', path: 'current', }, + '1.0.0': { + label: '1.0.0', + path: '1.0.0', + }, '0.1.0': { label: '0.1.0', path: '0.1.0', diff --git a/versioned_docs/version-1.0.0/about.md b/versioned_docs/version-1.0.0/about.md new file mode 100644 index 000000000..50c967fd0 --- /dev/null +++ b/versioned_docs/version-1.0.0/about.md @@ -0,0 +1,55 @@ +--- +id: about +title: About Netcode for GameObjects +description: Learn more about the available APIs for Unity Multiplayer Networking, including Netcode for GameObjects and Transport. +--- + +Netcode for GameObjects (Netcode) is a high-level networking library built for Unity for you to abstract networking logic. It enables you to send GameObjects and world data across a networking session to multiplayer players at once. With Netcode, you can focus on building your game instead of low-level protocols and networking frameworks. + +To learn more about Netcode for GameObjects functionality and capabilities, explore the content below: + +
+ +| Getting Started | Hello World and Golden Paths | Education and Samples | +| -- | -- | -- | +| [Install Unity Netcode](installation/installation.md)
[Migration from UNet to Netcode](installation/migratingfromUNet.md)
[Upgrade to Unity Netcode Package](installation/migratingfrommlapi.md) | [Your First Networked Game](tutorials/helloworld.md)
[Module One](tutorials/goldenpath_series/gp_module_one.md)
[Module Two](tutorials/goldenpath_series/gp_module_two.md)
| [Boss Room](learn/bossroom/getting-started-boss-room.md)
[Bite Size Samples](learn/bitesize/bitesize-introduction.md)
[Dilmer's Tutorials](learn/dilmer/dilmer-video.md) | + +
+ +
+ +| Core Concepts | Debugging | Terminology and FAQs | +| -- | -- | -- | +| [Networking](basics/connection-approval.md)
[Components](components/networkmanager.md)
[Objects](basics/object-spawning.md)
[Messaging System](advanced-topics/messaging-system.md)
[Serialization](advanced-topics/serialization/serialization-intro.md)
[Scenes](basics/scenemanagement/scene-management-overview.md) | [Logging](basics/logging.md)
[Troubleshooting](troubleshooting/troubleshooting.md)
[Error Messages](troubleshooting/error-messages.md) | [High Level Terminology](reference/glossary/high-level-terminology.md)
[Multiplayer Game Architecture](learn/multiplayer_game_arch_intro.md)
[FAQs](learn/faq.md) | + +
+ +Don't forget to check out our [Release Notes](https://docs-multiplayer.unity3d.com/releases/introduction) and [APIs](api/introduction.md)! + +## Before you begin + +Netcode supports the following versions: +* Unity 2020.3, 2021.1, 2021.2, and 2021.3 +* Mono and IL2CPP [Scripting Backends](https://docs.unity3d.com/Manual/scripting-backends.html) + +Netcode supports the following platforms: +* Windows, MacOS, and Linux +* iOS and Android +* XR platforms running on Windows, Android, and iOS operating systems +* Most [**closed platforms**](https://unity.com/platform-installation), such as consoles. Contact us for more information about specific closed platforms. + * When working with consoles (such as PlayStation, Xbox, or Nintendo Switch), there may be Netcode-specific policies you should be aware of while testing and before launching your game live. Refer to the console's internal documentation for more information. This content is typically protected by NDA. + +:::caution Using WebGL +Netcode does not support the WebGL platform because it does not allow access to IP Sockets. + +There are third party transports provided by the community that may enable you to use Netcode on WebGL platforms. A list of these transports are found [here](https://github.com/Unity-Technologies/multiplayer-community-contributions#transports). + +Use with caution: +* You may encounter bugs and issues while using Netcode on WebGL, and we will not prioritize fixing those issues. +* The server or host cannot be a WebGL client, but a Desktop or Mobile build. +* You may experience **increased** latency and jitter because of the TCP protocol used by WebSockets. +::: + +:::unity Content Licenses +This is free under the permissive MIT [Licenses](/reference/license) by Unity and the Netcode collaborators. Netcode is open source with no attached costs or limitations, so you can develop features alongside Unity. +::: diff --git a/versioned_docs/version-1.0.0/advanced-topics/bufferserializer.md b/versioned_docs/version-1.0.0/advanced-topics/bufferserializer.md new file mode 100644 index 000000000..31576e929 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/bufferserializer.md @@ -0,0 +1,21 @@ +--- +id: bufferserializer +title: BufferSerializer +sidebar_label: BufferSerializer +--- + +`BufferSerializer` is the bi-directional serializer primarily used for serializing within [`INetworkSerializable`](inetworkserializable.md) types. It wraps [`FastBufferWriter` and `FastBufferReader`](fastbufferwriter-fastbufferreader.md) to provide high performance serialization, but has a couple of differences to make it more user-friendly: + +- Rather than writing separate methods for serializing and deserializing, `BufferSerializer` allows writing a single method that can handle both operations, which reduces the possibility of a mismatch between the two +- `BufferSerializer` does bound checking on every read and write by default, making it easier to avoid mistakes around manual bounds checking required by `FastBufferWriter` and `FastBufferReader` + +These aren't without downsides, however: + +- `BufferSerializer` has to operate on an existing mutable value due to its bi-directional nature, which means values like `List.Count` have to be stored to a local variable before writing. +- `BufferSerializer` is slightly slower than `FastBufferReader` and `FastBufferWriter` due to both the extra pass-through method calls and the mandatory bounds checking on each write. +- `BufferSerializer` do not support any form of packed reads and writes. + +However, when those downsides are unreasonable, `BufferSerializer` offers two ways to perform more optimal serialization for either performance or bandwidth usage: + +- For performance, you can use `PreCheck(int amount)` followed by `SerializeValuePreChecked()` to perform bounds checking for multiple fields at once. +- For both performance and bandwidth usage, you can obtain the wrapped underlying reader/writer via `serializer.GetFastBufferReader()` when `serializer.IsReader` is `true`, and `serializer.GetFastBufferWriter()` when `serializer.IsWriter` is `true`. These provide micro-performance improvements by removing a level of indirection, and also give you a type you can use with `BytePacker` and `ByteUnpacker`. diff --git a/versioned_docs/version-1.0.0/advanced-topics/custom-serialization.md b/versioned_docs/version-1.0.0/advanced-topics/custom-serialization.md new file mode 100644 index 000000000..e249c3131 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/custom-serialization.md @@ -0,0 +1,57 @@ +--- +id: custom-serialization +title: Custom Serialization +--- + +When using `RPC`'s, `NetworkVariable`'s or any other Netcode for GameObjects (Netcode) related task that requires serialization. The Netcode uses a default serialization pipeline that looks like this: + +`` +Custom Types => Built In Types => INetworkSerializable +`` + +That is, when Netcode first gets hold of a type, it will check for any custom types that the user have registered for serialization, after that it will check if it's a built in type, such as a Vector3, float etc. These are handled by default. If not, it will check if the type inherits `INetworkSerializable`, if it does, it will call it's write methods. + +By default, any type that satisfies the `unmanaged` generic constraint can be automatically serialized as RPC parameters. This includes all basic types (bool, byte, int, float, enum, etc) as well as any structs that contains only these basic types. + +With this flow, you can override **ALL** serialization for **ALL** types, even built in types, and with the API provided, it can even be done with types that you have not defined yourself, those who are behind a 3rd party wall, such as .NET types. + +To register a custom type, or override an already handled type, you need to create extension methods for `FastBufferReader.ReadValueSafe()` and `FastBufferWriter.WriteValueSafe()`: + +```csharp +// Tells the Netcode how to serialize and deserialize Url in the future. +// The class name doesn't matter here. +public static class SerializationExtensions +{ + public static void ReadValueSafe(this FastBufferReader reader, out Url value) + { + reader.ReadValueSafe(out string val); + value = new Url(val); + } + + public static void WriteValueSafe(this FastBufferWriter writer, in Url value) + { + writer.WriteValueSafe(instance.Value); + } +} +``` + +The code generation for RPCs will automatically pick up and use these functions, and they'll become available via `FastBufferWriter` and `FastBufferReader` directly. + +You can also optionally use the same method to add support for `BufferSerializer.SerializeValue()`, if you wish, which will make this type readily available within [`INetworkSerializable`](/advanced-topics/serialization/inetworkserializable.md) types: + +```c# +// The class name doesn't matter here. +public static class SerializationExtensions +{ + public static void SerializeValue(this BufferSerializer serializer, ref Url value) where TReaderWriter: IReaderWriter + { + if (serializer.IsReader) + { + value = new Url(); + } + serializer.SerializeValue(ref value.Value); + } +} +``` + +Additionally, you can also add extensions for `FastBufferReader.ReadValue()`, `FastBufferWriter.WriteValue()`, and `BufferSerializer.SerializeValuePreChecked()` to provide more optimal implementations for manual serialization using `FastBufferReader.TryBeginRead()`, `FastBufferWriter.TryBeginWrite()`, and `BufferSerializer.PreCheck()`, respectively. However, none of these will be used for serializing RPCs - only `ReadValueSafe` and `WriteValueSafe` are used. \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/advanced-topics/fastbufferwriter-fastbufferreader.md b/versioned_docs/version-1.0.0/advanced-topics/fastbufferwriter-fastbufferreader.md new file mode 100644 index 000000000..63f8a7371 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/fastbufferwriter-fastbufferreader.md @@ -0,0 +1,163 @@ +--- +id: fastbufferwriter-fastbufferreader +title: FastBufferWriter and FastBufferReader +sidebar_label: FastBufferWriter and FastBufferReader +--- +The serialization and deserialization is done via `FastBufferWriter` and `FastBufferReader`. These have methods for serializing individual types and methods for serializing packed numbers, but in particular provide a high-performance method called `WriteValue()/ReadValue()` (for Writers and Readers, respectively) that can extremely quickly write an entire unmanaged struct to a buffer. + +There's a trade-off of CPU usage vs bandwidth in using this: Writing individual fields is slower (especially when it includes operations on unaligned memory), but allows the buffer to be filled more efficiently, both because it avoids padding for alignment in structs, and because it allows you to use `BytePacker.WriteValuePacked()`/`ByteUnpacker.ReadValuePacked()` and `BytePacker.WriteValueBitPacked()`/`ByteUnpacker.ReadValueBitPacked()`. The difference between these two is that the BitPacked variants pack more efficiently, but they reduce the valid range of values. See the section below for details on packing. + + +**Example** + +```csharp +struct ExampleStruct +{ + private float f; + private bool b; + private int i; + + void Serialize(FastBufferWriter writer); +} +``` + +In this example struct, `Serialize` can be implemented in two ways: + +```csharp +void Serialize(FastBufferWriter writer) +{ + if(!writer.TryBeginWrite(sizeof(float) + sizeof(bool) + sizeof(i))) + { + throw new OverflowException("Not enough space in the buffer"); + } + writer.WriteValue(f); + writer.WriteValue(b); + writer.WriteValue(i); +} +``` + +```csharp +void Serialize(FastBufferWriter writer) +{ + if(!writer.TryBeginWrite(sizeof(ExampleStruct))) + { + throw new OverflowException("Not enough space in the buffer"); + } + writer.WriteValue(this); +} +``` +This creates efficiently packed data in the message, and can be further optimized by using `BytePacker.WriteValuePacked()` and `BytePacker.WriteValueBitPacked()`, but it has two downsides: +- First, it involves more method calls and more instructions, making it slower. +- Second, that it creates a greater opportunity for the serialize and deserialize code to become misaligned, since they must contain the same operations in the same order. + +You can also use a hybrid approach if you have a few values that will need to be packed and several that won't: + +```C# +struct ExampleStruct +{ + struct Embedded + { + private byte a; + private byte b; + private byte c; + private byte d; + } + public Embedded embedded; + public float f; + public short i; + + void Serialize(FastBufferWriter writer) + { + writer.WriteValue(embedded); + BytePacker.WriteValuePacked(writer, f); + BytePacker.WriteValuePacked(writer, i); + } +} +``` + +This allows the four bytes of the embedded struct to be rapidly serialized as a single action, then adds the compacted data at the end, resulting in better bandwidth usage than serializing the whole struct as-is, but better performance than serializing it one byte at a time. + + +## FastBufferWriter and FastBufferReader + +`FastBufferWriter` and `FastBufferReader` are replacements for the old `NetworkWriter` and `NetworkReader`. For those familiar with the old classes, there are some key differences: + +- `FastBufferWriter` uses `WriteValue()` as the name of the method for all types *except* [`INetworkSerializable`](serialization/inetworkserializable) types, which are serialized through `WriteNetworkSerializable()` +- `FastBufferReader` similarly uses `ReadValue()` for all types except INetworkSerializable (which is read through `ReadNetworkSerializable`), with the output changed from a return value to an `out` parameter to allow for method overload resolution to pick the correct value. +- `FastBufferWriter` and `FastBufferReader` outsource packed writes and reads to `BytePacker` and `ByteUnpacker`, respectively. +- `FastBufferWriter` and `FastBufferReader` are **structs**, not **classes**. This means they can be constructed and destructed without GC allocations. +- `FastBufferWriter` and `FastBufferReader` both use the same allocation scheme as Native Containers, allowing the internal buffers to be created and resized without creating any garbage and with the use of `Allocator.Temp` or `Allocator.TempJob`. +- `FastBufferReader` can be instantiated using `Allocator.None` to operate on an existing buffer with no allocations and no copies. +- Neither `FastBufferReader` nor `FastBufferWriter` inherits from nor contains a `Stream`. +- `FastBufferReader` and `FastBufferWriter` are heavily optimized for speed, using aggressive inlining and unsafe code to achieve the fastest possible buffer storage and retrieval. +- `FastBufferReader` and `FastBufferWriter` use unsafe typecasts and `UnsafeUtility.MemCpy` operations on `byte*` values, achieving native memory copy performance with no need to iterate or do bitwise shifts and masks. +- `FastBufferReader` and `FastBufferWriter` are intended to make data easier to debug - one such thing to support will be a `#define MLAPI_FAST_BUFFER_UNPACK_ALL` that will disable all packing operations to make the buffers for messages that use them easier to read. +- `FastBufferReader` and `FastBufferWriter` do not support runtime type discovery - there is no `WriteObject` or `ReadObject` implementation. All types must be known at compile time. This is to avoid garbage and boxing allocations. + +A core benefit of `NativeArray` is that it offers access to the allocation scheme of `Allocator.TempJob`. This uses a special type of allocation that is nearly as fast as stack allocation and involves no GC overhead, while being able to persist for a few frames. In general they are rarely if ever needed for more than a frame, but this does provide a very efficient option for creating buffers as needed, which avoids the need to use a pool for them. The only downside is that buffers created this way must be manually disposed after use, as they're not garbage collected. + +## Creating and Disposing FastBufferWriters and FastBufferReaders + +To create your own `FastBufferWriter`s and `FastBufferReader`s, it's important to note that struct default/parameterless constructors cannot be removed or overridden, but `FastBufferWriter` and `FastBufferReader` require constructor behavior to be functional. + +`FastBufferWriter` always owns its internal buffer and must be constructed with an initial size, an allocator, and a maximum size. If the maximum size is not provided or is less than or equal to the initial size, the `FastBufferWriter` cannot expand. + +`FastBufferReader` can be constructed to either own its buffer or reference an existing one via `Allocator.None`. Not all types are compatible with `Allocator.None` - only `byte*`, `NativeArray`, and `FastBufferWriter` input types can provide `Allocator.None`. You can obtain a `byte*` from a `byte[]` using the following method: + +```c# +byte[] byteArray; +fixed(byte* bytePtr = byteArray) +{ + // use bytePtr here +} +``` + +It's important to note with `Allocator.None` that the `FastBufferReader` will be directly referencing a position in memory, which means the `FastBufferReader` must not live longer than the input buffer it references - and if the input buffer is a `byte[]`, the `FastBufferReader` must not live longer than the `fixed()` statement, because outside of that statement, the garbage collector is free to move that memory, which will cause random and unpredictable errors. + +Regardless which allocator you use (including `Allocator.None`), `FastBufferWriter` and `FastBufferReader` must always have `Dispose()` called on them when you're done with them. The best practice is to use them within `using` blocks. + +## Bounds Checking + +For performance reasons, by default, `FastBufferReader` and `FastBufferWriter` **do not do bounds checking** on each write. Rather, they require the use of specific bounds checking functions - `TryBeginRead(int amount)` and `TryBeginWrite(int amount)`, respectively. This improves performance by allowing you to verify the space exists for the multiple values in a single call, rather than doing that check on every single operation. + +:::info +**In editor mode and development builds**, calling these functions records a watermark point, and any attempt to read or write past the watermark point will throw an exception. This ensures these functions are used properly, while avoiding the performance cost of per-operation checking in production builds. In production builds, attempting to read or write past the end of the buffer will cause undefined behavior, likely program instability and/or crashes. +::: + +For convenience, every `WriteValue()` and `ReadValue()` method has an equivalent `WriteValueSafe()` and `ReadValueSafe()` that does bounds checking for you, throwing `OverflowException` if the boundary is exceeded. Additionally, some methods, such as arrays (where the amount of data being read can't be known until the size value is read) and [`INetworkSerializable`](inetworkserializable.md) values (where the size can't be predicted outside the implementation) will always do bounds checking internally. + +## Bitwise Reading and Writing + +Writing values in sizes measured in bits rather than bytes comes with a cost +- First, it comes with a cost of having to track bitwise lengths and convert them to bytewise lenghts. +- Second, it comes with a cost of having to remember to add padding after your bitwise writes and reads to ensure the next bytewise write or read functions correctly, and to make sure the buffer length includes any trailing bits. + +To address that, `FastBufferReader` and `FastBufferWriter` do not, themselves, have bitwise operations. When needed, however, you can create a `BitWriter` or `BitReader` instance, which is used ensure that no unaligned bits are left at the end - from the perspective of `FastBufferReader` and `FastBufferWriter`, only bytes are allowed. `BitWriter` and `BitReader` operate directly on the underlying buffer, so calling non-bitwise operations within a bitwise context is an error (and will raise an exception in non-production builds). + +```csharp +FastBufferWriter writer = new FastBufferWriter(256, Allocator.TempJob); +using(var bitWriter = writer.EnterBitwiseContext()) +{ + bitWriter.WriteBit(a); + bitWriter.WriteBits(b, 5); +} // Dispose automatically adds 2 more 0 bits to pad to the next byte. +``` + +## Packing + +Packing values is done using the utility classes `BytePacker` and `ByteUnpacker`. These generally offer two different ways of packing values: + +- `BytePacker.WriteValuePacked()`/`ByteUnpacker.ReadValuePacked()` are the most versatile. They can write any range of values that fit into the type, and also have special built-in methods for many common Unity types that can automatically pack the values contained within. + +- `BytePacker.WriteValueBitPacked()`/`ByteUnpacker.ReadValueBitPacked()` offer tighter/more optimal packing (the data in the buffer will never exceed `sizeof(type)`, which can happen with very large values using `WriteValuePacked()`, and will usually be one byte smaller than with `WriteValuePacked()` except for values <= 240, which will be one byte with both methods), but come with the limitations that they can only be used on integral types, and they use some bits of the type to encode length information, meaning that they reduce the usable size of the type. The sizes allowed by these functions are as follows: + + | Type | Usable Size | + | ------ | ------------------------------------------------------------ | + | short | 14 bits + sign bit (-16,384 to 16,383) | + | ushort | 15 bits (0 to 32,767) | + | int | 29 bits + sign bit (-536,870,912 to 536,870,911) | + | uint | 30 bits (0 to 1,073,741,824) | + | long | 60 bits + sign bit (-1,152,921,504,606,846,976 to 1,152,921,504,606,846,975) | + | ulong | 61 bits (0 to 2,305,843,009,213,693,952) | + + diff --git a/versioned_docs/version-1.0.0/advanced-topics/inscene_parenting_player.md b/versioned_docs/version-1.0.0/advanced-topics/inscene_parenting_player.md new file mode 100644 index 000000000..290e3fcab --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/inscene_parenting_player.md @@ -0,0 +1,87 @@ +--- +id: inscene-parenting-players +title: Real world In-scene NetworkObject parenting of players solution +description: In-scene NetworkObject parenting of players Solution +--- + + +We received the following issue in Github. + +## Issue: + +When a player prefab contains a script that dynamically adds a parent to its transform, the client cannot join a game hosted by another client. [You can see orignal issue here](https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/issues/1211) + +Steps to reproduce the behavior: + +1. Set up basic networking game with at least one `GameObject` in a scene that is not the player. +1. Add a script to the player prefab that adds parenting to its transform via `gameObject.transform.SetParent()` in the `Start()` method. +1. Launch one instance of the game as Host. +1. Launch another instance and try to join as Client. + +## Solution: + + +If you want to do this when a player has first connected and all `NetworkObjects` (in-scene placed and already dynamically spawned by the server-host) have been fully synchronized with the client then we would recommend using the `NetworkManager.SceneManager.OnSceneEvent` to trap for the `C2S_SyncComplete` event. + +Here is an example script that we recommend using to achieve this: + +```csharp +using Unity.Netcode; + +public class ParentPlayerToInSceneNetworkObject : NetworkBehaviour +{ + public override void OnNetworkSpawn() + { + if (IsServer) + { + // Server subscribes to the NetworkSceneManager.OnSceneEvent event + NetworkManager.SceneManager.OnSceneEvent += SceneManager_OnSceneEvent; + + // Server player is parented under this NetworkObject + SetPlayerParent(NetworkManager.LocalClientId); + } + } + + private void SetPlayerParent(ulong clientId) + { + if (IsSpawned && IsServer) + { + // As long as the client (player) is in the connected clients list + if (NetworkManager.ConnectedClients.ContainsKey(clientId)) + { + // Set the player as a child of this in-scene placed NetworkObject + NetworkManager.ConnectedClients[clientId].PlayerObject.transform.parent = transform; + } + } + } + + private void SceneManager_OnSceneEvent(SceneEvent sceneEvent) + { + // OnSceneEvent is very useful for many things + switch (sceneEvent.SceneEventType) + { + // The C2S_SyncComplete event tells the server that a client-player has: + // 1.) Connected and Spawned + // 2.) Loaded all scenes that were loaded on the server at the time of connecting + // 3.) Synchronized (instantiated and spawned) all NetworkObjects in the network session + case SceneEventData.SceneEventTypes.C2S_SyncComplete: + { + // As long as we are not the server-player + if (sceneEvent.ClientId != NetworkManager.LocalClientId) + { + // Set the newly joined and synchronized client-player as a child of this in-scene placed NetworkObject + SetPlayerParent(sceneEvent.ClientId); + } + break; + } + } + } +} +``` + +You should place this script on your in-scene placed `NetworkObject` (i.e. the first `GameObject`) and do the parenting from it in order to avoid any timing issues of when it is spawned or the like. It only runs the script on the server-host side since parenting is server authoritative. + + +:::note +Remove any parenting code you might have had from your player prefab before using the above script. +::: \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/advanced-topics/message-system/clientrpc.md b/versioned_docs/version-1.0.0/advanced-topics/message-system/clientrpc.md new file mode 100644 index 000000000..1a875eec9 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/message-system/clientrpc.md @@ -0,0 +1,123 @@ +--- +id: clientrpc +title: ClientRpc +--- +import ImageSwitcher from '@site/src/ImageSwitcher.js'; + + +A `ClientRpc` can be invoked by the server to be executed on a client. + +
+ +
+ + + +## Declaring a ClientRpc +Developers can declare a `ClientRpc` by marking a method with `[ClientRpc]` attribute and making sure to have `ClientRpc` suffix in the method name. + +```csharp +[ClientRpc] +void PongClientRpc(int somenumber, string sometext) { /* ... */ } +``` + +## Invoking a ClientRpc + +Developers can invoke a `ClientRpc` by making a direct function call with parameters: + +```csharp +void Update() +{ + if (Input.GetKeyDown(KeyCode.P)) + { + PongClientRpc(Time.frameCount, "hello, world"); // Server -> Client + } +} +``` + +Marking method with ``[ClientRpc]`` attribute and putting `ClientRpc` suffix to the method name are required, otherwise it will prompt error messages: + +```csharp +// Error: Invalid, missing 'ClientRpc' suffix in the method name +[ClientRpc] +void Pong(int somenumber, string sometext) { /* ... */ } + +// Error: Invalid, missing [ClientRpc] attribute on the method +void PongClientRpc(int somenumber, string sometext) { /* ... */ } +``` + +`[ClientRpc]` attribute and matching `...ClientRpc` suffix in the method name are there to make it crystal clear for RPC call sites to know when they are executing an RPC, it will be replicated and executed on the client-side, without necessarily jumping into original RPC method declaration to find out if it was an RPC, if so whether it is a [ServerRpc](serverrpc.md) or `ClientRpc`: + +```csharp +Pong(somenumber, sometext); // Is this an RPC call? + +PongRpc(somenumber, sometext); // Is this a ServerRpc call or ClientRpc call? + +PongClientRpc(somenumber, sometext); // This is clearly a ClientRpc call +``` + +## To Send to One Client, use ClientRpcSendParameters + +The following code provides an example of using `ClientRpcSendParameters`, which will allow you to send a `ClientRpc` to a specific Client connection(s) whereas the default Netcode for GameObjects's behavior is to broadcast to every single client. + +```csharp +private void DoSomethingServerSide(int clientId) + { + // If is not the Server/Host then we should early return here! + if (!IsServer) return; + + + // NOTE! In case you know a list of ClientId's ahead of time, that does not need change, + // Then please consider caching this (as a member variable), to avoid Allocating Memory every time you run this function + ClientRpcParams clientRpcParams = new ClientRpcParams + { + Send = new ClientRpcSendParams + { + TargetClientIds = new ulong[]{clientId} + } + }; + + // Let's imagine that you need to compute a Random integer and want to send that to a client + const int maxValue = 4; + int randomInteger = Random.Range(0, maxValue); + DoSomethingClientRPC(randomInteger, clientRpcParams); + } + + [ClientRpc] + private void DoSomethingClientRPC(int randomInteger, ClientRpcParams clientRpcParams = default) + { + if (IsOwner) return; + + // Run your client-side logic here!! + Debug.LogFormat("GameObject: {0} has received a randomInteger with value: {1}", gameObject.name, randomInteger); + } +``` + +
+ +
Server can invoke a client RPC on a Network Object. The RPC will be placed in the local queue and then sent to a selection of clients (by default this selection is "all clients"). When received by a client, RPC will be executed on the client's version of the same Network Object.
+
+ +## Invoking a Client RPC from the Host. +As the host is both a client and a server, if a host invokes a Client RPC, that RPC will be executed on the host too in addition to other clients. + + + +
+ +
Client Hosts can invoke Client RPCs on Network Objects. The RPC will be placed in the local queue and then, after a short delay the client RPC will be executed on the Client Host, and sent to the other clients. When client RPC is received by the client - it is executed on the Client's version of the same Network Object.
+
+ +See [examples](../../learn/bossroom/bossroom-actions) of how these were used in Boss Room. + + +## See also + +* [ServerRpc](serverrpc.md) +* [RPC Params](rpc-params.md) \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/advanced-topics/message-system/custom-messages.md b/versioned_docs/version-1.0.0/advanced-topics/message-system/custom-messages.md new file mode 100644 index 000000000..66b2504c7 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/message-system/custom-messages.md @@ -0,0 +1,301 @@ +--- +id: custom-messages +title: Custom Messages +description: A brief explanation of Custom Messages use in Netcode for GameObjects (Netcode) covering Named and Unnamed messages. +--- +import ImageSwitcher from '@site/src/ImageSwitcher.js'; + +If you do not want to use the Netcode for GameObjects (Netcode) messaging system, you do not have to. You can use a thin layer called "Custom Messages" to implement your own messaging behavior and/or add custom targeting. They are unbound to any game object. Custom messages can be used in combination with [RPC messages](../messaging-system.md). + +There are two types of custom messages: +- Unnamed +- Named + +## Unnamed Messages +Unnamed messages can be thought of as a single sending channel. A message sent has one receive handler, this is useful for building your own custom messaging system. Netcode for GameObjects handles delivering and receiving custom unnamed messages, you can provide your own "custom message headers" to determine the type of unnamed message being sent or received. + +### Unnamed Message Example +Below is a very basic example of how you might implement your own messaging system using unnamed messages: +```csharp +using UnityEngine; +using Unity.Collections; +using Unity.Netcode; + +/// +/// Using an unnamed message to send a string message +/// defined +/// further down below. +/// +public class UnnamedStringMessageHandler : CustomUnnamedMessageHandler +{ + /// + /// We override this method to define the unique message type + /// identifier for this child derived class + /// + protected override byte MessageType() + { + // As an example, we could define message type of 1 for string messages + return 1; + } + + public override void OnNetworkSpawn() + { + // For this example, we always want to invoke the base + base.OnNetworkSpawn(); + + if (IsServer) + { + // Server broadcasts to all clients when a new client connects + // (just for example purposes) + NetworkManager.OnClientConnectedCallback += OnClientConnectedCallback; + } + else + { + // Clients send a greeting string message to the server + SendUnnamedMessage("I am a client connecting!"); + } + } + + public override void OnNetworkDespawn() + { + // For this example, we always want to invoke the base + base.OnNetworkDespawn(); + + // Whether server or not, unregister this. + NetworkManager.OnClientDisconnectCallback -= OnClientConnectedCallback; + } + + private void OnClientConnectedCallback(ulong clientId) + { + // Server broadcasts a welcome string message to all clients that + // a new client has joined. + SendUnnamedMessage($"Everyone welcome the newly joined client ({clientId})!"); + } + + /// + /// For this example, we override this message to handle receiving the string + /// message. + /// + protected override void OnReceivedUnnamedMessage(ulong clientId, FastBufferReader reader) + { + var stringMessage = string.Empty; + reader.ReadValueSafe(out stringMessage); + if (IsServer) + { + Debug.Log($"Server received unnamed message of type ({MessageType()}) from client " + + $"({clientId}) that contained the string: \"{stringMessage}\""); + + // As an example, we could also broadcast the client message to everyone + SendUnnamedMessage($"Newly connected client sent this greeting: \"{stringMessage}\""); + } + else + { + Debug.Log(stringMessage); + } + } + + /// + /// For this example, we will send a string as the payload. + /// + /// IMPORTANT NOTE: You can construct your own header to be + /// written for custom message types, this example just uses + /// the message type value as the "header". This provides us + /// with the ability to have "different types" of unnamed + /// messages. + /// + public override void SendUnnamedMessage(string dataToSend) + { + var writer = new FastBufferWriter(1100, Allocator.Temp); + var customMessagingManager = NetworkManager.CustomMessagingManager; + // Tip: Placing the writer within a using scope assures it will + // be disposed upon leaving the using scope + using (writer) + { + // Write our message type + writer.WriteValueSafe(MessageType()); + + // Write our string message + writer.WriteValueSafe(dataToSend); + if (IsServer) + { + // This is a server-only method that will broadcast the unnamed message. + // Caution: Invoking this method on a client will throw an exception! + customMessagingManager.SendUnnamedMessageToAll(writer); + } + else + { + // This method can be used by a client or server (client to server or server to client) + customMessagingManager.SendUnnamedMessage(NetworkManager.ServerClientId, writer); + } + } + } +} + +/// +/// A templated class to handle sending different data types +/// per unique unnamed message type/child derived class. +/// +public class CustomUnnamedMessageHandler : NetworkBehaviour +{ + /// + /// Since there is no unique way to identify unnamed messages, + /// adding a message type identifier to the message itself is + /// one way to handle know: + /// "what kind of unnamed message was received?" + /// + protected virtual byte MessageType() + { + // The default unnamed message type + return 0; + } + + /// + /// For most cases, you want to register once your NetworkBehaviour's + /// NetworkObject (typically in-scene placed) is spawned. + /// + public override void OnNetworkSpawn() + { + // Both the server-host and client(s) will always subscribe to the + // the unnamed message received event + NetworkManager.CustomMessagingManager.OnUnnamedMessage += ReceiveMessage; + } + + public override void OnNetworkDespawn() + { + // Unsubscribe when the associated NetworkObject is despawned. + NetworkManager.CustomMessagingManager.OnUnnamedMessage -= ReceiveMessage; + } + + /// + /// This method needs to be overridden to handle reading a unique message type + /// (i.e. derived class) + /// + protected virtual void OnReceivedUnnamedMessage(ulong clientId, FastBufferReader reader) + { + } + + /// + /// For this unnamed message example, we always read the message type + /// value to determine if it should be handled by this instance in the + /// event it is a child of the CustomUnnamedMessageHandler class. + /// + private void ReceiveMessage(ulong clientId, FastBufferReader reader) + { + var messageType = (byte)0; + // Read the message type value that is written first when we send + // this unnamed message. + reader.ReadValueSafe(out messageType); + // Example purposes only, you might handle this in a more optimal way + if (messageType == MessageType()) + { + OnReceivedUnnamedMessage(clientId, reader); + } + } + + /// + /// For simplicity, the default does nothing + /// + /// + public virtual void SendUnnamedMessage(T dataToSend) + { + + } +} +``` +## Named Messages +If you don't want to handle the complexity of creating your own messaging system, Netcode for GameObjects also provides you with the option to use custom "named messages". Custom named messages use the "message name" as the unique identifier (it creates a hash value from the name and links that to a received named message callback). +:::tip +If you are not quite sure if you need to incorporate the complexity of message identification and handling like you do with custom unnamed messages, you can always start with custom named messages and then if, at a later date, you determine you need "sub-message types" for a specific custom named message then you can always incorporate a type identifier (like you would with unnamed messages) into the named message payload itself. +::: + +### Name Message Example +Below is a very basic example of implementing a custom named message: +```csharp +using System; +using UnityEngine; +using Unity.Collections; +using Unity.Netcode; +public class CustomNamedMessageHandler : NetworkBehaviour +{ + [Tooltip("The name identifier used for this custom message handler.")] + public string MessageName = "MyCustomNamedMessage"; + + /// + /// For most cases, you want to register once your NetworkBehaviour's + /// NetworkObject (typically in-scene placed) is spawned. + /// + public override void OnNetworkSpawn() + { + // Both the server-host and client(s) register the custom named message. + NetworkManager.CustomMessagingManager.RegisterNamedMessageHandler(MessageName, ReceiveMessage); + + if (IsServer) + { + // Server broadcasts to all clients when a new client connects (just for example purposes) + NetworkManager.OnClientConnectedCallback += OnClientConnectedCallback; + } + else + { + // Clients send a unique Guid to the server + SendMessage(Guid.NewGuid()); + } + } + + private void OnClientConnectedCallback(ulong obj) + { + SendMessage(Guid.NewGuid()); + } + + public override void OnNetworkDespawn() + { + // De-register when the associated NetworkObject is despawned. + NetworkManager.CustomMessagingManager.UnregisterNamedMessageHandler(MessageName); + // Whether server or not, unregister this. + NetworkManager.OnClientDisconnectCallback -= OnClientConnectedCallback; + } + + /// + /// Invoked when a custom message of type + /// + private void ReceiveMessage(ulong senderId, FastBufferReader messagePayload) + { + var receivedMessageContent = new ForceNetworkSerializeByMemcpy(new Guid()); + messagePayload.ReadValueSafe(out receivedMessageContent); + if (IsServer) + { + Debug.Log($"Sever received GUID ({receivedMessageContent.Value}) from client ({senderId})"); + } + else + { + Debug.Log($"Client received GUID ({receivedMessageContent.Value}) from the server."); + } + } + + /// + /// Invoke this with a Guid by a client or server-host to send a + /// custom named message. + /// + public void SendMessage(Guid inGameIdentifier) + { + var messageContent = new ForceNetworkSerializeByMemcpy(inGameIdentifier); + var writer = new FastBufferWriter(1100, Allocator.Temp); + var customMessagingManager = NetworkManager.CustomMessagingManager; + using (writer) + { + writer.WriteValueSafe(messageContent); + if (IsServer) + { + // This is a server-only method that will broadcast the named message. + // Caution: Invoking this method on a client will throw an exception! + customMessagingManager.SendNamedMessageToAll(MessageName, writer); + } + else + { + // This is a client or server method that sends a named message to one target destination + // (client to server or server to client) + customMessagingManager.SendNamedMessage(MessageName, NetworkManager.ServerClientId, writer); + } + } + } +} +``` diff --git a/versioned_docs/version-1.0.0/advanced-topics/message-system/deprecation-of-return-values.md b/versioned_docs/version-1.0.0/advanced-topics/message-system/deprecation-of-return-values.md new file mode 100644 index 000000000..8f3da8a95 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/message-system/deprecation-of-return-values.md @@ -0,0 +1,51 @@ +--- +id: deprecation-of-return-values +title: Deprecation of Return Values +--- +import ImageSwitcher from '@site/src/ImageSwitcher.js'; + +Netcode for GameObjects (Netcode) supports RPC return values on convenience RPCs. + +Example: + +```csharp +public IEnumerator MyRpcCoroutine() +{ + RpcResponse response = InvokeServerRpc(MyRpcWithReturnValue, Random.Range(0f, 100f), Random.Range(0f, 100f)); + + while (!response.IsDone) + { + yield return null; + } + + Debug.LogFormat("The final result was {0}!", response.Value); +} + +[ServerRPC] +public float MyRpcWithReturnValue(float x, float y) +{ + return x * y; +} + +``` + +This RFC also drops this feature and similar functionality can be achived as following: + +```csharp +void MyRpcInvoker() +{ + MyRpcWithReturnValueRequestServerRpc(Random.Range(0f, 100f)), Random.Range(0f, 100f))); +} + +[ServerRpc] +void MyRpcWithReturnValueRequestServerRpc(float x, float y) +{ + MyRpcWithReturnValueResponseClientRpc(x * y); +} + +[ClientRpc] +void MyRpcWithReturnValueResponseClientRpc(float result) +{ + Debug.LogFormat("The final result was {0}!", result); +} +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/advanced-topics/message-system/execution-table.md b/versioned_docs/version-1.0.0/advanced-topics/message-system/execution-table.md new file mode 100644 index 000000000..7dfbd2632 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/message-system/execution-table.md @@ -0,0 +1,97 @@ +--- +id: execution-table +title: Execution Table +--- +import ImageSwitcher from '@site/src/ImageSwitcher.js'; + +The following table details the execution of `ServerRpc` and `ClientRpc` functions: + +| Function | Server | Client | Host (Server+Client) | +|---|:---:|:---:|:---:| +| ServerRpc Send | | | | +| ServerRpc Execute | | | | +| ClientRpc Send | | | | +| ClientRpc Execute | | | | + +An RPC function typically doesn't execute its body immediately since the function call really is a stand-in for a network transmission. Since the host is both a client and a server, local RPCs targeting the host-server or host-client are invoked immediately. As such, avoid nesting RPCs when running in host mode as a ServerRpc method that invokes a ClientRpc method that invokes the same ServerRpc method (and repeat...) could cause a stack overflow. + +Structure of a typical `ServerRpc`: + +```csharp +[ServerRpc] +void MyServerRpc(int somenumber, string somestring) +{ + // Network Send Block (framework-code) + // Network Return Block (framework-code) + // RPC Method Body (user-code) +} +``` + +Pseudo-code sample of a `ServerRpc`: + +```csharp +[ServerRpc] +void MyServerRpc(int somenumber, string somestring) +{ + // --- begin: injected framework-code + if (NetworkSend()) + { + // this block will be executed if: + // - called from user-code on client + // - called from user-code on host + + var writer = NetworkCreateWriter(); + writer.WriteInt32(1234567890); // RPC method signature hash + writer.WriteInt32(somenumber); + writer.WriteChars(somestring); + NetworkSendRpc(writer); + } + + if (NetworkReturn()) + { + // this block will be executed if: + // - called from user-code + // - called from framework-code on client + + return; + } + // --- end: injected framework-code + + print($"MyServerRpc: {somenumber}"); +} +``` + +
+ +
Client can invoke a server RPC on a Network Object. The RPC will be placed in the local queue and then sent to the server, where it will be executed on the server version of the same Network Object.
+
+ +
+ +
Clients can invoke server RPCs on Client Hosts the same way they can invoke server RPCs on the regular servers: the RPC will be placed in the local queue and then sent to the Client Host, where it will be executed on the Client Host's version of the same Network Object.
+
+ + +
+ +
When a server RPC is invoked by the Client Host, the RPC will be placed in a local queue and then executed on the Client Host after a short delay. The same happens for pure servers.
+
+ +
+ +
+ +
+ +
Client Hosts can invoke Client RPCs on Network Objects. The RPC will be placed in the local queue and then, after a short delay the client RPC will be executed on the Client Host, and sent to the other clients. When client RPC is received by the client - it is executed on the Client's version of the same Network Object.
+
diff --git a/versioned_docs/version-1.0.0/advanced-topics/message-system/reliabilty.md b/versioned_docs/version-1.0.0/advanced-topics/message-system/reliabilty.md new file mode 100644 index 000000000..442a9f46c --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/message-system/reliabilty.md @@ -0,0 +1,47 @@ +--- +id: reliability +title: Reliability +--- +import ImageSwitcher from '@site/src/ImageSwitcher.js'; + +## Introduction +RPCs **are reliable by default**. This means they are guaranteed to be received and executed on the remote side. However, sometimes developers might want to opt-out reliability, which is often the case for non-critical events such as particle effects, sounds effects etc. +:::caution +Packet reliability can be a two edged sword (pro and con): +- **The Pro**: Under bad network conditions a reliable packet is guaranteed to be received by the target remote side. +- **The Con**: Because the sender will continue trying to send a reliable packet if it does not get a "packet received" response, under bad network conditions too many reliable packets being sent can cause additional bandwidth overhead. +::: + +### Reliable and Unreliable RPC Examples: +Reliability configuration can be specified for both `ServerRpc` and `ClientRpc` methods at compile-time: + +```csharp + +[ServerRpc] +void MyReliableServerRpc() { /* ... */ } + +[ServerRpc(Delivery = RpcDelivery.Unreliable)] +void MyUnreliableServerRpc() { /* ... */ } + +[ClientRpc] +void MyReliableClientRpc() { /* ... */ } + +[ClientRpc(Delivery = RpcDelivery.Unreliable)] +void MyUnreliableClientRpc() { /* ... */ } +``` + +Reliable RPCs will be received on the remote end in the same order as they are fired but this in-order guarantee only applies to RPCs on the same `NetworkObject`. Different `NetworkObjects` might have reliable RPCs called but executed in different order compared to each other. To put more simply, **in-order reliable RPC execution is guaranteed per `NetworkObject` basis only**. If you determine an RPC is being updated frequently (i.e. several times per second), it _might_ be better suited as an unreliable RPC. +:::caution +When testing unreliable RPCs on a local network, the chance of an unreliable packet being dropped is reduced greatly (sometimes never). As such, you might want to use [`UnityTransport`'s Simulator Pipeline](https://docs-multiplayer.unity3d.com/transport/current/pipelines#simulator-pipeline) to simulate poor network conditions in order to better determine how dropped unreliable RPC messages impacts your project. +::: + +:::tip +Sometimes you might find out that you are sending parameters that are both critical and non-critical. Under this scenario you might benefit by splitting the RPC into two or more RPCs with the less critical parameters being sent unreliably (possibly at the same or higher frequency) while the more critical parameters are sent reliably (possibly at the same or lower frequency). +::: + +### Additional RPC Facts +- An RPC call made without an active connection will not be automatically added to the send queue and will be dropped/ignored. +- Both reliable and unreliable RPC calls have to be made when there is an active network connection established between a client and the server. _The caveat to this rule is if you are running a host since a host is both a server and a client:_ + - _A host can send RPC messages from the "host-server" to the "host-client" and vice versa._ +- Reliable RPC calls made during connection will be dropped if the sender disconnects before the RPC is sent. + diff --git a/versioned_docs/version-1.0.0/advanced-topics/message-system/rpc-compatibility.md b/versioned_docs/version-1.0.0/advanced-topics/message-system/rpc-compatibility.md new file mode 100644 index 000000000..23838fadc --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/message-system/rpc-compatibility.md @@ -0,0 +1,92 @@ +--- +id: rpc-compatibility +title: RPC migration and compatibility +--- +import ImageSwitcher from '@site/src/ImageSwitcher.js'; + +This section provides information on compatibility and support for Unity Netcode for GameObjects (Netcode) features compared to previous Netcode versions. See the [Release Notes](../../../../releases/introduction) for more information. + +## Cross-Compatibility + +Learn more about standard RPC API's cross-compatibility only, not the framework as a whole. A method marked as RPC will be statically registered with its assembly-scoped method signature hash. + +A typical assembly-scoped method signature sample: + +``` +Game.dll / System.Void Shooter::PingServerRpc(System.Int32,MLAPI.Messaging.ServerRpcParams) +``` + +where: + +- `Game.dll` is the Assembly +- `/` is a Separator +- `System.Void Shooter::PingServerRpc(System.Int32,MLAPI.Messaging.ServerRpcParams)` is the Method signature: + + - `System.Void` is the Return type + - `Shooter` is the Enclosing type + - `::` is the Scope resolution operator + - `PingServerRpc` is the Method name + - `(System.Int32,MLAPI.Messaging.ServerRpcParams)` is the Params with types (no param names) + +An RPC signature will be turned into a 32-bit integer using [xxHash](https://cyan4973.github.io/xxHash/) (XXH32) non-cryptographic hash algorithm. + +As expected, RPC signature therefore its hash will be changed if assembly, return type, enclosing type, method name and/or any method param type changes. Names of method parameters can be changed as they are not a part of the method signature. + +A change in the RPC signature will lead into a different send/receive codepath with different serialization code and execute a different method body. Previous versions of the RPC method will not be executed by the new RPC method with the new signature. + +| Compatibility | | Description | +| -- | :--: | -- | +| Cross-Build Compatibility | | As long as the RPC method signature is kept the same, it will be compatible between different builds. | +| Cross-Version Compatibility | | As long as the RPC method signature is kept the same, it will be compatible between different versions. | +| Cross-Project Compatibility | | Since project name or any project-specific token is not being a part of RPC signature, it is possible to have the exact same RPC method signature defined in different builds and they are not necessarily going to be compatible with each other. | + +## Deprecation of return values + +Netcode supports RPC return values on convenience RPCs. + +Example: + +```csharp +public IEnumerator MyRpcCoroutine() +{ + RpcResponse response = InvokeServerRpc(MyRpcWithReturnValue, Random.Range(0f, 100f), Random.Range(0f, 100f)); + + while (!response.IsDone) + { + yield return null; + } + + Debug.LogFormat("The final result was {0}!", response.Value); +} + +[ServerRPC] +public float MyRpcWithReturnValue(float x, float y) +{ + return x * y; +} + +``` + +To achieve similar functionality, use the following: + +```csharp +void MyRpcInvoker() +{ + MyRpcWithReturnValueRequestServerRpc(Random.Range(0f, 100f), Random.Range(0f, 100f)); +} + +[ServerRpc] +void MyRpcWithReturnValueRequestServerRpc(float x, float y) +{ + MyRpcWithReturnValueResponseClientRpc(x * y); +} + +[ClientRpc] +void MyRpcWithReturnValueResponseClientRpc(float result) +{ + Debug.LogFormat("The final result was {0}!", result); +} +``` + +import useBaseUrl from '@docusaurus/useBaseUrl'; +import Link from '@docusaurus/Link'; \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/advanced-topics/message-system/rpc-params.md b/versioned_docs/version-1.0.0/advanced-topics/message-system/rpc-params.md new file mode 100644 index 000000000..0661cb2d9 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/message-system/rpc-params.md @@ -0,0 +1,48 @@ +--- +id: rpc-params +title: RPC Params +--- +import ImageSwitcher from '@site/src/ImageSwitcher.js'; + +Both `ServerRpc` and `ClientRpc` methods can be configured either by `[ServerRpc]` and `[ClientRpc]` attributes at compile-time and `ServerRpcParams` and `ClientRpcParams` at runtime. + +Developers can put `ServerRpcParams` and `ClientRpcParams` as the last parameter (optionally). They can also be used for a consolidated space for `XXXRpcReceiveParams` and `XXXRpcSendParams`. + +The network framework will inject the corresponding `XXXRpcReceiveParams` to what the user had declared in code when invoked by network receive handling (framework code) and will consume `XXXRpcSendParams` when invoked by RPC send call (user code). + + +## ServerRpc Params + +See the following for `ServerRpc` params: + +``` csharp +// Both ServerRpc methods below are fine, `ServerRpcParams` is completely optional + +[ServerRpc] +void AbcdServerRpc(int somenumber) { /* ... */ } + +[ServerRpc] +void XyzwServerRpc(int somenumber, ServerRpcParams serverRpcParams = default) { /* ... */ } +``` + +[ServerRpcParams Documentation](../../api/Unity.Netcode.ServerRpcParams) + +## ClientRpc Params + +See the following for `ClientRpc` params: + +```csharp +// Both ClientRpc methods below are fine, `ClientRpcParams` is completely optional + +[ClientRpc] +void AbcdClientRpc(int framekey) { /* ... */ } + +[ClientRpc] +void XyzwClientRpc(int framekey, ClientRpcParams clientRpcParams = default) { /* ... */ } +``` + +[ClientRpcParams Documentation](../../api/Unity.Netcode.ClientRpcParams) + +:::tip +`ClientRpcSendParams`'s `TargetClientIds` property is a `ulong[]` which means everytime you try to specify a subset of target clients or even a single client target, you will have to allocate a `new ulong[]`. This pattern could quickly lead into lots of heap allocations and pressure GC which would cause GC spikes at runtime. We suggest developers cache their `ulong[]` variables or use an array pool to cycle `ulong[]` instances so that it would cause less heap allocations. +::: diff --git a/versioned_docs/version-1.0.0/advanced-topics/message-system/serverrpc.md b/versioned_docs/version-1.0.0/advanced-topics/message-system/serverrpc.md new file mode 100644 index 000000000..4f8448595 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/message-system/serverrpc.md @@ -0,0 +1,157 @@ +--- +id: serverrpc +title: ServerRpc +--- +import ImageSwitcher from '@site/src/ImageSwitcher.js'; + +## Introduction +A `ServerRpc` provides you with the ability to send information from a client to a server just like you would invoke a method from within a class. A `ServerRpc` is a remote procedure call (RPC) that can be only invoked by a client and will always be received and executed on the server/host. + +## Declaring a ServerRpc +You can declare a `ServerRpc` by: +1. Creating a method that ends with the `ServerRpc` suffix within a `NetworkBehaviour` derived class. +2. Adding the `[ServerRpc]` attribute above the method + +### Example of declaring a ServerRpc: +```csharp +public class SomeNetworkBehaviour : NetworkBehaviour +{ + [ServerRpc] + public void PingServerRpc(int pingCount) + { + + } +} +``` +The above example uses the default [ServerRpc] attribute settings which only allows a client owner (client that owns `NetworkObject` associated with the `NetworkBehaviour` containing the `ServerRpc` method) invocation rights. Any client that is not the owner will not be allowed to invoke the `ServerRpc`. + +## ServerRpc Ownership And ServerRpcParams +There are times where you might want any client to have `ServerRpc` invocation rights. You can easily accomplish this by setting the `ServerRpc` attribute's `RequireOwnership` parameter to false like in the example below: +```csharp +[ServerRpc(RequireOwnership = false)] +public void MyGlobalServerRpc(ServerRpcParams serverRpcParams = default) +{ + var clientId = serverRpcParams.Receive.SenderClientId; + if (NetworkManager.ConnectedClients.ContainsKey(clientId)) + { + var client = NetworkManager.ConnectedClients[clientId]; + // Do things for this client + } +} +``` +In the above example, you will also notice that `MyGlobalServerRpc` takes a single parameter of type [`ServerRpcParams`](https://docs-multiplayer.unity3d.com/netcode/current/api/Unity.Netcode.ServerRpcParams). This parameter type is optional, but it can be very useful to identify **which client** was requesting the server invoke the RPC. The `ServerRpcParams.Receive.SenderClientId` property is automatically set upon the server receiving the `ServerRpc` request and used to get the server-side `NetworkClient` instance of the client (sender). +:::important Best Practice +Using the `ServerRpcParams.Receive.SenderClientId` property is considered the best practice to identify which client was invoking the `ServerRpc`. It is not recommended to send the client identifier via an additional `ulong` parameter added to the `ServerRpc`:
+```csharp +[ServerRpc(RequireOwnership = false)] +public void MyGlobalServerRpc(ulong clientId) // This is considered a bad practice (Not Recommended) +{ + if (NetworkManager.ConnectedClients.ContainsKey(clientId)) + { + var client = NetworkManager.ConnectedClients[clientId]; + // Do things for this client + } +} +``` +The primary reason, especially when `RequireOwnership == false`, is that it could introduce potential security issues. The secondary reason is that this value is already automatically provided to you via `ServerRpcParams` without the additional `ulong` parameter bandwidth overhead you would incur by sending the client identifier as a `ServerRpc` parameter. +::: + +Now, taking the best practices example into consideration, you might want to have other valid parameters added to your `ServerRpc`. When adding additional parameters other than the `ServerRpcParams` parameter, you **must** declare `ServerRpcParams` as the **last** parameter of the `ServerRpc`: +```csharp +[ServerRpc(RequireOwnership = false)] +public void PlayerShootGunServerRpc(Vector3 lookWorldPosition, ServerRpcParams serverRpcParams = default) +{ + var clientId = serverRpcParams.Receive.SenderClientId; + if (NetworkManager.ConnectedClients.ContainsKey(clientId)) + { + var client = NetworkManager.ConnectedClients[clientId]; + var castRay = new Ray(client.PlayerObject.transform.position, lookWorldPosition); + RaycastHit rayCastHit; + if (Physics.Raycast(castRay, out rayCastHit, 100.0f)) + { + // Handle shooting something + } + } +} +``` +Looking at the above example, we can see the client invoking the `PlayerShootGunServerRpc` method passes in a world position based on perhaps a screen space crosshair position to world space position, the `ServerRpcParams`, and the `ServerRpc` doesn't require ownership. + +:::tip Alternate Owner Example +Of course, if your project's design was such that a weapon changes ownership when it is picked up by a player, then you would only allow owners to invoke the method and would only need the one `Vector3` parameter like in the example below: +```csharp +[ServerRpc] +public void PlayerOwnerShootGunServerRpc(Vector3 lookWorldPosition) +{ + if (NetworkManager.ConnectedClients.ContainsKey(OwnerClientId)) + { + var client = NetworkManager.ConnectedClients[OwnerClientId]; + var castRay = new Ray(client.PlayerObject.transform.position, lookWorldPosition); + RaycastHit rayCastHit; + if (Physics.Raycast(castRay, out rayCastHit, 100.0f)) + { + // Handle shooting something + } + } +} +``` +::: + +## Invoking a ServerRpc +From the example below that uses the `PlayerOwnerShootGunServerRpc` method, you can see that you would invoke it just any other method: + +```csharp +private void Update() +{ + if (!IsSpawned || !IsOwner) + { + return; + } + + if (Input.GetKeyDown(KeyCode.Space)) + { + var point = new Vector3(); + var currentEvent = Event.current; + var mousePos = new Vector2(); + + // Get the mouse position from Event. + // Note that the y position from Event is inverted. + mousePos.x = currentEvent.mousePosition.x; + mousePos.y = Camera.current.pixelHeight - currentEvent.mousePosition.y; + + point = Camera.current.ScreenToWorldPoint(new Vector3(mousePos.x, + mousePos.y, Camera.current.nearClipPlane)); + + PlayerOwnerShootGunServerRpc(point); + } +} +``` + +### ServerRpc Timing +The following are a few timing diagrams to help provide additional visual context when invoking a `ServerRpc`. + +
+ +
Client can invoke a server RPC on a Network Object. The RPC will be placed in the local queue and then sent to the server, where it will be executed on the server version of the same Network Object.
+
+ +
+ +
Clients can invoke server RPCs on Client Hosts the same way they can invoke server RPCs on the regular servers: the RPC will be placed in the local queue and then sent to the Client Host, where it will be executed on the Client Host's version of the same Network Object.
+
+ +
+ +
When a server RPC is invoked by the Client Host, the RPC will be placed in a local queue and then executed on the Client Host after a short delay. The same happens for pure servers.
+
+ +## See Also + +* [ClientRpc](clientrpc.md) +* [RPC Params](rpc-params.md) +* See [examples](../../learn/bossroom/bossroom-actions) of how these were used in Boss Room. diff --git a/versioned_docs/version-1.0.0/advanced-topics/messaging-system.md b/versioned_docs/version-1.0.0/advanced-topics/messaging-system.md new file mode 100644 index 000000000..17c70607a --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/messaging-system.md @@ -0,0 +1,81 @@ +--- +id: messaging-system +title: Sending Events with RPCs +description: An introduction to the messaging system in Unity MLAPI, including RPC's and Custom Messages. +--- +import ImageSwitcher from '@site/src/ImageSwitcher.js'; + +Netcode for GameObjects (Netcode) has two parts to its messaging system: RPCs and [Custom Messages](message-system/custom-messages.md). Both types have sub-types that change their behaviour, functionality, and performance. This page will focus on RPCs. + +## RPC: Remote Procedure Call + +The concept of an `RPC` is common not only in video games but in the software industry in general. They are ways to call methods on objects that are not in the same executable. + +
+ +
Client can invoke a server RPC on a Network Object. The RPC will be placed in the local queue and then sent to the server, where it will be executed on the server version of the same Network Object.
+
+ +At a high level, when calling an `RPC` client side, the SDK will take a note of the object, component, method and any parameters for that `RPC` and send that information over the network. The server will receive that information, find the specified object, find the specified method and call it on the specified object with the received parameters. + +When calling an `RPC`, you call a method remotely on an object that could be anywhere in the world. They are "events" you can trigger when needed. + +If you call an `RPC` method on your side, it will execute on a different machine. + +Netcode has two variations of RPCs to execute logic on either server-side or client-side: [`ServerRpc`](message-system/serverrpc.md) and [`ClientRpc`](message-system/clientrpc.md). + +
+ +
Server can invoke a client RPC on a Network Object. The RPC will be placed in the local queue and then sent to a selection of clients (by default this selection is "all clients"). When received by a client, RPC will be executed on the client's version of the same Network Object.
+
+ + +:::info +For more information see the wikipedia entry on [Remote Procedure Call's](https://en.wikipedia.org/wiki/Remote_procedure_call). +::: + +### Netcode's RPCs + +See the following pages for more information: + +- [ClientRpc](message-system/clientrpc.md) +- [ServerRpc](message-system/serverrpc.md) +- [Reliability](message-system/reliabilty.md) +- [Execution Table](message-system/execution-table.md) +- [RPC Params](message-system/rpc-params.md) + - [Serialization Types and RPCs](message-system/../serialization/serialization-intro.md) + +There is also some additional design advice on RPC's and some usage examples on the following pages: + +- [RPC vs NetworkVariable](../learn/rpcvnetvar.md) +- [RPC vs NewtorkVariables Examples](../learn/rpcnetvarexamples.md) + +:::note Migration and Compatibility +See [RPC Migration and Compatibility](message-system/rpc-compatibility.md) for more information on updates, cross-compatibility, and deprecated methods for Unity RPC. +::: + +## RPC method calls + +A typical SDK user (Unity developer) can declare multiple RPCs under a `NetworkBehaviour` and inbound/outbound RPC calls will be replicated as a part of its replication in a network frame. + +A method turned into an RPC is no longer a regular method, it will have its own implications on direct calls and in the network pipeline. See [Execution Table](message-system/execution-table.md). + +### RPC usage checklist: +To use RPCs, make sure +- ```[ClientRpc]``` or ```[ServerRpc]``` attributes are on your method +- Your method name ends with ```ClientRpc``` or ```ServerRpc``` (ex: ```DoSomethingServerRpc()```) +- your method is declared in a class that inherits from NetworkBehaviour + - your GameObject has a NetworkObject component attached +- Make sure to call your RPC method server side or client side (using ```isClient``` or ```isServer```) +- Only accept value types as parameters + +## Serialization Types and RPCs + +Instances of Serializable Types are passed into an RPC as parameters and are serialized and replicated to the remote side. + +See [Serialization](serialization/serialization-intro.md) for more information. + diff --git a/versioned_docs/version-1.0.0/advanced-topics/network-update-loop-system/index.md b/versioned_docs/version-1.0.0/advanced-topics/network-update-loop-system/index.md new file mode 100644 index 000000000..e6808243b --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/network-update-loop-system/index.md @@ -0,0 +1,54 @@ +--- +id: about-network-update-loop +title: About Network Update Loop +--- + +Often there is a need to update netcode systems like RPC queue, transport IO, and others outside the standard `MonoBehaviour` event cycle. + +The Network Update Loop infrastructure utilizes Unity's low-level Player Loop API allowing for registering `INetworkUpdateSystems` with `NetworkUpdate()` methods to be executed at specific `NetworkUpdateStages` which may be either prior to or after `MonoBehaviour`-driven game logic execution. + +Typically you will interact with `NetworkUpdateLoop` for registration and `INetworkUpdateSystem` for implementation. Systems such as network tick and future features (such as network variable snapshotting) will rely on this pipeline. + +## Registration + +`NetworkUpdateLoop` exposes four methods for registration: + +| Method | Registers | +| -- | -- | +| `void RegisterNetworkUpdate(INetworkUpdateSystem updateSystem, NetworkUpdateStage updateStage)` | Registers an `INetworkUpdateSystem` to be executed on the specified `NetworkUpdateStage` | +| `void RegisterAllNetworkUpdates(INetworkUpdateSystem updateSystem)` | Registers an `INetworkUpdateSystem` to be executed on all `NetworkUpdateStage`s | +| `void UnregisterNetworkUpdate(INetworkUpdateSystem updateSystem, NetworkUpdateStage updateStage)` | Unregisters an `INetworkUpdateSystem` from the specified `NetworkUpdateStage` | +| `void UnregisterAllNetworkUpdates(INetworkUpdateSystem updateSystem)` | Unregisters an `INetworkUpdateSystem` from all `NetworkUpdateStage`s | + +## Update Stages + +After injection, the player loops follows these stages. The player loop executes the `Initialization` stage and that invokes `NetworkUpdateLoop`'s `RunNetworkInitialization` method which iterates over registered `INetworkUpdateSystems` in `m_Initialization_Array` and calls `INetworkUpdateSystem.NetworkUpdate(UpdateStage)` on them. + +In all `NetworkUpdateStages`, it iterates over an array and calls the `NetworkUpdate` method over `INetworkUpdateSystem` interface, and the pattern is repeated. + + B --> C --> D --> E --> F --> G +`}/> + +| Stage | Method | +| -- | -- | +| `Initialization` | `RunNetworkInitialization` | +| `EarlyUpdate` | `RunNetworkEarlyUpdate`
`ScriptRunDelayedStartupFrame`
Other systems | +| `FixedUpdate` | `RunNetworkFixedUpdate`
`ScriptRunBehaviourFixedUpdate`
Other systems | +| `PreUpdate` | `RunNetworkPreUpdate`
`PhysicsUpdate`
`Physics2DUpdate`
Other systems | +| `Update` | `RunNetworkUpdate`
`ScriptRunBehaviourUpdate`
Other systems | +| `PreLateUpdate` | `RunNetworkPreLateUpdate`
`ScriptRunBehaviourLateUpdate` | +| `PostLateUpdate` | `PlayerSendFrameComplete`
`RunNetworkPostLateUpdate`
Other systems | + +## References + +See [Network Update Loop Reference](network-update-loop-reference.md) for process flow diagrams and code. + diff --git a/versioned_docs/version-1.0.0/advanced-topics/network-update-loop-system/network-update-loop-reference.md b/versioned_docs/version-1.0.0/advanced-topics/network-update-loop-system/network-update-loop-reference.md new file mode 100644 index 000000000..857045c90 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/network-update-loop-system/network-update-loop-reference.md @@ -0,0 +1,22 @@ +--- +id: network-update-loop-reference +title: Network Update Loop Reference +--- + +The following diagrams provide insight into the Network Update Loop process and APIs. + +## Injecting NetworkUpdateLoop Systems Into PlayerLoop + +
+ +![Injecting NetworkUpdateLoop Systems Into PlayerLoop](/img/injecting-networkupdatesloop.svg) + +
+ +## NetworkUpdateLoop Running INetworkUpdateSystem Updates + +
+ +![NetworkUpdateLoop Running INetworkUpdateSystem Updates](/img/runninginetworkupdatesystemupdates.svg) + +
diff --git a/versioned_docs/version-1.0.0/advanced-topics/networkobject-parenting.md b/versioned_docs/version-1.0.0/advanced-topics/networkobject-parenting.md new file mode 100644 index 000000000..d209eafc4 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/networkobject-parenting.md @@ -0,0 +1,192 @@ +--- +id: networkobject-parenting +title: NetworkObject Parenting +description: A `NetworkObject` parenting solution within Netcode for GameObjects (Netcode) to help developers with synchronizing transform parent-child relationships of `NetworkObjects`. + +--- +### Overview +If you aren't completely familiar with transform parenting in Unity, then it is highly recommended to [review over the existing Unity documentation](https://docs.unity3d.com/Manual/class-Transform.html) before reading further. In order to properly synchronize all connected clients with any change in a `GameObject`'s transform parented status, Netcode for GameObjects (NGO) requires that the parent and child `GameObject`s have `NetworkObject` components attached to them. + +### Parenting Rules +- Setting the parent of a child's `Transform` directly (i.e. `transform.parent = childTransform;`) will always use the default `WorldPositionStays` value of `true`. + - It is recommended to always use the `NetworkObject.TrySetParent` method when parenting if you plan on changing the `WorldPositionStays` default value. + - Likewise, it is also recommended to use the `NetworkObject.TryRemoveParent` method to remove a parent from a child. +- When a server parents a spawned `NetworkObject` under another spawned `NetowrkObject` during a netcode game session this parent child relationship is replicated across the network to all connected and future late joining clients. +- If, while editing a scene, you place an in-scene placed `NetworkObject` under a `GameObject` that does not have a `NetworkObject` component attached to it, NGO will preserve that parenting relationship. + - During runtime, this parent-child hierarchy will remain true unless user code removes the GameObject parent from the child NetworkObject. + - _Note: Once removed, NGO will not allow you to re-parent the `NetworkObject` back under the same or another `GameObject` that with no `NetworkObject` component attached to it._ +- You can perform the same parenting actions with in-scene placed `NetworkObject`s as you can with dynamically spawned `NetworkObject`s. + - Only in-scene placed `NetworkObject`s can have multiple generations of nested `NetworkObject` children. + - You can parent dynamically spawned `NetworkObject`s under in-scene placed `NetworkObject`s and vice versa. +- To adjust a child's transform values when parenting or when removing a parent: + - Override the `NetworkBehaviour.OnNetworkObjectParentChanged` virtual method within a `NetworkBehaviour` attached to the child NetworkObject. + - When `OnNetworkObjectParentChanged` is invoked, on the server side, adjust the child's transform values within the overridden method. + - NGO will then synchronize all clients with the child's parenting and transform changes. + +:::tip +When a NetworkObject is parented, NGO will synchronize both the parenting information along with the child's transform values. NGO uses the `WorldPositionStays` setting to determine whether to synchronize the local or world space transform values of the child `NetworkObject`. This means that a `NetworkObject` does not require you to include a `NetworkTransform` component if it never moves around, rotates, or changes its scale when it is not parented. This can be useful for world items a player might pickup (i.e. parent the item under the player) and the item in question needs to be adjusted relative to the player when it is parented or the parent is removed (i.e. dropped). This helps to reduce the item's over-all bandwidth and processing resources consumption. +::: + +### OnNetworkObjectParentChanged +[`NetworkBehaviour.OnNetworkObjectParentChanged`](https://docs-multiplayer.unity3d.com/netcode/current/api/Unity.Netcode.NetworkBehaviour#onnetworkobjectparentchangednetworkobject) is a virtual method you can override to be notified when a `NetworkObject`'s parent has changed. The [`MonoBehaviour.OnTransformParentChanged()`](https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTransformParentChanged.html) method is used by `NetworkObject` to catch `transform.parent` changes and notify its associated `NetworkBehaviour`s. + +```csharp +/// +/// Gets called when the parent NetworkObject of this NetworkBehaviour's NetworkObject has changed +/// +virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) { } +``` + +:::caution Multi-Generation Children and Scale +If you are dealing with more than one generation of nested children where each parent and child have scale values other than `Vector3.one`, then mixing the `WorldPositionStays` value when parenting and removing a parent will impact how the final scale is calculated! If you want to maintain the same values prior to parenting when removing a parent from a child, then you need to use the same `WorldPositionStays` value used when the child was parented. +::: + +### Only A Server (or A Host) Can Parent NetworkObjects +Similar to [Ownership](../basics/networkobject#ownership), only the server (or host) can control `NetworkObject` parenting. + +:::tip +If you run into a situation where your client must trigger parenting a `NetworkObject`, one solution is for the client to send an RPC to the server. Upon receiving the RPC message, the server then handles parenting the `NetworkObject`. +::: + +### Only Parent Under A `NetworkObject` Or Nothing (i.e. The Root or null) +You can only parent a NetworkObject under another NetworkObject. The only exception is if you don't want the NetworkObject to have a parent. In this case, you would can remove the NetworkObject's parent by invoking `NetworkObject.TryRemoveParent`. If this operation succeeds, the the parent of the child will be set to `null` (root of the scene hierarchy). + +### Only Spawned NetworkObjects Can Be Parented +A `NetworkObject` can only be parented if it is spawned and can only be parented under another spawned `NetworkObject`. This also means that `NetworkObject` parenting can only occur during a network session (netcode enabled game session). Think of `NetworkObject` parenting as a netcode event. In order for it to happen, you must have, at very minimum, a server or host instance started and listening. + +### Invalid Parenting Actions Are Reverted +If an invalid/unsupported `NetworkObject` parenting action occurs, the attempted parenting action will be reverted back to the `NetworkObject`'s original parenting state. + +**For example:** +If you had a `NetworkObject` who's current parent was root and tried to parent it in an invalid way (i.e. under a GameObject without a `NetworkObject` component) then a warning message would be logged and the `NetworkObject` would revert back to having root as its parent. + +### In-scene Object Parenting and Player Objects +If you plan on parenting in-scene placed `NetworkObject`s with a player `NetworkObject` when it is initially spawned, you need to wait until the client has finished synchronizing with the server first. Since parenting can only be performed on the server side, you should perform the parenting action only when the server has received the `NetworkSceneManager` generated `SceneEventType.SynchronizeComplete` message from the client that owns the player `NetworkObject` to be parented (as a child or parent). +:::info For More Information +- [Real World In-scene NetworkObject Parenting of Players Solution](inscene_parenting_player.md)
+- [Scene Event Notifications](../basics/scenemanagement/scene-events#scene-event-notifications)
+- [In-Scene NetworkObjects](../basics/scenemanagement/inscene-placed-networkobjects.md) +::: + +### WorldPositionStays usage +When using the `NetworkObject.TrySetParent` or `NetworkObject.TryRemoveParent` methods, the `WorldPositionStays` parameter is synchronized with currently connected and late joining clients. When removing a child from its parent, you should use the same `WorldPositionStays` value that was used to parent the child. More specifically when `WorldPositionStays` is set to false this applies, but if you are using the defalt value of `true` then this is not required (because it is the default). + +When the `WorldPositionStays` parameter in `NetworkObject.TrySetParent` is the default value of `true`, this will preserve the world space values of the child `NetworkObject` relative to the parent. However, sometimes you might want to only preserve the local space values (i.e. pick up an object that only has some initial changes to the child's transform when parented). Through a combination of `NetworkObject.TrySetParent` and `NetworkBehaviour.OnNetworkObjectParentChanged` you can accomplish this without the need for a `NetworkTransform`. To better understand how this works, it is important to understand the order of operations for both of these two methods: + +**Server-Side** +- `NetworkObject.TrySetParent` invokes `NetworkBehaviour.OnNetworkObjectParentChanged` + - You can make adjustments to the child's position, rotation, and scale in the overridden `OnNetworkObjectParentChanged` method. +- The ParentSyncMessage is generated, the transform values are added to the message, and the message is then sent. + - ParentSyncMessage includes the child's position, rotation, and scale + - Currently connected or late joining clients will be synchronized with the parenting and the child's associated transform values + +**When to use a NetworkTransform**
+If you plan on the child `NetowrkObject` moving around, rotating, or scaling independently (when parented or not) then you will still want to use a NetworkTransform. +If you only plan on making a one time adjustment to the child `NetworkObject`'s transform when parented or having a parent removed, then the child does not need a `NetworkTransform` component. + +:::info For More Information +- [Learn More About WorldPositionStays](https://docs.unity3d.com/ScriptReference/Transform.SetParent.html) +::: + +### Network Prefabs, Parenting, and NetworkTransforms +Since the `NetworkTransform` component synchronizes the transform of a `GameObject` (with a `NetworkObject` component attached to it), it can become tricky to understand the parent-child transform relationship and how that translates when synchronizing late joining clients. Currently, a network prefab can only have one `NetworkObject` component within on the root `GameObject` of the prefab. However, you can have a complex hierarchy of `GameObject`s nested under the root `GameObjet` and each child `GameObject` can have a `NetworkBehaviour` attached to it. Since a `NetworkTransform` synchronizes the transform of the `GameObject` it is attached to, you might be tempted to setup a network prefab like this: + +``` +Network Prefab Root (GameObject with NetworkObject and NetworkTransform components attached to it) + ├─ Child #1 (GameObject with NetworkTransform component attached to it) + │ + └─ Child #2 (GameObject with NetworkTransform component attached to it) +``` +While this will not give you any warnings and, depending upon the transform settings of Child #1 & #2, it might appear to work properly (i.e. synchronizes clients, etc.), it is important to understand how the child `GameObject`, with no `NetworkObject` component attached to it, and parent `GameObject`, that does have a `NetworkObject` component attached to it, will be synchronized when a client connects to an already in-progress network session (i.e. late joins or late joining client). If Child #1 or Child #2 have had changes to their respective `GameObject`'s transform prior to a client joining, then upon a client late joining the two child `GameObject`'s transforms will not get synchronized during the initial synchronization period because they do not have `NetworkObject` components attached to them: + +``` +Network Prefab Root (Late joining client is synchronized with `GameObject`'s current transform state) + ├─ Child #1 (Late joining client *is not synchronized* with `GameObject`'s current transform state) + │ + └─ Child #2 (Late joining client *is not synchronized* with `GameObject`'s current transform state) +``` +This *is important* to understand because the `NetworkTransform` component initializes itself, during `NetworkTransform.OnNetworkSpawn`, with the `GameObject`'s current transform state. Just below, in the parenting examples, we provide you with some valid and invalid parenting rules. As such, you should take these rules into consideration when using `NetworkTransform` components if you plan on using a complex parent-child hierarchy and should make sure to organize your project's assets where any children that have `NetworkTransform` components attached to them also have `NetworkObject` components attached to them to avoid late-joining client synchronization issues. + +## Parenting Examples + +### Simple Example: +Let's assume we have the following initial scene hierarchy before we attempt parenting: +``` +Sun +Tree +Camera +Player (GameObject->NetworkObject) +Vehicle (GameObject->NetworkObject) +``` +Both the player and vehicle `NetworkObject`s are spawned and the player moves towards the vehicle and wants to "get into" the vehicle. The player's client sends perhaps a "use object" RPC command to the server. In turn, the server then parents the player under the vehicle and changes the player's model pose to sitting. Since both `NetworkObject`s are spawned and the server is receiving an RPC to perform the parenting action, the parenting action performed by the server is considered valid and the player is then parented under the vehicle as it is shown below: + +``` +Sun +Tree +Camera +Vehicle (GameObject->NetworkObject) + └─ Player (GameObject->NetworkObject) +``` + +### Mildly Complex Invalid Example: +``` +Sun +Tree +Camera +Player (GameObject->NetworkObject) +Vehicle (GameObject->NetworkObject) + ├─ Seat1 (GameObject) + └─ Seat2 (GameObject) +``` +In the above example, the vehicle has two GameObjects nested under the vehicle's root GameObject to represent the two available seats. If we tried to parent the player under Seat1: +``` +Sun +Tree +Camera +Vehicle (GameObject->NetworkObject) + ├─Seat1 (GameObject) + │ └─Player (GameObject->NetworkObject) + └─Seat2 (GameObject) +``` +This would be considered an invalid parenting and would be reverted. + +### Mildly Complex Valid Example: +In order to resolve the previous invalid parenting issue, we would need to add a `NetworkObjet` component to the seats. This means we would need to: +1. Spawn the vehicle and the seats: +``` +Sun +Tree +Camera +Player (GameObject->NetworkObject) +Vehicle (GameObject->NetworkObject) +Seat1 (GameObject->NetworkObject) +Seat2 (GameObject->NetworkObject) +``` + +2. Once spawned, parent the seats under the vehicle + +``` +Sun +Tree +Camera +Player (GameObject->NetworkObject) +Vehicle (GameObject->NetworkObject) + ├─ Seat1 (GameObject->NetworkObject) + └─ Seat2 (GameObject->NetworkObject) +``` +3. Finally, some time later a player wants to get into the vehicle and the player is parented under Seat1: +``` +Sun +Tree +Camera +Vehicle (GameObject->NetworkObject) + ├─Seat1 (GameObject->NetworkObject) + │ └─Player (GameObject->NetworkObject) + └─Seat2 (GameObject->NetworkObject) +``` + +:::note Optional Auto Synchronized Parenting +The Auto Object Parent Sync property of NetworkObject, enabled by default, allows you to disable automatic parent change synchronization in the event you want to implement your own parenting solution for one or more NetworkObjects. +::: + + diff --git a/versioned_docs/version-1.0.0/advanced-topics/networktime-ticks.md b/versioned_docs/version-1.0.0/advanced-topics/networktime-ticks.md new file mode 100644 index 000000000..3d6308007 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/networktime-ticks.md @@ -0,0 +1,203 @@ +--- +id: networktime-ticks +title: NetworkTime and Ticks +sidebar_label: NetworkTime & Ticks +--- + +## LocalTime and ServerTime + +Why are there two different time values and which one should be used? + +Netcode for GameObjects (Netcode) uses a star topology. That means all communications happen between the clients and the server/host and never between clients directly. Messages take time to transmit over the network. That's why `RPCs` and `NetworkVariable` will not happen immediately on other machines. `NetworkTime` allows to use time while considering those transmission delays. + +- `LocalTime` on a client is ahead of the server. If a server RPC is sent at `LocalTime` from a client it will roughly arrive at `ServerTime` on the server. +- `ServerTime` on clients is behind the server. If a client RPC is sent at `ServerTime` from the server to clients it will roughly arrive at `ServerTime` on the clients. + + + +>Server: Delay when sending message + Note over Server: Message arrives at ServerTime. + Note over Server: On server: ServerTime == LocalTime. + Note over Server: Send message to clients at LocalTime. + Server->>Receiver: Delay when sending message + Note over Receiver: Message arrives at ServerTime. +`}/> + + + + +`LocalTime` +- Use for player objects with client authority. +- Use if just a general time value is needed. + +`ServerTime`: +- For player objects with server authority (E.g. by sending inputs to the server via RPCs) +- In sync with position updates of `NetworkTransform` for all `NetworkObjects` where the client is not authoritative over the transform. +- For everything on non client controlled `NetworkObjects`. + +## Examples + +### Example 1: Using network time to synchronize environments + +Many games have environmental objects which move in a fixed pattern. By using network time these objects can be moved without having to synchronize their positions with a `NetworkTransform`. + +For instance the following code could be used to create a moving elevator platform for a client authoritative game: + +```csharp +using Unity.Netcode; +using UnityEngine; + +public class MovingPlatform : MonoBehaviour +{ + public void Update() + { + // Move up and down by 5 meters and change direction every 3 seconds. + var positionY = Mathf.PingPong(NetworkManager.Singleton.LocalTime.TimeAsFloat / 3f, 1f) * 5f; + transform.position = new Vector3(0, positionY, 0); + } +} +``` + +### Example 2: Using network time to create a synced event + +Most of the time aligning an effect precisely to time is not needed. But in some cases for important effects or gameplay events it can help to improve consistency especially for clients with bad network connections. + +```csharp +using System.Collections; +using Unity.Netcode; +using UnityEngine; +using UnityEngine.Assertions; + +public class SyncedEventExample : NetworkBehaviour +{ + public GameObject ParticleEffect; + + // Called by the client to create a synced particle event at its own position. + public void ClientCreateSyncedEffect() + { + Assert.IsTrue(IsOwner); + var time = NetworkManager.LocalTime.Time; + CreateSyncedEffectServerRpc(time); + StartCoroutine(WaitAndSpawnSyncedEffect(0)); // Create the effect immediately locally. + } + + private IEnumerator WaitAndSpawnSyncedEffect(float timeToWait) + { + // Note sometimes the timeToWait will be negative on the server or the receiving clients if a message got delayed by the network for a long time. This usually happens only in rare cases. Custom logic could be implemented to deal with that scenario. + if (timeToWait > 0) + { + yield return new WaitForSeconds(timeToWait); + } + + Instantiate(ParticleEffect, transform.position, Quaternion.identity); + } + + [ServerRpc] + private void CreateSyncedEffectServerRpc(double time) + { + CreateSyncedEffectClientRpc(time); // Call a client RPC to also create the effect on each client. + var timeToWait = time - NetworkManager.ServerTime.Time; + StartCoroutine(WaitAndSpawnSyncedEffect((float)timeToWait)); // Create the effect on the server but wait for the right time. + } + + [ClientRpc] + private void CreateSyncedEffectClientRpc(double time) + { + // The owner already created the effect so skip them. + if (IsOwner == false) + { + var timeToWait = time - NetworkManager.ServerTime.Time; + StartCoroutine(WaitAndSpawnSyncedEffect((float)timeToWait)); // Create the effect on the client but wait for the right time. + } + } +} +``` + +>Server: CreateSyncedEffectServerRpc + Server->>Receiver: CreateSyncedEffectClientRpc + Note over Server: ServerTime = 9.95 #38; timeToWait = 0.05 + Note over Server: StartCoroutine(WaitAndSpawnSyncedEffect(0.05)) + Server->>Server: WaitForSeconds(0.05); + Note over Server: Instantiate effect at ServerTime = 10.0 + Note over Receiver: ServerTime = 9.93 #38; timeToWait = 0.07 + Note over Receiver: StartCoroutine(WaitAndSpawnSyncedEffect(0.07)) + Receiver->>Receiver: WaitForSeconds(0.07); + Note over Receiver: Instantiate effect at ServerTime = 10.0 +`}/> + + + +:::note +Some components such as `NetworkTransform` add additional buffering. When trying to align an RPC event like in this example, an additional delay would need to be added. +::: + +## Network Ticks + +Network ticks are run at a fixed rate. The 'Tick Rate' field on the `NetworkManager` can be used to set the tick rate. + +What does changing the network tick affect? Changes to `NetworkVariables` are not sent immediately. Instead during each network tick changes to `NetworkVariables` are collected and sent out to other peers. + +To run custom code once per network tick (before `NetworkVariable` changes are collected) the `Tick` event on the `NetworkTickSystem` can be used. +```cs +public override void OnNetworkSpawn() +{ + NetworkManager.NetworkTickSystem.Tick += Tick; +} + +private void Tick() +{ + Debug.Log($"Tick: {NetworkManager.LocalTime.Tick}"); +} + +public override void OnNetworkDespawn() // don't forget to unsubscribe +{ + NetworkManager.NetworkTickSystem.Tick -= Tick; +} +``` + +:::tip +When using `FixedUpdate` or physics in your game, set the network tick rate to the same rate as the fixed update rate. The `FixedUpdate` rate can be changed in `Edit > Project Settings > Time > Fixed Timestep` +::: + +## Network FixedTime + +`Network FixedTime` can be used to get a time value representing the time during a network tick. This works similar to `FixedUpdate` where `Time.fixedTime` represents the time during the `FixedUpdate`. + +```cs +public void Update() +{ + double time = NetworkManager.Singleton.LocalTime.Time; // time during this Update + double fixedTime = NetworkManager.Singleton.LocalTime.FixedTime; // time during the previous network tick +} +``` + +## NetworkTime Precision + +Network time values are calculated using double precisions. This allows time to stay accurate on long running servers. For game servers which run sessions for a long time (multiple hours or days) do not convert this value in a float and always use doubles for time related calculations. + +For games with short play sessions casting the time to float is safe or `TimeAsFloat` can be used. + +## NetworkTimeSystem Configuration + +:::caution +The properties of the `NetworkTimeSystem` should be left untouched on the server/host. Changing the values on the client is sufficient to change the behavior of the time system. +::: + +The way network time gets calculated can be configured in the `NetworkTimeSystem` if needed. See the API docs (TODO LINK) for information about the properties which can be modified. All properties can be safely adjusted at runtime. For instance buffer values could be increased for a player with a bad connection. + + + diff --git a/versioned_docs/version-1.0.0/advanced-topics/object-pooling.md b/versioned_docs/version-1.0.0/advanced-topics/object-pooling.md new file mode 100644 index 000000000..cd4d6ffb3 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/object-pooling.md @@ -0,0 +1,28 @@ +--- +id: object-pooling +title: Object Pooling +--- + +Netcode for GameObjects (Netcode) provides built-in support for Object Pooling, which allows you to override the default Netcode destroy and spawn handlers with your own logic. This allows you to store destroyed network objects in a pool to reuse later. This is useful for frequently used objects, such as projectiles, and is a way to increase the application's overall performance. By pre-instantiating and reusing the instances of those objects, object pooling removes the need to create or destroy objects at runtime, which could save a lot of work for the CPU. This means that instead of creating or destroying the same object over and over again, it is simply deactivated after use, then, when another object is needed, the pool recycles one of the deactivated objects and reactivates it. + +See [Introduction to Object Pooling](https://learn.unity.com/tutorial/introduction-to-object-pooling) to learn more about the importance of pooling objects. + +## NetworkPrefabInstanceHandler + +You can register your own spawn handlers by including the `INetworkPrefabInstanceHandler` interface and registering with the `NetworkPrefabHandler`. +```csharp + public interface INetworkPrefabInstanceHandler + { + NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaternion rotation); + void Destroy(NetworkObject networkObject); + } +``` +Netcode will use the `Instantiate` and `Destroy` methods in place of default spawn handlers for the `NetworkObject` used during spawning and despawning. Because the message to instantiate a new `NetworkObject` originates from a Host or Server, both will not have the Instantiate method invoked. All clients (excluding a Host) will have the instantiate method invoked if the `INetworkPrefabInstanceHandler` implementation is registered with `NetworkPrefabHandler` (`NetworkManager.PrefabHandler`) and a Host or Server spawns the registered/associated `NetworkObject`. + +The following example is from the Boss Room Sample. It shows how object pooling is used to handle the different projectile objects. In that example, the class `NetworkObjectPool` is the data structure containing the pooled objects and the class `PooledPrefabInstanceHandler` is the handler implementing `INetworkPrefabInstanceHandler`. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/Infrastructure/NetworkObjectPool.cs +``` + +Let's have a look at `NetworkObjectPool` first. `PooledPrefabsList` contains a list of prefabs to handle, with an initial number of instances to spawn for each. In the `Start` method, it initialises the different pools for each prefab as queues inside the `pooledObjects` dictionary. It also instantiates the handlers for each prefab and registers them. To use these objects, a user then needs to obtain it via the `GetNetworkObject` method before spawning it, then return the object to the pool after use with `ReturnNetworkObject` before despawning it. This only needs to be done on the server, as the `PooledPrefabInstanceHandler` will handle it on the client(s) when the network object's `Spawn` or `Despawn` method is called, via its `Instantiate` and `Destroy` methods. Inside those methods, the `PooledPrefabInstanceHandler` simply calls the pool to get the corresponding object, or to return it. diff --git a/versioned_docs/version-1.0.0/advanced-topics/physics.md b/versioned_docs/version-1.0.0/advanced-topics/physics.md new file mode 100644 index 000000000..7533304fa --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/physics.md @@ -0,0 +1,33 @@ +--- +id: physics +title: Physics +Description: Brief explanation on using Physics in Netcode for GameObjects +--- + +There are many different ways to do physics in multiplayer games. Netcode for GameObjects (Netcode) has a built in approach which allows for server authoritative physics where the physics simulation is only run on the server. To enable network physics add a `NetworkRigidbody` component to your object. + +## NetworkRigidbody + +`NetworkRigidbody` is a component which sets the `Rigidbody` of the `GameObject` into kinematic mode on every peer except the server. That way a realistic physics simulation can be run on the server and the resulting positions can be synchronized to the clients without any interference. + +To use `NetworkRigidbody` add a `Rigidbody`, `NetworkTransform` and `NetworkRigidbody` component to your `NetworkObject`. + +Some collision events are not fired when using `NetworkRigidbody`. +- On the `server` all collision and trigger events (such as OnCollisionEnter) will fire as expected and you can access / modify values of the `Rigidbody` such as velocity. +- On the `clients` the rigidbody will be kinematic. Trigger events will still be fired but collision events will not be fired when colliding with other networked rigidbodies. + +:::tip +If there is a need for a gameplay event to happen on a collision you can listen to `OnCollisionEnter` function on the server and synchronize the event via ClientRpc to all clients. +::: + +## NetworkRigidbody2D + +`NetworkRigidbody2D` works in the same way as `NetworkRigidbody` but for 2d physics (`Rigidbody2D`) instead. + +## NetworkRigidbody & ClientNetworkTransform + +`NetworkRigidbody` can be used in combination with the [ClientNetworkTransform](../components/networktransform.md#clientnetworktransform) package sample to allow the owner client of a `NetworkObject` to move it authoritatively. In this mode collisions will only result in realistic dynamic collisions if the object is colliding with other `NetworkObjects` which are owned by the same client. + +:::note +Add the `ClientNetworkTransform` component first to your `GameObject` else the `NetworkRigidbody` will automatically add a regular `NetworkTransform`. +::: \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/advanced-topics/reconnecting-mid-game.md b/versioned_docs/version-1.0.0/advanced-topics/reconnecting-mid-game.md new file mode 100644 index 000000000..783df14cc --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/reconnecting-mid-game.md @@ -0,0 +1,57 @@ +--- +id: reconnecting-mid-game +title: Reconnecting Mid-Game +--- + +In a multiplayer game, clients may get disconnected from the server for a variety of reasons (network issues, application/device crashes, etc). For those reasons, you may want to allow your players to reconnect to the game. + +## Considerations + +Review the following considerations before allowing clients to reconnect in the middle of an active game: + +- Clients may have specific state and in-game data associated with them. If you want them to reconnect with that same state and data, implement a mechanism to maintain the association of state and data with the client for when they reconnect. See [Session Management](session-management.md) for more information. +- Depending on your game's requirements, make sure the client's state is properly reset and ready to connect before attempting reconnection. This may require resetting some external services. +- When using [scene management](../basics/scenemanagement/scene-management-overview.md) and multiple additive scenes, there is a specific case to keep in mind. During the synchronization process, which launches when connecting to a game, if the client's active main scene is the same as the server's, it will not initiate a scene load in single mode for that scene. Instead, it will load all additive scenes that are currently loaded on the server. This means that if the client has additive scenes currently loaded, it will not unload them like it would if the client's main scene was different than the server's. + - For example, if during a game, the server loads **main scene A**, then additively loads scenes **B** and **C**, the client has all three loaded. If the client disconnects and reconnects without changing scenes, the scene synchronization process recognizes that **main scene A** is already loaded on the client, and then simply proceeds to load the server's additive scenes. In that case, the client loads the scenes **B** and **C** a second time and then has two copies of those scenes loaded. + + However, if, while the client is disconnected, the server loads or unloads a scene additively, there is also a mismatch between the scenes loaded on the client and on the server. For example, if the server unloads scene **C** and loads scene **D**, the client loads scene **D** when synchronizing, but doesn't unload scene C, so the client has loaded scenes **A**, **B** (twice), **C**, and **D**, while the server only has loaded scenes **A**, **B**, and **D**. + - If you want to avoid this behavior, you can + - Load a different scene in single mode on the client when disconnecting + - Unload additive scenes on the client when disconnecting + - Unload additive scenes on the client when reconnecting + - Use the `NetworkSceneManager.VerifySceneBeforeLoading` callback to prevent loading scenes already loaded on the client. However, this will not handle unloading scenes that were unloaded by the server between the time the client disconnected and reconnected. + + +## Automatic reconnection + +For a smoother experience for your players, clients can automatically attempt to reconnect to a game when connection is lost unexpectedly. + +To implement automatic reconnection: +- Define what will trigger the reconnection process and when it will start. + - For example, you can use the `NetworkManager.OnClientDisconnectCallback` callback, or some other unique event depending on your game. +- Ensure the `NetworkManager` properly shuts down before attempting any reconnection. + - You can use the `NetworkManager.ShutdownInProgress` property to manage this. +- Add additional checks to ensure automatic reconnection does not trigger under the wrong conditions. + - Examples + - A client purposefully quits a game + - The server shuts down as expected when the game session ends + - A client gets kicked from a game + - A client is denied during connection approval + +Depending on your game, you may want to add the following features as well: +- Include multiple reconnection attempts in case of failure. You need to define how many attempts these should be, ensure that `NetworkManager` properly shuts down between each attempt, and reset the client's state (if needed). +- Provide an option for players to cancel the reconnection process. This may be useful when there are a lot of reconnection attempts or when each attempt lasts a long duration. + +### Automatic reconnection example + +Check out our [Boss Room sample](../learn/bossroom/getting-started-boss-room.md) for an example implementation of automatic reconnection. + +The entry point for this feature is in [this class](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/ConnectionManagement/ConnectionState/ClientReconnectingState.cs). Boss Room's implementation uses a state inside a state machine that starts a coroutine on entering it (`ReconnectCoroutine`) that attempts to reconnect a few times sequentially, until it either succeeds, surpasses the defined maximum number of attempts, or is cancelled. (See `OnClientConnected`, `OnClientDisconnect`, `OnDisconnectReasonReceived`, and `OnUserRequestedShutdown`) + +The reconnecting state is entered when a client disconnects unexpectedly. (See `OnClientDisconnect` in [this class](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/ConnectionManagement/ConnectionState/ClientConnectedState.cs)) + +:::note +This sample connects with [Lobby](https://docs.unity.com/lobby/unity-lobby-service-overview.html) and [Relay](https://docs.unity.com/relay/get-started.html) services, so the client must make sure it has properly left the lobby before each reconnection attempt. + +For more information about how Boss Room leverages Lobby and Relay, see [Getting Started with Boss Room](../learn/bossroom/getting-started-boss-room.md#register-the-project-with-unity-gaming-services-ugs) +::: diff --git a/versioned_docs/version-1.0.0/advanced-topics/serialization/cprimatives.md b/versioned_docs/version-1.0.0/advanced-topics/serialization/cprimatives.md new file mode 100644 index 000000000..1b98df5d6 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/serialization/cprimatives.md @@ -0,0 +1,19 @@ +--- +id: cprimitives +title: C# Primitives +--- + +C# Primitive types will be serialized by built-in serialization code. These types include `bool`, `char`, `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `long`, `ulong`, `float`, `double`, and `string`. + +```csharp +[ServerRpc] +void FooServerRpc(int somenumber, string sometext) { /* ... */ } + +void Update() +{ + if (Input.GetKeyDown(KeyCode.P)) + { + FooServerRpc(Time.frameCount, "hello, world"); // Client -> Server + } +} +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/advanced-topics/serialization/enum-types.md b/versioned_docs/version-1.0.0/advanced-topics/serialization/enum-types.md new file mode 100644 index 000000000..2d4cb3bc0 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/serialization/enum-types.md @@ -0,0 +1,33 @@ +--- +id: enum_types +title: Enum Types +--- + +A user-defined enum type will be serialized by built-in serialization code (with underlying integer type). + +```csharp +enum SmallEnum : byte +{ + A, + B, + C +} + +enum NormalEnum // default -> int +{ + X, + Y, + Z +} + +[ServerRpc] +void ConfigServerRpc(SmallEnum smallEnum, NormalEnum normalEnum) { /* ... */ } + +void Update() +{ + if (Input.GetKeyDown(KeyCode.P)) + { + ConfigServerRpc(SmallEnum.A, NormalEnum.X); // Client -> Server + } +} +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/advanced-topics/serialization/inetworkserializable.md b/versioned_docs/version-1.0.0/advanced-topics/serialization/inetworkserializable.md new file mode 100644 index 000000000..ddee8297b --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/serialization/inetworkserializable.md @@ -0,0 +1,241 @@ +--- +id: inetworkserializable +title: INetworkSerializable +sidebar_label: INetworkSerializable +--- + +The `INetworkSerializable` interface can be used to define custom serializable types. + +:::caution +All examples provided will work with RPCs and custom messages but some examples will not work with `NetworkVariable` due to the unmanaged type restriction.
+**NetworkVariable Type Litmus Test for INetworkSerializable Implementations:** +- If the implementation itself can be a null (i.e. a class), then it cannot be used +- If it contains any property that can be null (i.e. arrays), then it cannot be used + +The alternative is to create your own `NetworkVariableBase` derived `type` specific class. +::: + +```csharp +struct MyComplexStruct : INetworkSerializable +{ + public Vector3 Position; + public Quaternion Rotation; + + // INetworkSerializable + void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + serializer.SerializeValue(ref Position); + serializer.SerializeValue(ref Rotation); + } + // ~INetworkSerializable +} +``` + +Types implementing `INetworkSerializable` are supported by `NetworkSerializer`, `RPC`s and `NetworkVariable`s. + +```csharp + +[ServerRpc] +void MyServerRpc(MyComplexStruct myStruct) { /* ... */ } + +void Update() +{ + if (Input.GetKeyDown(KeyCode.P)) + { + MyServerRpc( + new MyComplexStruct + { + Position = transform.position, + Rotation = transform.rotation + }); // Client -> Server + } +} +``` + +## Nested serial types + +Nested serial types will be `null` unless you initialize following one of these methods: + +* Manually before calling `SerializeValue` if `serializer.IsReader` (or something like that) +* Initialize in the default constructor + +This is by design. You may see the values as null until properly initialized. The serializer is not deserializing them, the `null` value is simply applied before it can be serialized. + +## Conditional Serialization + +As you have more control over serialization of a struct, you might implement conditional serialization at runtime. + +More advanced use-cases are explored in following examples. + +### Example: Array +:::caution +The below `INetworkSerializable` implementation example works only with RPCs and/or custom messages. The below implementation uses an array within an `INetworkSerializable` implementation. Arrays can be `null` and are not supported by the `NetworkVariable` class. As an alternative, you can write your own `NetworkVariableBase` derived class that does support managed or unmanaged value types.
+[Read More About Custom NetworkVariable Implementations](../../basics/networkvariable.md) +::: + +```csharp +public struct MyCustomStruct : INetworkSerializable +{ + public int[] Array; + + public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + // Length + int length = 0; + if (!serializer.IsReader) + { + length = Array.Length; + } + + serializer.SerializeValue(ref length); + + // Array + if (serializer.IsReader) + { + Array = new int[length]; + } + + for (int n = 0; n < length; ++n) + { + serializer.SerializeValue(ref Array[n]); + } + } +} +``` + +**Reading:** + +- (De)serialize `length` back from the stream +- Iterate over `Array` member `n=length` times +- (De)serialize value back into Array[n] element from the stream + + +**Writing:** + +- Serialize length=Array.Length into stream +- Iterate over Array member n=length times +- Serialize value from Array[n] element into the stream + + +The `BufferSerializer.IsReader` flag is being utilized here to determine whether or not to set `length` value to prepare before writing into the stream — we then use it to determine whether or not to create a new `int[]` instance with `length` size to set `Array` before reading values from the stream. There's also an equivalent but opposite `BufferSerializer.IsWriting` + + +### Example: Move + +```csharp + +public struct MyMoveStruct : INetworkSerializable +{ + public Vector3 Position; + public Quaternion Rotation; + + public bool SyncVelocity; + public Vector3 LinearVelocity; + public Vector3 AngularVelocity; + + void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + // Position & Rotation + serializer.SerializeValue(ref Position); + serializer.SerializeValue(ref Rotation); + + // LinearVelocity & AngularVelocity + serializer.SerializeValue(ref SyncVelocity); + if (SyncVelocity) + { + serializer.SerializeValue(ref LinearVelocity); + serializer.SerializeValue(ref AngularVelocity); + } + } +} +``` + +**Reading:** + +- (De)serialize `Position` back from the stream +- (De)serialize `Rotation` back from the stream +- (De)serialize `SyncVelocity` back from the stream +- Check if `SyncVelocity` is set to true, if so: + - (De)serialize `LinearVelocity` back from the stream + - (De)serialize `AngularVelocity` back from the stream + +**Writing:** + +- Serialize `Position` into the stream +- Serialize `Rotation` into the stream +- Serialize `SyncVelocity` into the stream +- Check if `SyncVelocity` is set to true, if so: + - Serialize `LinearVelocity` into the stream + - Serialize `AngularVelocity` into the stream + +Unlike the [Array](#example-array) example above, in this example we do not use `BufferSerializer.IsReader` flag to change serialization logic but to change the value of a serialized flag itself. + +- If the `SyncVelocity` flag is set to true, both the `LinearVelocity` and `AngularVelocity` will be serialized into the stream +- When the `SyncVelocity` flag is set to `false`, we will leave `LinearVelocity` and `AngularVelocity` with default values. + +## Recursive Nested Serialization + +It is possible to recursively serialize nested members with `INetworkSerializable` interface down in the hierarchy tree. + +Review the following example: + +```csharp + +public struct MyStructA : INetworkSerializable +{ + public Vector3 Position; + public Quaternion Rotation; + + void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + serializer.SerializeValue(ref Position); + serializer.SerializeValue(ref Rotation); + } +} + +public struct MyStructB : INetworkSerializable +{ + public int SomeNumber; + public string SomeText; + public MyStructA StructA; + + void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + serializer.SerializeValue(ref SomeNumber); + serializer.SerializeValue(ref SomeText); + StructA.NetworkSerialize(serializer); + } +} +``` +If we were to serialize `MyStructA` alone, it would serialize `Position` and `Rotation` into the stream using `NetworkSerializer`. + +However, if we were to serialize `MyStructB`, it would serialize `SomeNumber` and `SomeText` into the stream, then serialize `StructA` by calling `MyStructA`'s `void NetworkSerialize(NetworkSerializer)` method, which serializes `Position` and `Rotation` into the same stream. + +:::note +Technically, there is no hard-limit on how many `INetworkSerializable` fields you can serialize down the tree hierarchy. In practice, consider memory and bandwidth boundaries for best performance. +::: + +:::tip +You can conditionally serialize in recursive nested serialization scenario and make use of both features. +::: + +:::caution +While you can have nested `INetworkSerializable` implementations (i.e. an `INetworkSerializable` implementation with `INetworkSerializable` implementations as properties) like demonstrated in the example above, you cannot have derived children of an `INetworkSerializable` implementation.
+**Unsupported Example** +```csharp +/// This is not supported. +public struct MyStructB : MyStructA +{ + public int SomeNumber; + public string SomeText; + + void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + serializer.SerializeValue(ref SomeNumber); + serializer.SerializeValue(ref SomeText); + serializer.SerializeValue(ref Position); + serializer.SerializeValue(ref Rotation); + } +} +``` +::: \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/advanced-topics/serialization/networkobject-serialization.md b/versioned_docs/version-1.0.0/advanced-topics/serialization/networkobject-serialization.md new file mode 100644 index 000000000..921ff57a9 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/serialization/networkobject-serialization.md @@ -0,0 +1,95 @@ +--- +id: networkobject-serialization +title: NetworkObject & NetworkBehaviour +description: Brief explanation on using NetworkObject & NetworkBehaviour in Network for GameObjects +--- + +`GameObjects`, `NetworkObjects` and `NetworkBehaviour` are not serializable types so they cannot be used in `RPCs` or `NetworkVariables` by default. + +There are two convenience wrappers which can be used to send a reference to a `NetworkObject` or a `NetworkBehaviour` over RPCs or `NetworkVariables`. + +## NetworkObjectReference + +`NetworkObjectReference` can be used to serialize a reference to a `NetworkObject`. It can only be used on already spawned `NetworkObjects`. + +Here is an example of using `NetworkObject` reference to send a target `NetworkObject` over an RPC: +```csharp +public class Weapon : NetworkBehaviour +{ + public void ShootTarget(GameObject target) + { + var targetObject = target.GetComponent(); + ShootTargetServerRpc(targetObject); + } + + [ServerRpc] + public void ShootTargetServerRpc(NetworkObjectReference target) + { + if (target.TryGet(out NetworkObject targetObject)) + { + // deal damage or something to target object. + } + else + { + // Target not found on server, likely because it already has been destroyed/despawned. + } + } +} +``` + +### Implicit Operators + +There are also implicit operators which convert from/to `NetworkObject/GameObject` which can be used to simplify code. For instance the above example can also be written in the following way: +```csharp +public class Weapon : NetworkBehaviour +{ + public void ShootTarget(GameObject target) + { + ShootTargetServerRpc(target); + } + + [ServerRpc] + public void ShootTargetServerRpc(NetworkObjectReference target) + { + NetworkObject targetObject = target; + } +} +``` +:::note +The implicit conversion to `NetworkObject` / `GameObject` will result in `Null` if the reference can not be found. +::: + +## NetworkBehaviourReference + +`NetworkBehaviourReference` works similar to `NetworkObjectReference` but is used to reference a specific `NetworkBehaviour` component on a spawned `NetworkObject`. + +```cs +public class Health : NetworkBehaviour +{ + public NetworkVariable Health = new NetworkVariable(); +} + +public class Weapon : NetworkBehaviour +{ + public void ShootTarget(GameObject target) + { + var health = target.GetComponent(); + ShootTargetServerRpc(health, 10); + } + + [ServerRpc] + public void ShootTargetServerRpc(NetworkBehaviourReference health, int damage) + { + if (health.TryGet(out Health healthComponent)) + { + healthComponent.Health.Value -= damage; + } + } +} +``` + +## How NetworkObjectReference & NetworkBehaviourReference work + +`NetworkObjectReference` and `NetworkBehaviourReference` are convenience wrappers which serialize the id of a `NetworkObject` when being sent and on the receiving end retrieve the corresponding ` ` with that id. `NetworkBehaviourReference` sends an additional index which is used to find the right `NetworkBehaviour` on the `NetworkObject`. + +Both of them are structs implementing the `INetworkSerializable` interface. \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/advanced-topics/serialization/serialization-arrays.md b/versioned_docs/version-1.0.0/advanced-topics/serialization/serialization-arrays.md new file mode 100644 index 000000000..a265e0c65 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/serialization/serialization-arrays.md @@ -0,0 +1,44 @@ +--- +id: arrays +title: Arrays +--- + +Arrays of [C# primitive types](cprimatives.md), like `int[]`, and [Unity primitive types](unity-primatives.md), such as `Vector3`, are serialized by built-in serialization code. Otherwise, any array of types that are not handled by the built-in serialization code, such as `string[]`, needs to be handled through a container class or structure that implements the [`INetworkSerializable`](inetworkserializable.md) interface. + +### Built-In Primitive Types Example +Using built-in primitive types is fairly straight forward: +```csharp +[ServerRpc] +void HelloServerRpc(int[] scores, Color[] colors) { /* ... */ } +``` + +### INetworkSerializable Implementation Example +There are many ways to handle sending an array of managed types. +The below example is a simple `string` container class that implements `INetworkSerializable` and can be used as an array of "StringContainers": +```csharp +[ClientRpc] +void SendMessagesClientRpc(StringContainer[] messages) +{ + foreach (var stringContainer in stringContainers) + { + Debug.Log($"{stringContainer.SomeText}"); + } +} + +public class StringContainer : INetworkSerializable +{ + public string SomeText; + public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + if (serializer.IsWriter) + { + serializer.GetFastBufferWriter().WriteValueSafe(SomeText); + } + else + { + serializer.GetFastBufferReader().ReadValueSafe(out SomeText); + } + } +} +``` + diff --git a/versioned_docs/version-1.0.0/advanced-topics/serialization/serialization-intro.md b/versioned_docs/version-1.0.0/advanced-topics/serialization/serialization-intro.md new file mode 100644 index 000000000..271dd10ba --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/serialization/serialization-intro.md @@ -0,0 +1,14 @@ +--- +id: serialization-intro +title: About Serialization +--- +Multiplayer framework has built-in serialization support for C# and Unity primitive types out-of-the-box, also with ability to further extend network serialization for user defined types implementing `INetworkSerializable` interface. + +See the following sections: + +* [C# Primitives](cprimatives.md) +* [Unity Primitives](unity-primatives.md) +* [Enum Types](enum-types.md) +* [Arrays](serialization-arrays.md) +* [INetworkSerializable](inetworkserializable.md) +* [NetworkObjects & NetworkBehaviours](networkobject-serialization.md) diff --git a/versioned_docs/version-1.0.0/advanced-topics/serialization/unity-primatives.md b/versioned_docs/version-1.0.0/advanced-topics/serialization/unity-primatives.md new file mode 100644 index 000000000..acd3d7e3b --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/serialization/unity-primatives.md @@ -0,0 +1,19 @@ +--- +id: unity-primitives +title: Unity Primitives +--- + +Unity Primitive `Color`, `Color32`, `Vector2`, `Vector3`, `Vector4`, `Quaternion`, `Ray`, `Ray2D` types will be serialized by built-in serialization code. + +```csharp +[ClientRpc] +void BarClientRpc(Color somecolor) { /* ... */ } + +void Update() +{ + if (Input.GetKeyDown(KeyCode.P)) + { + BarClientRpc(Color.red); // Server -> Client + } +} +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/advanced-topics/session-management.md b/versioned_docs/version-1.0.0/advanced-topics/session-management.md new file mode 100644 index 000000000..c642fce71 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/session-management.md @@ -0,0 +1,41 @@ +--- +id: session-management +title: Session Management +--- + +You can use session management to ensure that when a player disconnects, some data is kept and accurately assigned back to that player when they reconnect. + +## Linking data to players + +To reassign data to the right player when they reconnect, we need to link this data to the player. + +The **clientId** generated by Netcode for GameObjects (Netcode) cannot be used, because it generates when a player connects and is disposed of when they disconnect. That ID may then be assigned to a different player if they connect to the server after the first one disconnected. + +To properly link data to a specific player, we need an ID that is not tied to the current connection, but persists through time and is unique to that player. Some options include +* A login system with unique player accounts +* A Globally Unique Identifier (GUID). For example, a GUID generated via `System.Guid.NewGuid()` and then saved to the `PlayerPrefs` client side. + +With this unique identifier, we can map each player's data that is needed when reconnecting, such as the current state of their character (last known position, health, etc). We then ensure this data is up to date and kept host side after a player disconnects to properly repopulate that player's data when they reconnect. + +You can also decide to clear all data when a session completes or add a timeout to purge the data after a specific amount of time. + +## Reconnection + +Reconnecting players depends on your game. For example, if we use a [Player Object](../basics/networkobject.md#player-objects), a new `Default Player Prefab` automatically spawns when any player connects to the game (including when they reconnect). You can then use the player's previously saved session data to update that object so that its state returns to what it was before disconnecting. In those cases, we would need to keep all the important data that we want to restore and map it to the player using our identification system. This data could be saved when a player disconnects, or updated periodically. We can then use the `OnNetworkSpawn` event on the Player Object's `NetworkBehavior`(s) to obtain this data and apply it where needed. + +In cases where we don't use the Player Object approach and instead manually attribute client ownership to `NetworkObject`(s), we could keep the objects that a player owns when they disconnect, and set the reconnected player as their new owner. To accomplish this, the only data we would need to keep would be the mapping between those objects and their owning player's identifier, then when a player reconnects we could use this mapping to set them as the new owner. This mapping can be as simple as a dictionary mapping the player identifier with the `NetworkObjectId`(s) of the `NetworkObject`(s) they own. Then, in the `OnClientConnectedCallback` from the `NetworkManager`, the server could set the ownership of these objects. + +## Example using the Player Object approach +Here is an example from the Boss Room sample, showing some simple session management. The game uses the Player Object approach and a GUID to identify unique players. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Packages/com.unity.multiplayer.samples.coop/Utilities/Net/SessionManager.cs +``` + +This class allows BossRoom to handle player session data, represented by a struct `T` implementing the `ISessionPlayerData` interface, by providing mechanisms to initialize, obtain and edit that data, and to associate it to a specific player. It also handles the clearing of data that is no longer used and the reinitialization of data between sessions. + +In this case, since game sessions are quite short, the session data is only cleared for disconnected players when a session ends, or if a player leaves before a session starts. This makes sure that if a player disconnects during a session and then reconnects during the next session, the game properly treats it as a new connection. The definition of when a session ends and when a session starts might vary from game to game, but in BossRoom a session is considered to start after character selection and end when the players win or loose the game and enter the post-game scene. In other cases, one might want to add a timeout to session data and clear it after a specified time instead. + +This code is in Boss Room's utilities package so it can be easily reused. You can add this package via the `Package Manager` window in the Unity Editor by selecting `add from Git URL` and adding the following URL: "https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop.git?path=/Packages/com.unity.multiplayer.samples.coop#main" + +Or you can directly add this line to your `manifest.json` file: "com.unity.multiplayer.samples.coop": "https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop.git?path=/Packages/com.unity.multiplayer.samples.coop#main" diff --git a/versioned_docs/version-1.0.0/advanced-topics/transports.md b/versioned_docs/version-1.0.0/advanced-topics/transports.md new file mode 100644 index 000000000..7db696fe7 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/transports.md @@ -0,0 +1,35 @@ +--- +id: transports +title: Transports +description: A transport collects messages from your application and transmits them safely over the network. It ensures that all packets arrive and in order, if needed. +--- + +Unity Netcode for GameObjects (Netcode) uses Unity Transport by default and supports UNet Transport (deprecated) up to Unity 2022.2 version. + +## So what is a transport layer? + +The transport layer establishes communication between your application and different hosts in a network. + +A transport layer can provide: +* *Connection-oriented communication* to ensure a robust connection before exchanging data with a handshake protocol. +* *Maintain order delivery* for your packets to fix any discrepancies from the network layer in case of packet drops or device interruption. +* *Ensure data integrity* by requesting retransmission of missing or corrupted data through using checksums. +* *Control the data flow* in a network connection to avoid buffer overflow or underflow--causing unnecessary network performance issues. +* *Manage network congestion* by mediating flow rates and node overloads. +* *Adjust data streams* to transmit as byte streams or packets. + +## Unity Transport Package (UTP) + +Netcode's default transport Unity Transport (UTP) is an entire transport layer that you can use to add multiplayer and network features to your project with or without Netcode. See the Transport [documentation](../../../transport/current/about) for more information and how to [install](../../../transport/current/install). + +## Unity’s UNet Transport Layer API + +UNet is a deprecated solution that is no longer supported after Unity 2022.2. Unity Transport Package (UTP) is the default transport for Netcode for GameObjects. We recommend transitioning to UTP as soon as possible. + +### Community Transports or Writing Your Own + +You can use any of the community contributed custom transport implementations or write your own. + +The community transports are interchangeable transport layers for Netcode and can be installed with the Unity Package Manager. After installation, the transport package will appear in the **Select Transport** dropdown of the `NetworkManager`. Check out the [Netcode community contributed transports](https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/Transports) for more information. + +To start writing your own and contributing to the community, check out the [Netcode community contribution repository](https://github.com/Unity-Technologies/multiplayer-community-contributions) for starting points and how to add your content. diff --git a/versioned_docs/version-1.0.0/advanced-topics/ways-to-synchronize.md b/versioned_docs/version-1.0.0/advanced-topics/ways-to-synchronize.md new file mode 100644 index 000000000..e497592d9 --- /dev/null +++ b/versioned_docs/version-1.0.0/advanced-topics/ways-to-synchronize.md @@ -0,0 +1,38 @@ +--- +id: ways-synchronize +title: Synchronizing States & Events +--- + +## Introduction +Netcode for GameObjects (Netcode) includes three options for synchronizing game states and/or events: +- Messaging System + - Remote Procedure Calls (RPCs) + - Custom Messages +- NetworkVariables + - Handled by the "internal" messaging system and [categorized under "Networking".](../basics/networkvariable.md) + +While each of the above options can be used for the same thing, synchronizing states or events, they all have specific use cases and limitations. + +## Messaging System +The Netcode messaging system provides you with the ability to handle sending and receiving messages or events. The entire messaging system supports the serialization of most primitive value `type`s as well as any classes and/or structures that implement the `INetworkSerializable` interface. + +### Remote Procedure Calls +RPCs can be viewed as a way to send an event notification as well as a way to handle direct communication between a server and a client (or vice versa). This is sometimes useful when the ownership scope of the `NetworkBehavior`, that the remote procedure call is declared within, belongs to the server but you still want one or more clients to be able to communicate with the associated `NetworkObject`. +**Some Usage Examples:** +- A ServerRpc could be used by a client to notify the server that the player is trying to use a world object (i.e. a door, a vehicle, etc.) +- A ClientRpc could be used by a server to notify a specific client of a special reconnection key or some other player specific information that doesn't require its state to be synchronized with all current and any future late joining client(s). + +**The are two types of RPC methods:** +- **ServerRpc:** A client invoked remote procedure call received by and executed on the server-side. + - [Read More About ServerRpc](../advanced-topics/message-system/serverrpc.md) +- **ClientRpc:** A server invoked remote procedure call received by and executed on one or more clients. + - [Read More About ClientRpc](../advanced-topics/message-system/clientrpc.md) + +### Custom Messages +Custom messages provide you with the ability to create your own "netcode message type" to handle scenarios where you might just need to create your own custom message. +[Read More About Custom Messages](../advanced-topics/message-system/custom-messages.md) + +## NetworkVariable System +A NetworkVariable is most commonly used to synchronize state between both connected and late joining clients. The `NetworkVariable` system only supports non-nullable value `type`s, but also provides support for `INetworkSerializable` implementations as well you can create your own `NetworkVariable` class by deriving from the `NetworkVariableBase` abstract class. If you want something to always be synchronized with current and late-joining clients, then it is likely a good `NetworkVariable` candidate. + +[Read More About NetworkVariable](../basics/networkvariable.md) diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.Arithmetic.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.Arithmetic.md new file mode 100644 index 000000000..3780e6a0d --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.Arithmetic.md @@ -0,0 +1,187 @@ +--- +id: Unity.Netcode.Arithmetic +title: Unity.Netcode.Arithmetic +--- + +# Class Arithmetic + + +Arithmetic helper class + + + + + + + +##### Inheritance + + +System.Object + + + + +Arithmetic + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public static class Arithmetic +``` + + + +### Methods + +#### VarIntSize(UInt64) + + +Gets the output size in bytes after VarInting a unsigned integer + + + + + + +##### Declaration + + +``` lang-csharp +public static int VarIntSize(ulong value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|-------|------------------------------------------| +| System.UInt64 | value | The unsigned integer whose length to get | + +##### Returns + +| Type | Description | +|--------------|---------------------| +| System.Int32 | The amount of bytes | + +#### ZigZagDecode(UInt64) + + +Decides a ZigZag encoded integer back to a signed integer + + + + + + +##### Declaration + + +``` lang-csharp +public static long ZigZagDecode(ulong value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|-------|----------------------| +| System.UInt64 | value | The unsigned integer | + +##### Returns + +| Type | Description | +|--------------|-----------------------------------| +| System.Int64 | The signed version of the integer | + +#### ZigZagEncode(Int64) + + +ZigZag encodes a signed integer and maps it to a unsigned integer + + + + + + +##### Declaration + + +``` lang-csharp +public static ulong ZigZagEncode(long value) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------|------------------------------| +| System.Int64 | value | The signed integer to encode | + +##### Returns + +| Type | Description | +|---------------|-----------------------------------------| +| System.UInt64 | A ZigZag encoded version of the integer | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.BitCounter.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.BitCounter.md new file mode 100644 index 000000000..a7d1fa7a6 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.BitCounter.md @@ -0,0 +1,219 @@ +--- +id: Unity.Netcode.BitCounter +title: Unity.Netcode.BitCounter +--- + +# Class BitCounter + + +Utility class to count the number of bytes or bits needed to serialize a +value. + + + + + + + +##### Inheritance + + +System.Object + + + + +BitCounter + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public static class BitCounter +``` + + + +### Methods + +#### GetUsedBitCount(UInt32) + + +Get the minimum number of bits required to represent the given value + + + + + + +##### Declaration + + +``` lang-csharp +public static int GetUsedBitCount(uint value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|-------|-------------| +| System.UInt32 | value | The value | + +##### Returns + +| Type | Description | +|--------------|-----------------------------| +| System.Int32 | The number of bits required | + +#### GetUsedBitCount(UInt64) + + +Get the minimum number of bits required to represent the given value + + + + + + +##### Declaration + + +``` lang-csharp +public static int GetUsedBitCount(ulong value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|-------|-------------| +| System.UInt64 | value | The value | + +##### Returns + +| Type | Description | +|--------------|-----------------------------| +| System.Int32 | The number of bits required | + +#### GetUsedByteCount(UInt32) + + +Get the minimum number of bytes required to represent the given value + + + + + + +##### Declaration + + +``` lang-csharp +public static int GetUsedByteCount(uint value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|-------|-------------| +| System.UInt32 | value | The value | + +##### Returns + +| Type | Description | +|--------------|------------------------------| +| System.Int32 | The number of bytes required | + +#### GetUsedByteCount(UInt64) + + +Get the minimum number of bytes required to represent the given value + + + + + + +##### Declaration + + +``` lang-csharp +public static int GetUsedByteCount(ulong value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|-------|-------------| +| System.UInt64 | value | The value | + +##### Returns + +| Type | Description | +|--------------|------------------------------| +| System.Int32 | The number of bytes required | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.BitReader.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.BitReader.md new file mode 100644 index 000000000..3773af45f --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.BitReader.md @@ -0,0 +1,235 @@ +--- +id: Unity.Netcode.BitReader +title: Unity.Netcode.BitReader +--- + +# Struct BitReader + + +Helper class for doing bitwise reads for a FastBufferReader. Ensures all +bitwise reads end on proper byte alignment so FastBufferReader doesn't +have to be concerned with misaligned reads. + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public ref struct BitReader +``` + + + +### Properties + +#### BitAligned + + +Whether or not the current BitPosition is evenly divisible by 8. I.e. +whether or not the BitPosition is at a byte boundary. + + + + + + +##### Declaration + + +``` lang-csharp +public readonly bool BitAligned { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +### Methods + +#### Dispose() + + +Pads the read bit count to byte alignment and commits the read back to +the reader + + + + + + +##### Declaration + + +``` lang-csharp +public void Dispose() +``` + + + +#### ReadBit(out Boolean) + + +Read a single bit from the buffer + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadBit(out bool bit) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|------|-------------------------------------------------------------| +| System.Boolean | bit | Out value of the bit. True represents 1, False represents 0 | + +#### ReadBits(out Byte, UInt32) + + +Read bits from stream. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadBits(out byte value, uint bitCount) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|---------------------------| +| System.Byte | value | Value to store bits into. | +| System.UInt32 | bitCount | Amount of bits to read. | + +#### ReadBits(out UInt64, UInt32) + + +Read a certain amount of bits from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadBits(out ulong value, uint bitCount) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|---------------------------| +| System.UInt64 | value | Value to store bits into. | +| System.UInt32 | bitCount | Amount of bits to read | + +#### TryBeginReadBits(UInt32) + + +Verifies the requested bit count can be read from the buffer. This +exists as a separate method to allow multiple bit reads to be bounds +checked with a single call. If it returns false, you may not read, and +in editor and development builds, attempting to do so will throw an +exception. In release builds, attempting to do so will read junk memory. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TryBeginReadBits(uint bitCount) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|-------------------------------------------| +| System.UInt32 | bitCount | Number of bits you want to read, in total | + +##### Returns + +| Type | Description | +|----------------|----------------------------------------------------------------| +| System.Boolean | True if you can read, false if that would exceed buffer bounds | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.BitWriter.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.BitWriter.md new file mode 100644 index 000000000..4156edcf0 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.BitWriter.md @@ -0,0 +1,243 @@ +--- +id: Unity.Netcode.BitWriter +title: Unity.Netcode.BitWriter +--- + +# Struct BitWriter + + +Helper class for doing bitwise writes for a FastBufferWriter. Ensures +all bitwise writes end on proper byte alignment so FastBufferWriter +doesn't have to be concerned with misaligned writes. + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public ref struct BitWriter +``` + + + +### Properties + +#### BitAligned + + +Whether or not the current BitPosition is evenly divisible by 8. I.e. +whether or not the BitPosition is at a byte boundary. + + + + + + +##### Declaration + + +``` lang-csharp +public readonly bool BitAligned { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +### Methods + +#### Dispose() + + +Pads the written bit count to byte alignment and commits the write back +to the writer + + + + + + +##### Declaration + + +``` lang-csharp +public void Dispose() +``` + + + +#### TryBeginWriteBits(Int32) + + +Allows faster serialization by batching bounds checking. When you know +you will be writing multiple fields back-to-back and you know the total +size, you can call TryBeginWriteBits() once on the total size, and then +follow it with calls to WriteBit() or WriteBits(). + +Bitwise write operations will throw OverflowException in editor and +development builds if you go past the point you've marked using +TryBeginWriteBits(). In release builds, OverflowException will not be +thrown for performance reasons, since the point of using TryBeginWrite +is to avoid bounds checking in the following operations in release +builds. Instead, attempting to write past the marked position in release +builds will write to random memory and cause undefined behavior, likely +including instability and crashes. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TryBeginWriteBits(int bitCount) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|----------|--------------------------------------------| +| System.Int32 | bitCount | Number of bits you want to write, in total | + +##### Returns + +| Type | Description | +|----------------|-----------------------------------------------------------------| +| System.Boolean | True if you can write, false if that would exceed buffer bounds | + +#### WriteBit(Boolean) + + +Write a single bit to the buffer + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteBit(bool bit) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|------|---------------------------------------------------------| +| System.Boolean | bit | Value of the bit. True represents 1, False represents 0 | + +#### WriteBits(Byte, UInt32) + + +Write bits to stream. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteBits(byte value, uint bitCount) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|--------------------------| +| System.Byte | value | Value to get bits from. | +| System.UInt32 | bitCount | Amount of bits to write. | + +#### WriteBits(UInt64, UInt32) + + +Write s certain amount of bits to the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteBits(ulong value, uint bitCount) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|-------------------------| +| System.UInt64 | value | Value to get bits from. | +| System.UInt32 | bitCount | Amount of bits to write | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.BufferSerializer-1.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.BufferSerializer-1.md new file mode 100644 index 000000000..1d02aa91c --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.BufferSerializer-1.md @@ -0,0 +1,2026 @@ +--- +id: Unity.Netcode.BufferSerializer-1 +title: Unity.Netcode.BufferSerializer-1 +--- + +# Struct BufferSerializer\ + + +Two-way serializer wrapping FastBufferReader or FastBufferWriter. + +Implemented as a ref struct for two reasons: + +1. The BufferSerializer cannot outlive the FBR/FBW it wraps or using it + will cause a crash +2. The BufferSerializer must always be passed by reference and can't be + copied + +Ref structs help enforce both of those rules: they can't ref live the +stack context in which they were created, and they're always passed by +reference no matter what. + +BufferSerializer doesn't wrapp FastBufferReader or FastBufferWriter +directly because it can't. ref structs can't implement interfaces, and +in order to be able to have two different implementations with the same +interface (which allows us to avoid an "if(IsReader)" on every call), +the thing directly wrapping the struct has to implement an interface. So +IReaderWriter exists as the interface, which is implemented by a normal +struct, while the ref struct wraps the normal one to enforce the two +above requirements. (Allowing direct access to the IReaderWriter struct +would allow dangerous things to happen because the struct's lifetime +could outlive the Reader/Writer's.) + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public ref struct BufferSerializer + where TReaderWriter : IReaderWriter +``` + + + +##### Type Parameters + +| Name | Description | +|---------------|---------------------------| +| TReaderWriter | The implementation struct | + +### Properties + +#### IsReader + + +Check if the contained implementation is a reader + + + + + + +##### Declaration + + +``` lang-csharp +public readonly bool IsReader { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsWriter + + +Check if the contained implementation is a writer + + + + + + +##### Declaration + + +``` lang-csharp +public readonly bool IsWriter { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +### Methods + +#### GetFastBufferReader() + + +Retrieves the FastBufferReader instance. Only valid if IsReader = true, +throws InvalidOperationException otherwise. + + + + + + +##### Declaration + + +``` lang-csharp +public FastBufferReader GetFastBufferReader() +``` + + + +##### Returns + +| Type | Description | +|------------------|-----------------| +| FastBufferReader | Reader instance | + +#### GetFastBufferWriter() + + +Retrieves the FastBufferWriter instance. Only valid if IsWriter = true, +throws InvalidOperationException otherwise. + + + + + + +##### Declaration + + +``` lang-csharp +public FastBufferWriter GetFastBufferWriter() +``` + + + +##### Returns + +| Type | Description | +|------------------|-----------------| +| FastBufferWriter | Writer instance | + +#### PreCheck(Int32) + + +Performs an advance check to ensure space is available to read/write one +or more values. This provides a performance benefit for serializing +multiple values using the SerializeValuePreChecked methods. But note +that the benefit is small and only likely to be noticeable if +serializing a very large number of items. + + + + + + +##### Declaration + + +``` lang-csharp +public bool PreCheck(int amount) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|--------|-------------| +| System.Int32 | amount | | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### SerializeNetworkSerializable\(ref T) + + +Read or write a NetworkSerializable value. SerializeValue() is the +preferred method to do this - this is provided for backward +compatibility only. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeNetworkSerializable(ref T value) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|--------------------------| +| T | value | The values to read/write | + +##### Type Parameters + +| Name | Description | +|------|-------------------------------| +| T | The network serializable type | + +#### SerializeValue(ref Color) + + +Read or write a Color value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Color value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------------| +| Color | value | The value to read/write | + +#### SerializeValue(ref Color\[\]) + + +Read or write an array of Color values + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Color[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|--------------------------| +| Color\[\] | value | The values to read/write | + +#### SerializeValue(ref Color32) + + +Read or write a Color32 value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Color32 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Color32 | value | The value to read/write | + +#### SerializeValue(ref Color32\[\]) + + +Read or write an array of Color32 values + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Color32[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Color32\[\] | value | The values to read/write | + +#### SerializeValue(ref Quaternion) + + +Read or write a Quaternion value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Quaternion value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Quaternion | value | The value to read/write | + +#### SerializeValue(ref Quaternion\[\]) + + +Read or write an array of Quaternion values + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Quaternion[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------------| +| Quaternion\[\] | value | The values to read/write | + +#### SerializeValue(ref Ray) + + +Read or write a Ray value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Ray value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|-------------------------| +| Ray | value | The value to read/write | + +#### SerializeValue(ref Ray\[\]) + + +Read or write an array of Ray values + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Ray[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------------| +| Ray\[\] | value | The values to read/write | + +#### SerializeValue(ref Ray2D) + + +Read or write a Ray2D value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Ray2D value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------------| +| Ray2D | value | The value to read/write | + +#### SerializeValue(ref Ray2D\[\]) + + +Read or write an array of Ray2D values + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Ray2D[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|--------------------------| +| Ray2D\[\] | value | The values to read/write | + +#### SerializeValue(ref Byte) + + +Read or write a single byte + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref byte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|-------------------------| +| System.Byte | value | The value to read/write | + +#### SerializeValue(ref String, Boolean) + + +Read or write a string + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref string s, bool oneByteChars = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------|------------------------------------------------------------------| +| System.String | s | The value to read/write | +| System.Boolean | oneByteChars | If true, characters will be limited to one-byte ASCII characters | + +#### SerializeValue(ref Vector2) + + +Read or write a Vector2 value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Vector2 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector2 | value | The value to read/write | + +#### SerializeValue(ref Vector2\[\]) + + +Read or write an array of Vector2 values + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Vector2[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Vector2\[\] | value | The values to read/write | + +#### SerializeValue(ref Vector2Int) + + +Read or write a Vector2Int value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Vector2Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Vector2Int | value | The value to read/write | + +#### SerializeValue(ref Vector2Int\[\]) + + +Read or write an array of Vector2Int values + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Vector2Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------------| +| Vector2Int\[\] | value | The values to read/write | + +#### SerializeValue(ref Vector3) + + +Read or write a Vector3 value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Vector3 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector3 | value | The value to read/write | + +#### SerializeValue(ref Vector3\[\]) + + +Read or write an array of Vector3 values + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Vector3[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Vector3\[\] | value | The values to read/write | + +#### SerializeValue(ref Vector3Int) + + +Read or write a Vector3Int value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Vector3Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Vector3Int | value | The value to read/write | + +#### SerializeValue(ref Vector3Int\[\]) + + +Read or write an array of Vector3Int values + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Vector3Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------------| +| Vector3Int\[\] | value | The values to read/write | + +#### SerializeValue(ref Vector4) + + +Read or write a Vector4 value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Vector4 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector4 | value | The value to read/write | + +#### SerializeValue(ref Vector4\[\]) + + +Read or write an array of Vector4 values + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref Vector4[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Vector4\[\] | value | The values to read/write | + +#### SerializeValue\(ref T, FastBufferWriter.ForEnums) + + +Read or write an enum value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref T value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T, FastBufferWriter.ForFixedStrings) + + +Read or write a FixedString value + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref T value, FastBufferWriter.ForFixedStrings unused = default(FastBufferWriter.ForFixedStrings)) + where T : struct, INativeList, IUTF8Bytes +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------------------|--------|---------------------------------------------------------------------------| +| T | value | The values to read/write | +| FastBufferWriter.ForFixedStrings | unused | An unused parameter used for enabling overload resolution of FixedStrings | + +##### Type Parameters + +| Name | Description | +|------|-------------------------------| +| T | The network serializable type | + +#### SerializeValue\(ref T, FastBufferWriter.ForNetworkSerializable) + + +Read or write a struct or class value implementing INetworkSerializable + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref T value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T, FastBufferWriter.ForPrimitives) + + +Read or write a primitive value (int, bool, etc) Accepts any value that +implements the given interfaces, but is not guaranteed to work correctly +on values that are not primitives. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref T value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T, FastBufferWriter.ForStructs) + + +Read or write a struct value implementing ISerializeByMemcpy + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref T value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T\[\], FastBufferWriter.ForEnums) + + +Read or write an array of enum values + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref T[] value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The value to read/write | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T\[\], FastBufferWriter.ForNetworkSerializable) + + +Read or write an array of struct or class values implementing +INetworkSerializable + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref T[] value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T\[\], FastBufferWriter.ForPrimitives) + + +Read or write an array of primitive values (int, bool, etc) Accepts any +value that implements the given interfaces, but is not guaranteed to +work correctly on values that are not primitives. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref T[] value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T\[\], FastBufferWriter.ForStructs) + + +Read or write an array of struct values implementing ISerializeByMemcpy + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValue(ref T[] value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValuePreChecked(ref Color) + + +Serialize a Color, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Color value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------------| +| Color | value | The value to read/write | + +#### SerializeValuePreChecked(ref Color\[\]) + + +Serialize a Color array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Color[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|-------------------------| +| Color\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Color32) + + +Serialize a Color32, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Color32 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Color32 | value | The value to read/write | + +#### SerializeValuePreChecked(ref Color32\[\]) + + +Serialize a Color32 array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Color32[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|-------------------------| +| Color32\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Quaternion) + + +Serialize a Quaternion, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Quaternion value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Quaternion | value | The value to read/write | + +#### SerializeValuePreChecked(ref Quaternion\[\]) + + +Serialize a Quaternion array, "pre-checked", which skips buffer checks. +In debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Quaternion[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|-------------------------| +| Quaternion\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Ray) + + +Serialize a Ray, "pre-checked", which skips buffer checks. In debug and +editor builds, a check is made to ensure you've called "PreCheck" before +calling this. In release builds, calling this without calling "PreCheck" +may read or write past the end of the buffer, which will cause memory +corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Ray value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|-------------------------| +| Ray | value | The value to read/write | + +#### SerializeValuePreChecked(ref Ray\[\]) + + +Serialize a Ray array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Ray[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Ray\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Ray2D) + + +Serialize a Ray2D, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Ray2D value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------------| +| Ray2D | value | The value to read/write | + +#### SerializeValuePreChecked(ref Ray2D\[\]) + + +Serialize a Ray2D array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Ray2D[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|-------------------------| +| Ray2D\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Byte) + + +Serialize a byte, "pre-checked", which skips buffer checks. In debug and +editor builds, a check is made to ensure you've called "PreCheck" before +calling this. In release builds, calling this without calling "PreCheck" +may read or write past the end of the buffer, which will cause memory +corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref byte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|-------------------------| +| System.Byte | value | The value to read/write | + +#### SerializeValuePreChecked(ref String, Boolean) + + +Serialize a string, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref string s, bool oneByteChars = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------|------------------------------------------------------------------| +| System.String | s | The value to read/write | +| System.Boolean | oneByteChars | If true, characters will be limited to one-byte ASCII characters | + +#### SerializeValuePreChecked(ref Vector2) + + +Serialize a Vector2, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Vector2 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector2 | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector2\[\]) + + +Serialize a Vector2 array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Vector2[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Vector2\[\] | value | The values to read/write | + +#### SerializeValuePreChecked(ref Vector2Int) + + +Serialize a Vector2Int, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Vector2Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Vector2Int | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector2Int\[\]) + + +Serialize a Vector2Int array, "pre-checked", which skips buffer checks. +In debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Vector2Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------------| +| Vector2Int\[\] | value | The values to read/write | + +#### SerializeValuePreChecked(ref Vector3) + + +Serialize a Vector3, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Vector3 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector3 | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector3\[\]) + + +Serialize a Vector3 array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Vector3[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Vector3\[\] | value | The values to read/write | + +#### SerializeValuePreChecked(ref Vector3Int) + + +Serialize a Vector3Int, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Vector3Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Vector3Int | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector3Int\[\]) + + +Serialize a Vector3Int array, "pre-checked", which skips buffer checks. +In debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Vector3Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|-------------------------| +| Vector3Int\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector4) + + +Serialize a Vector4, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Vector4 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector4 | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector4\[\]) + + +Serialize a Vector4Array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref Vector4[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|-------------------------| +| Vector4\[\] | value | The value to read/write | + +#### SerializeValuePreChecked\(ref T, FastBufferWriter.ForEnums) + + +Serialize an enum, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref T value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|--------------------------------------------------------------------| +| T | value | The values to read/write | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution of enums | + +##### Type Parameters + +| Name | Description | +|------|-------------------------------| +| T | The network serializable type | + +#### SerializeValuePreChecked\(ref T, FastBufferWriter.ForFixedStrings) + + +Serialize a FixedString, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref T value, FastBufferWriter.ForFixedStrings unused = default(FastBufferWriter.ForFixedStrings)) + where T : struct, INativeList, IUTF8Bytes +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------------------|--------|-----------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForFixedStrings | unused | An unused parameter that can be used for enabling overload resolution for fixed strings | + +##### Type Parameters + +| Name | Description | +|------|-------------------------------| +| T | The network serializable type | + +#### SerializeValuePreChecked\(ref T, FastBufferWriter.ForPrimitives) + + +Serialize a primitive, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref T value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|-------------------------------| +| T | The network serializable type | + +#### SerializeValuePreChecked\(ref T, FastBufferWriter.ForStructs) + + +Serialize a struct, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref T value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------| +| T | value | The values to read/write | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution of structs | + +##### Type Parameters + +| Name | Description | +|------|-------------------------------| +| T | The network serializable type | + +#### SerializeValuePreChecked\(ref T\[\], FastBufferWriter.ForEnums) + + +Serialize an array of enums, "pre-checked", which skips buffer checks. +In debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref T[] value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|--------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution of enums | + +##### Type Parameters + +| Name | Description | +|------|--------------------------------------------| +| T | The network serializable types in an array | + +#### SerializeValuePreChecked\(ref T\[\], FastBufferWriter.ForPrimitives) + + +Serialize an array of primitives, "pre-checked", which skips buffer +checks. In debug and editor builds, a check is made to ensure you've +called "PreCheck" before calling this. In release builds, calling this +without calling "PreCheck" may read or write past the end of the buffer, +which will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref T[] value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|-------------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution of primitives | + +##### Type Parameters + +| Name | Description | +|------|--------------------------------------------| +| T | The network serializable types in an array | + +#### SerializeValuePreChecked\(ref T\[\], FastBufferWriter.ForStructs) + + +Serialize an array of structs, "pre-checked", which skips buffer checks. +In debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +public void SerializeValuePreChecked(ref T[] value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution of structs | + +##### Type Parameters + +| Name | Description | +|------|--------------------------------------------| +| T | The network serializable types in an array | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.BytePacker.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.BytePacker.md new file mode 100644 index 000000000..393162779 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.BytePacker.md @@ -0,0 +1,1110 @@ +--- +id: Unity.Netcode.BytePacker +title: Unity.Netcode.BytePacker +--- + +# Class BytePacker + + +Utility class for packing values in serialization. ByteUnpacker to +unpack packed values. + + + + + + + +##### Inheritance + + +System.Object + + + + +BytePacker + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public static class BytePacker +``` + + + +### Fields + +#### BitPackedIntMax + + +Maximum serializable value for a BitPacked int + + + + + + +##### Declaration + + +``` lang-csharp +public const int BitPackedIntMax = 536870911 +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### BitPackedIntMin + + +Minimum serializable value size for a BitPacked int + + + + + + +##### Declaration + + +``` lang-csharp +public const int BitPackedIntMin = -536870912 +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### BitPackedLongMax + + +Maximum serializable value for a BitPacked long + + + + + + +##### Declaration + + +``` lang-csharp +public const long BitPackedLongMax = 1152921504606846975L +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int64 | | + +#### BitPackedLongMin + + +Minimum serializable value size for a BitPacked long + + + + + + +##### Declaration + + +``` lang-csharp +public const long BitPackedLongMin = -1152921504606846976L +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int64 | | + +#### BitPackedShortMax + + +Maximum serializable value for a BitPacked short + + + + + + +##### Declaration + + +``` lang-csharp +public const short BitPackedShortMax = 16383 +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int16 | | + +#### BitPackedShortMin + + +Minimum serializable value size for a BitPacked ushort + + + + + + +##### Declaration + + +``` lang-csharp +public const short BitPackedShortMin = -16384 +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int16 | | + +#### BitPackedUintMax + + +Maximum serializable value for a BitPacked uint (minimum for unsigned is +0) + + + + + + +##### Declaration + + +``` lang-csharp +public const uint BitPackedUintMax = 1073741823U +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt32 | | + +#### BitPackedULongMax + + +Maximum serializable value for a BitPacked ulong (minimum for unsigned +is 0) + + + + + + +##### Declaration + + +``` lang-csharp +public const ulong BitPackedULongMax = 2305843009213693951UL +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +#### BitPackedUshortMax + + +Maximum serializable value for a BitPacked ushort (minimum for unsigned +is 0) + + + + + + +##### Declaration + + +``` lang-csharp +public const ushort BitPackedUshortMax = 32767 +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt16 | | + +### Methods + +#### WriteValueBitPacked(FastBufferWriter, Int16) + + +Writes a 14-bit signed short to the buffer in a bit-encoded packed +format. The first bit indicates whether the value is 1 byte or 2. The +sign bit takes up another bit. That leaves 14 bits for the value. A +value greater than 2^14-1 or less than -2^14 will throw an exception in +editor and development builds. In release builds builds the exception is +not thrown and the value is truncated by losing its two most significant +bits after zig-zag encoding. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValueBitPacked(FastBufferWriter writer, short value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.Int16 | value | The value to pack | + +#### WriteValueBitPacked(FastBufferWriter, Int32) + + +Writes a 29-bit signed int to the buffer in a bit-encoded packed format. +The first two bits indicate whether the value is 1, 2, 3, or 4 bytes. +The sign bit takes up another bit. That leaves 29 bits for the value. A +value greater than 2^29-1 or less than -2^29 will throw an exception in +editor and development builds. In release builds builds the exception is +not thrown and the value is truncated by losing its three most +significant bits after zig-zag encoding. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValueBitPacked(FastBufferWriter writer, int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.Int32 | value | The value to pack | + +#### WriteValueBitPacked(FastBufferWriter, Int64) + + +Writes a 60-bit signed long to the buffer in a bit-encoded packed +format. The first three bits indicate whether the value is 1, 2, 3, 4, +5, 6, 7, or 8 bytes. The sign bit takes up another bit. That leaves 60 +bits for the value. A value greater than 2^60-1 or less than -2^60 will +throw an exception in editor and development builds. In release builds +builds the exception is not thrown and the value is truncated by losing +its four most significant bits after zig-zag encoding. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValueBitPacked(FastBufferWriter writer, long value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.Int64 | value | The value to pack | + +#### WriteValueBitPacked(FastBufferWriter, UInt16) + + +Writes a 15-bit unsigned short to the buffer in a bit-encoded packed +format. The first bit indicates whether the value is 1 byte or 2. That +leaves 15 bits for the value. A value greater than 2^15-1 will throw an +exception in editor and development builds. In release builds builds the +exception is not thrown and the value is truncated by losing its most +significant bit. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValueBitPacked(FastBufferWriter writer, ushort value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.UInt16 | value | The value to pack | + +#### WriteValueBitPacked(FastBufferWriter, UInt32) + + +Writes a 30-bit unsigned int to the buffer in a bit-encoded packed +format. The first two bits indicate whether the value is 1, 2, 3, or 4 +bytes. That leaves 30 bits for the value. A value greater than 2^30-1 +will throw an exception in editor and development builds. In release +builds builds the exception is not thrown and the value is truncated by +losing its two most significant bits. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValueBitPacked(FastBufferWriter writer, uint value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.UInt32 | value | The value to pack | + +#### WriteValueBitPacked(FastBufferWriter, UInt64) + + +Writes a 61-bit unsigned long to the buffer in a bit-encoded packed +format. The first three bits indicate whether the value is 1, 2, 3, 4, +5, 6, 7, or 8 bytes. That leaves 31 bits for the value. A value greater +than 2^61-1 will throw an exception in editor and development builds. In +release builds builds the exception is not thrown and the value is +truncated by losing its three most significant bits. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValueBitPacked(FastBufferWriter writer, ulong value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.UInt64 | value | The value to pack | + +#### WriteValuePacked(FastBufferWriter, Color) + + +Convenience method that writes four varint floats from the color to the +buffer + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, Color color) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| Color | color | Color to write | + +#### WriteValuePacked(FastBufferWriter, Color32) + + +Convenience method that writes four varint floats from the color to the +buffer + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, Color32 color) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| Color32 | color | Color to write | + +#### WriteValuePacked(FastBufferWriter, Quaternion) + + +Writes the rotation to the buffer. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, Quaternion rotation) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|----------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| Quaternion | rotation | Rotation to write | + +#### WriteValuePacked(FastBufferWriter, Ray) + + +Convenience method that writes two packed Vector3 from the ray to the +buffer + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, Ray ray) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| Ray | ray | Ray to write | + +#### WriteValuePacked(FastBufferWriter, Ray2D) + + +Convenience method that writes two packed Vector2 from the ray to the +buffer + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, Ray2D ray2d) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| Ray2D | ray2d | Ray2D to write | + +#### WriteValuePacked(FastBufferWriter, Boolean) + + +Write a bool to the buffer. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, bool value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.Boolean | value | Value to write | + +#### WriteValuePacked(FastBufferWriter, Byte) + + +Write a byte to the buffer. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, byte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.Byte | value | Value to write | + +#### WriteValuePacked(FastBufferWriter, Char) + + +Write a two-byte character as a varint to the buffer. WARNING: If the +value you're writing is \> 2287, this will use MORE space (3 bytes +instead of 2), and if your value is \> 240 you'll get no savings at all. +Only use this if you're certain your value will be small. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, char c) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.Char | c | Value to write | + +#### WriteValuePacked(FastBufferWriter, Double) + + +Write double-precision floating point value to the buffer as a varint + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, double value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.Double | value | Value to write | + +#### WriteValuePacked(FastBufferWriter, Int16) + + +Write a signed short (Int16) as a ZigZag encoded varint to the buffer. +WARNING: If the value you're writing is \> 2287, this will use MORE +space (3 bytes instead of 2), and if your value is \> 240 you'll get no +savings at all. Only use this if you're certain your value will be +small. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, short value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.Int16 | value | Value to write | + +#### WriteValuePacked(FastBufferWriter, Int32) + + +Write a signed int (Int32) as a ZigZag encoded varint to the buffer. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.Int32 | value | Value to write | + +#### WriteValuePacked(FastBufferWriter, Int64) + + +Write a signed long (Int64) as a ZigZag encoded varint to the buffer. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, long value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.Int64 | value | Value to write | + +#### WriteValuePacked(FastBufferWriter, SByte) + + +Write a signed byte to the buffer. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, sbyte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.SByte | value | Value to write | + +#### WriteValuePacked(FastBufferWriter, Single) + + +Write single-precision floating point value to the buffer as a varint + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, float value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.Single | value | Value to write | + +#### WriteValuePacked(FastBufferWriter, String) + + +Writes a string in a packed format + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, string s) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.String | s | The value to pack | + +#### WriteValuePacked(FastBufferWriter, UInt16) + + +Write an unsigned short (UInt16) as a varint to the buffer. WARNING: If +the value you're writing is \> 2287, this will use MORE space (3 bytes +instead of 2), and if your value is \> 240 you'll get no savings at all. +Only use this if you're certain your value will be small. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, ushort value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.UInt16 | value | Value to write | + +#### WriteValuePacked(FastBufferWriter, UInt32) + + +Write an unsigned int (UInt32) to the buffer. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, uint value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.UInt32 | value | Value to write | + +#### WriteValuePacked(FastBufferWriter, UInt64) + + +Write an unsigned long (UInt64) to the buffer. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, ulong value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| System.UInt64 | value | Value to write | + +#### WriteValuePacked(FastBufferWriter, Vector2) + + +Convenience method that writes two varint floats from the vector to the +buffer + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, Vector2 vector2) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|---------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| Vector2 | vector2 | Vector to write | + +#### WriteValuePacked(FastBufferWriter, Vector3) + + +Convenience method that writes three varint floats from the vector to +the buffer + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, Vector3 vector3) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|---------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| Vector3 | vector3 | Vector to write | + +#### WriteValuePacked(FastBufferWriter, Vector4) + + +Convenience method that writes four varint floats from the vector to the +buffer + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, Vector4 vector4) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|---------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| Vector4 | vector4 | Vector to write | + +#### WriteValuePacked\(FastBufferWriter, TEnum) + + +Write a packed enum value. + + + + + + +##### Declaration + + +``` lang-csharp +public static void WriteValuePacked(FastBufferWriter writer, TEnum value) + where TEnum : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------| +| FastBufferWriter | writer | The writer to write to | +| TEnum | value | The value to write | + +##### Type Parameters + +| Name | Description | +|-------|--------------| +| TEnum | An enum type | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.ByteUnpacker.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.ByteUnpacker.md new file mode 100644 index 000000000..911a3d783 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.ByteUnpacker.md @@ -0,0 +1,850 @@ +--- +id: Unity.Netcode.ByteUnpacker +title: Unity.Netcode.ByteUnpacker +--- + +# Class ByteUnpacker + + +Byte Unpacking Helper Class Use this class to unpack values during +deserialization for values that were packed. BytePacker to pack unpacked +values + + + + + + + +##### Inheritance + + +System.Object + + + + +ByteUnpacker + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public static class ByteUnpacker +``` + + + +### Methods + +#### ReadValueBitPacked(FastBufferReader, out Int16) + + +Read a bit-packed 14-bit signed short from the stream. See BytePacker.cs +for a description of the format. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValueBitPacked(FastBufferReader reader, out short value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.Int16 | value | The value to read | + +#### ReadValueBitPacked(FastBufferReader, out Int32) + + +Read a bit-packed 29-bit signed int from the stream. See BytePacker.cs +for a description of the format. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValueBitPacked(FastBufferReader reader, out int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.Int32 | value | The value to read | + +#### ReadValueBitPacked(FastBufferReader, out Int64) + + +Read a bit-packed 60-bit signed long from the stream. See BytePacker.cs +for a description of the format. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValueBitPacked(FastBufferReader reader, out long value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.Int64 | value | The value to read | + +#### ReadValueBitPacked(FastBufferReader, out UInt16) + + +Read a bit-packed 15-bit unsigned short from the stream. See +BytePacker.cs for a description of the format. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValueBitPacked(FastBufferReader reader, out ushort value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.UInt16 | value | The value to read | + +#### ReadValueBitPacked(FastBufferReader, out UInt32) + + +Read a bit-packed 30-bit unsigned int from the stream. See BytePacker.cs +for a description of the format. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValueBitPacked(FastBufferReader reader, out uint value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.UInt32 | value | The value to read | + +#### ReadValueBitPacked(FastBufferReader, out UInt64) + + +Read a bit-packed 61-bit signed long from the stream. See BytePacker.cs +for a description of the format. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValueBitPacked(FastBufferReader reader, out ulong value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.UInt64 | value | The value to read | + +#### ReadValuePacked(FastBufferReader, out Color) + + +Convenience method that reads four varint floats from the color from the +stream + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out Color color) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| Color | color | Color to read | + +#### ReadValuePacked(FastBufferReader, out Color32) + + +Convenience method that reads four varint floats from the color from the +stream + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out Color32 color) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| Color32 | color | Color to read | + +#### ReadValuePacked(FastBufferReader, out Quaternion) + + +Reads the rotation from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out Quaternion rotation) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|----------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| Quaternion | rotation | Rotation to read | + +#### ReadValuePacked(FastBufferReader, out Ray) + + +Convenience method that reads two packed Vector3 from the ray from the +stream + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out Ray ray) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| Ray | ray | Ray to read | + +#### ReadValuePacked(FastBufferReader, out Ray2D) + + +Convenience method that reads two packed Vector2 from the ray from the +stream + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out Ray2D ray2d) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| Ray2D | ray2d | Ray2D to read | + +#### ReadValuePacked(FastBufferReader, out Boolean) + + +Read a boolean from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out bool value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.Boolean | value | Value to read | + +#### ReadValuePacked(FastBufferReader, out Byte) + + +Read a byte from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out byte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.Byte | value | Value to read | + +#### ReadValuePacked(FastBufferReader, out Char) + + +Read a two-byte character as a varint from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out char c) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.Char | c | Value to read | + +#### ReadValuePacked(FastBufferReader, out Double) + + +Read double-precision floating point value from the stream as a varint + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out double value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.Double | value | Value to read | + +#### ReadValuePacked(FastBufferReader, out Int16) + + +Read an usigned short (Int16) as a varint from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out short value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.Int16 | value | Value to read | + +#### ReadValuePacked(FastBufferReader, out Int32) + + +Read a signed int (Int32) as a ZigZag encoded varint from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.Int32 | value | Value to read | + +#### ReadValuePacked(FastBufferReader, out Int64) + + +Read a signed long (Int64) as a ZigZag encoded varint from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out long value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.Int64 | value | Value to read | + +#### ReadValuePacked(FastBufferReader, out SByte) + + +Read a signed byte from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out sbyte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.SByte | value | Value to read | + +#### ReadValuePacked(FastBufferReader, out Single) + + +Read single-precision floating point value from the stream as a varint + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out float value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.Single | value | Value to read | + +#### ReadValuePacked(FastBufferReader, out String) + + +Reads a string in a packed format + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out string s) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.String | s | | + +#### ReadValuePacked(FastBufferReader, out UInt16) + + +Read an unsigned short (UInt16) as a varint from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out ushort value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.UInt16 | value | Value to read | + +#### ReadValuePacked(FastBufferReader, out UInt32) + + +Read an unsigned int (UInt32) from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out uint value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.UInt32 | value | Value to read | + +#### ReadValuePacked(FastBufferReader, out UInt64) + + +Read an unsigned long (UInt64) from the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out ulong value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| System.UInt64 | value | Value to read | + +#### ReadValuePacked(FastBufferReader, out Vector2) + + +Convenience method that reads two varint floats from the vector from the +stream + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out Vector2 vector2) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|---------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| Vector2 | vector2 | Vector to read | + +#### ReadValuePacked(FastBufferReader, out Vector3) + + +Convenience method that reads three varint floats from the vector from +the stream + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out Vector3 vector3) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|---------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| Vector3 | vector3 | Vector to read | + +#### ReadValuePacked(FastBufferReader, out Vector4) + + +Convenience method that reads four varint floats from the vector from +the stream + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out Vector4 vector4) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|---------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| Vector4 | vector4 | Vector to read | + +#### ReadValuePacked\(FastBufferReader, out TEnum) + + +Read a packed enum value + + + + + + +##### Declaration + + +``` lang-csharp +public static void ReadValuePacked(FastBufferReader reader, out TEnum value) + where TEnum : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-------------------------| +| FastBufferReader | reader | The reader to read from | +| TEnum | value | The value that's read | + +##### Type Parameters + +| Name | Description | +|-------|----------------------| +| TEnum | Type of enum to read | + +##### Exceptions + +| Type | Condition | +|----------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------| +| System.InvalidOperationException | Throws InvalidOperationException if an enum somehow ends up not being the size of a byte, short, int, or long (which should be impossible) | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcAttribute.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcAttribute.md new file mode 100644 index 000000000..1e375fa69 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcAttribute.md @@ -0,0 +1,393 @@ +--- +id: Unity.Netcode.ClientRpcAttribute +title: Unity.Netcode.ClientRpcAttribute +--- + +# Class ClientRpcAttribute + + +Marks a method as ClientRpc. + +A ClientRpc marked method will be fired by the server but executed on +clients. + + + + + + + +##### Inheritance + + +System.Object + + + + +System.Attribute + + + + +RpcAttribute + + + + +ClientRpcAttribute + + + + + + +##### Implements + + + +System.Runtime.InteropServices.\_Attribute + + + + + + +##### Inherited Members + + + +RpcAttribute.Delivery + + + + + +System.Attribute.Equals(System.Object) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Assembly, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Assembly, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.MemberInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.MemberInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Module, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Module, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.ParameterInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.ParameterInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetHashCode() + + + + + +System.Attribute.IsDefaultAttribute() + + + + + +System.Attribute.IsDefined(System.Reflection.Assembly, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.Assembly, System.Type, +System.Boolean) + + + + + +System.Attribute.IsDefined(System.Reflection.MemberInfo, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.MemberInfo, System.Type, +System.Boolean) + + + + + +System.Attribute.IsDefined(System.Reflection.Module, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.Module, System.Type, +System.Boolean) + + + + + +System.Attribute.IsDefined(System.Reflection.ParameterInfo, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.ParameterInfo, System.Type, +System.Boolean) + + + + + +System.Attribute.Match(System.Object) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.GetIDsOfNames(System.Guid, +System.IntPtr, System.UInt32, System.UInt32, System.IntPtr) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.GetTypeInfo(System.UInt32, +System.UInt32, System.IntPtr) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.GetTypeInfoCount(System.UInt32) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.Invoke(System.UInt32, +System.Guid, System.UInt32, System.Int16, System.IntPtr, System.IntPtr, +System.IntPtr, System.IntPtr) + + + + + +System.Attribute.TypeId + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +[AttributeUsage(AttributeTargets.Method)] +public class ClientRpcAttribute : RpcAttribute, _Attribute +``` + + + +### Implements + + + +System.Runtime.InteropServices.\_Attribute + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcParams.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcParams.md new file mode 100644 index 000000000..c0d2382d5 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcParams.md @@ -0,0 +1,126 @@ +--- +id: Unity.Netcode.ClientRpcParams +title: Unity.Netcode.ClientRpcParams +--- + +# Struct ClientRpcParams + + +Client-Side RPC Can be used with any client-side remote procedure call +Note: Typically this is used primarily for sending to a specific list of +clients as opposed to the default (all). ClientRpcSendParams + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ClientRpcParams +``` + + + +### Fields + +#### Receive + + +The client RPC receive parameters (currently a place holder) + + + + + + +##### Declaration + + +``` lang-csharp +public ClientRpcReceiveParams Receive +``` + + + +##### Field Value + +| Type | Description | +|------------------------|-------------| +| ClientRpcReceiveParams | | + +#### Send + + +The client RPC send parameters provides you with the ability to send to +a specific list of clients + + + + + + +##### Declaration + + +``` lang-csharp +public ClientRpcSendParams Send +``` + + + +##### Field Value + +| Type | Description | +|---------------------|-------------| +| ClientRpcSendParams | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcReceiveParams.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcReceiveParams.md new file mode 100644 index 000000000..caf7b0bbf --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcReceiveParams.md @@ -0,0 +1,72 @@ +--- +id: Unity.Netcode.ClientRpcReceiveParams +title: Unity.Netcode.ClientRpcReceiveParams +--- + +# Struct ClientRpcReceiveParams + + +Client-Side RPC Place holder. ServerRpcParams Note: Server will always +be the sender, so this structure is a place holder + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ClientRpcReceiveParams +``` + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcSendParams.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcSendParams.md new file mode 100644 index 000000000..3cbecd3b1 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.ClientRpcSendParams.md @@ -0,0 +1,130 @@ +--- +id: Unity.Netcode.ClientRpcSendParams +title: Unity.Netcode.ClientRpcSendParams +--- + +# Struct ClientRpcSendParams + + +Client-Side RPC The send parameters, when sending client RPCs, provides +you wil the ability to target specific clients as a managed or unmanaged +list: TargetClientIds and TargetClientIdsNativeArray + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ClientRpcSendParams +``` + + + +### Fields + +#### TargetClientIds + + +IEnumerable version of target id list - use either this OR +TargetClientIdsNativeArray Note: Even if you provide a value type such +as NativeArray, enumerating it will cause boxing. If you want to avoid +boxing, use TargetClientIdsNativeArray + + + + + + +##### Declaration + + +``` lang-csharp +public IReadOnlyList TargetClientIds +``` + + + +##### Field Value + +| Type | Description | +|--------------------------------|-------------| +| IReadOnlyList\ | | + +#### TargetClientIdsNativeArray + + +NativeArray version of target id list - use either this OR +TargetClientIds This option avoids any GC allocations but is a bit +trickier to use. + + + + + + +##### Declaration + + +``` lang-csharp +public NativeArray? TargetClientIdsNativeArray +``` + + + +##### Field Value + +| Type | Description | +|-------------------------------------------------|-------------| +| System.Nullable\\> | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.CustomMessagingManager.HandleNamedMessageDelegate.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.CustomMessagingManager.HandleNamedMessageDelegate.md new file mode 100644 index 000000000..7c7ea402c --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.CustomMessagingManager.HandleNamedMessageDelegate.md @@ -0,0 +1,37 @@ +--- +id: Unity.Netcode.CustomMessagingManager.HandleNamedMessageDelegate +title: Unity.Netcode.CustomMessagingManager.HandleNamedMessageDelegate +--- + +# Delegate CustomMessagingManager.HandleNamedMessageDelegate + + +Delegate used to handle named messages + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void HandleNamedMessageDelegate(ulong senderClientId, FastBufferReader messagePayload); +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|----------------|-------------| +| System.UInt64 | senderClientId | | +| FastBufferReader | messagePayload | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.CustomMessagingManager.UnnamedMessageDelegate.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.CustomMessagingManager.UnnamedMessageDelegate.md new file mode 100644 index 000000000..40558bb4a --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.CustomMessagingManager.UnnamedMessageDelegate.md @@ -0,0 +1,37 @@ +--- +id: Unity.Netcode.CustomMessagingManager.UnnamedMessageDelegate +title: Unity.Netcode.CustomMessagingManager.UnnamedMessageDelegate +--- + +# Delegate CustomMessagingManager.UnnamedMessageDelegate + + +Delegate used for incoming unnamed messages + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void UnnamedMessageDelegate(ulong clientId, FastBufferReader reader); +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|----------|----------------------------------------| +| System.UInt64 | clientId | The clientId that sent the message | +| FastBufferReader | reader | The stream containing the message data | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.CustomMessagingManager.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.CustomMessagingManager.md new file mode 100644 index 000000000..81a3f2f52 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.CustomMessagingManager.md @@ -0,0 +1,337 @@ +--- +id: Unity.Netcode.CustomMessagingManager +title: Unity.Netcode.CustomMessagingManager +--- + +# Class CustomMessagingManager + + +The manager class to manage custom messages, note that this is different +from the NetworkManager custom messages. These are named and are much +easier to use. + + + + + + + +##### Inheritance + + +System.Object + + + + +CustomMessagingManager + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class CustomMessagingManager +``` + + + +### Methods + +#### RegisterNamedMessageHandler(String, CustomMessagingManager.HandleNamedMessageDelegate) + + +Registers a named message handler delegate. + + + + + + +##### Declaration + + +``` lang-csharp +public void RegisterNamedMessageHandler(string name, CustomMessagingManager.HandleNamedMessageDelegate callback) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------------------------------|----------|-------------------------------------------------------| +| System.String | name | Name of the message. | +| CustomMessagingManager.HandleNamedMessageDelegate | callback | The callback to run when a named message is received. | + +#### SendNamedMessage(String, IReadOnlyList\, FastBufferWriter, NetworkDelivery) + + +Sends the named message + + + + + + +##### Declaration + + +``` lang-csharp +public void SendNamedMessage(string messageName, IReadOnlyList clientIds, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|-----------------|-------------------------------------------| +| System.String | messageName | The message name to send | +| IReadOnlyList\ | clientIds | The clients to send to | +| FastBufferWriter | messageStream | The message stream containing the data | +| NetworkDelivery | networkDelivery | The delivery type (QoS) to send data with | + +#### SendNamedMessage(String, UInt64, FastBufferWriter, NetworkDelivery) + + +Sends a named message + + + + + + +##### Declaration + + +``` lang-csharp +public void SendNamedMessage(string messageName, ulong clientId, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|-----------------|-------------------------------------------| +| System.String | messageName | The message name to send | +| System.UInt64 | clientId | The client to send the message to | +| FastBufferWriter | messageStream | The message stream containing the data | +| NetworkDelivery | networkDelivery | The delivery type (QoS) to send data with | + +#### SendNamedMessageToAll(String, FastBufferWriter, NetworkDelivery) + + +Sends a named message to all clients + + + + + + +##### Declaration + + +``` lang-csharp +public void SendNamedMessageToAll(string messageName, FastBufferWriter messageStream, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|-----------------|-------------------------------------------| +| System.String | messageName | The message name to send | +| FastBufferWriter | messageStream | The message stream containing the data | +| NetworkDelivery | networkDelivery | The delivery type (QoS) to send data with | + +#### SendUnnamedMessage(IReadOnlyList\, FastBufferWriter, NetworkDelivery) + + +Sends unnamed message to a list of clients + + + + + + +##### Declaration + + +``` lang-csharp +public void SendUnnamedMessage(IReadOnlyList clientIds, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|-----------------|---------------------------------------------------| +| IReadOnlyList\ | clientIds | The clients to send to, sends to everyone if null | +| FastBufferWriter | messageBuffer | The message stream containing the data | +| NetworkDelivery | networkDelivery | The delivery type (QoS) to send data with | + +#### SendUnnamedMessage(UInt64, FastBufferWriter, NetworkDelivery) + + +Sends a unnamed message to a specific client + + + + + + +##### Declaration + + +``` lang-csharp +public void SendUnnamedMessage(ulong clientId, FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|-----------------|-------------------------------------------| +| System.UInt64 | clientId | The client to send the message to | +| FastBufferWriter | messageBuffer | The message stream containing the data | +| NetworkDelivery | networkDelivery | The delivery type (QoS) to send data with | + +#### SendUnnamedMessageToAll(FastBufferWriter, NetworkDelivery) + + +Sends unnamed message to all clients + + + + + + +##### Declaration + + +``` lang-csharp +public void SendUnnamedMessageToAll(FastBufferWriter messageBuffer, NetworkDelivery networkDelivery = NetworkDelivery.ReliableSequenced) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|-----------------|-------------------------------------------| +| FastBufferWriter | messageBuffer | The message stream containing the data | +| NetworkDelivery | networkDelivery | The delivery type (QoS) to send data with | + +#### UnregisterNamedMessageHandler(String) + + +Unregisters a named message handler. + + + + + + +##### Declaration + + +``` lang-csharp +public void UnregisterNamedMessageHandler(string name) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|------|--------------------------| +| System.String | name | The name of the message. | + +### Events + +#### OnUnnamedMessage + + +Event invoked when unnamed messages arrive + + + + + + +##### Declaration + + +``` lang-csharp +public event CustomMessagingManager.UnnamedMessageDelegate OnUnnamedMessage +``` + + + +##### Event Type + +| Type | Description | +|-----------------------------------------------|-------------| +| CustomMessagingManager.UnnamedMessageDelegate | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferReader.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferReader.md new file mode 100644 index 000000000..5fddc0f82 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferReader.md @@ -0,0 +1,2701 @@ +--- +id: Unity.Netcode.FastBufferReader +title: Unity.Netcode.FastBufferReader +--- + +# Struct FastBufferReader + + +Optimized class used for reading values from a byte stream +FastBufferWriter BytePacker ByteUnpacker + + + + + + + +##### Implements + + + +System.IDisposable + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct FastBufferReader : IDisposable +``` + + + +### Constructors + +#### FastBufferReader(NativeArray\, Allocator, Int32, Int32, Allocator) + + +Create a FastBufferReader from a NativeArray. + +A new buffer will be created using the given and the value will be +copied in. FastBufferReader will then own the data. + +The exception to this is when the passed in is Allocator.None. In this +scenario, ownership of the data remains with the caller and the reader +will point at it directly. When created with Allocator.None, +FastBufferReader will allocate some internal data using Allocator.Temp +so it should be treated as if it's a ref struct and not allowed to +outlive the context in which it was created (it should neither be +returned from that function nor stored anywhere in heap memory). This is +true, unless the param is explicitly set to i.e.: Allocator.Persistent +in which case it would allow the internal data to Persist for longer, +but the caller should manually call Dispose() when it is no longer +needed. + + + + + + +##### Declaration + + +``` lang-csharp +public FastBufferReader(NativeArray buffer, Allocator copyAllocator, int length = -1, int offset = 0, Allocator internalAllocator = null) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------------|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| NativeArray\ | buffer | | +| Allocator | copyAllocator | The allocator type used for internal data when copying an existing buffer if other than Allocator.None is specified, that memory will be owned by this FastBufferReader instance | +| System.Int32 | length | | +| System.Int32 | offset | | +| Allocator | internalAllocator | The allocator type used for internal data when this reader points directly at a buffer owned by someone else | + +#### FastBufferReader(ArraySegment\, Allocator, Int32, Int32) + + +Create a FastBufferReader from an ArraySegment. + +A new buffer will be created using the given allocator and the value +will be copied in. FastBufferReader will then own the data. + +Allocator.None is not supported for byte\[\]. If you need this +functionality, use a fixed() block and ensure the FastBufferReader isn't +used outside that block. + + + + + + +##### Declaration + + +``` lang-csharp +public FastBufferReader(ArraySegment buffer, Allocator copyAllocator, int length = -1, int offset = 0) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------------------|---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| System.ArraySegment\ | buffer | The buffer to copy from | +| Allocator | copyAllocator | The allocator type used for internal data when copying an existing buffer if other than Allocator.None is specified, that memory will be owned by this FastBufferReader instance | +| System.Int32 | length | The number of bytes to copy (all if this is -1) | +| System.Int32 | offset | The offset of the buffer to start copying from | + +#### FastBufferReader(Byte\*, Allocator, Int32, Int32, Allocator) + + +Create a FastBufferReader from an existing byte buffer. + +A new buffer will be created using the given and the value will be +copied in. FastBufferReader will then own the data. + +The exception to this is when the passed in is Allocator.None. In this +scenario, ownership of the data remains with the caller and the reader +will point at it directly. When created with Allocator.None, +FastBufferReader will allocate some internal data using Allocator.Temp, +so it should be treated as if it's a ref struct and not allowed to +outlive the context in which it was created (it should neither be +returned from that function nor stored anywhere in heap memory). This is +true, unless the param is explicitly set to i.e.: Allocator.Persistent +in which case it would allow the internal data to Persist for longer, +but the caller should manually call Dispose() when it is no longer +needed. + + + + + + +##### Declaration + + +``` lang-csharp +public FastBufferReader(byte *buffer, Allocator copyAllocator, int length, int offset = 0, Allocator internalAllocator = null) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| System.Byte\* | buffer | The buffer to copy from | +| Allocator | copyAllocator | The allocator type used for internal data when copying an existing buffer if other than Allocator.None is specified, that memory will be owned by this FastBufferReader instance | +| System.Int32 | length | The number of bytes to copy | +| System.Int32 | offset | The offset of the buffer to start copying from | +| Allocator | internalAllocator | The allocator type used for internal data when this reader points directly at a buffer owned by someone else | + +#### FastBufferReader(Byte\[\], Allocator, Int32, Int32) + + +Create a FastBufferReader from an existing byte array. + +A new buffer will be created using the given allocator and the value +will be copied in. FastBufferReader will then own the data. + +Allocator.None is not supported for byte\[\]. If you need this +functionality, use a fixed() block and ensure the FastBufferReader isn't +used outside that block. + + + + + + +##### Declaration + + +``` lang-csharp +public FastBufferReader(byte[] buffer, Allocator copyAllocator, int length = -1, int offset = 0) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------|---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| System.Byte\[\] | buffer | The buffer to copy from | +| Allocator | copyAllocator | The allocator type used for internal data when copying an existing buffer if other than Allocator.None is specified, that memory will be owned by this FastBufferReader instance | +| System.Int32 | length | The number of bytes to copy (all if this is -1) | +| System.Int32 | offset | The offset of the buffer to start copying from | + +#### FastBufferReader(FastBufferReader, Allocator, Int32, Int32, Allocator) + + +Create a FastBufferReader from another existing FastBufferReader. This +is typically used when you want to change the copyAllocator that a +reader is allocated to - for example, upgrading a Temp reader to a +Persistent one to be processed later. + +A new buffer will be created using the given and the value will be +copied in. FastBufferReader will then own the data. + +The exception to this is when the passed in is Allocator.None. In this +scenario, ownership of the data remains with the caller and the reader +will point at it directly. When created with Allocator.None, +FastBufferReader will allocate some internal data using Allocator.Temp, +so it should be treated as if it's a ref struct and not allowed to +outlive the context in which it was created (it should neither be +returned from that function nor stored anywhere in heap memory). + + + + + + +##### Declaration + + +``` lang-csharp +public FastBufferReader(FastBufferReader reader, Allocator copyAllocator, int length = -1, int offset = 0, Allocator internalAllocator = null) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| FastBufferReader | reader | The reader to copy from | +| Allocator | copyAllocator | The allocator type used for internal data when copying an existing buffer if other than Allocator.None is specified, that memory will be owned by this FastBufferReader instance | +| System.Int32 | length | The number of bytes to copy (all if this is -1) | +| System.Int32 | offset | The offset of the buffer to start copying from | +| Allocator | internalAllocator | The allocator type used for internal data when this reader points directly at a buffer owned by someone else | + +#### FastBufferReader(FastBufferWriter, Allocator, Int32, Int32, Allocator) + + +Create a FastBufferReader from a FastBufferWriter. + +A new buffer will be created using the given and the value will be +copied in. FastBufferReader will then own the data. + +The exception to this is when the passed in is Allocator.None. In this +scenario, ownership of the data remains with the caller and the reader +will point at it directly. When created with Allocator.None, +FastBufferReader will allocate some internal data using Allocator.Temp, +so it should be treated as if it's a ref struct and not allowed to +outlive the context in which it was created (it should neither be +returned from that function nor stored anywhere in heap memory). This is +true, unless the param is explicitly set to i.e.: Allocator.Persistent +in which case it would allow the internal data to Persist for longer, +but the caller should manually call Dispose() when it is no longer +needed. + + + + + + +##### Declaration + + +``` lang-csharp +public FastBufferReader(FastBufferWriter writer, Allocator copyAllocator, int length = -1, int offset = 0, Allocator internalAllocator = null) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|-------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| FastBufferWriter | writer | The writer to copy from | +| Allocator | copyAllocator | The allocator type used for internal data when copying an existing buffer if other than Allocator.None is specified, that memory will be owned by this FastBufferReader instance | +| System.Int32 | length | The number of bytes to copy (all if this is -1) | +| System.Int32 | offset | The offset of the buffer to start copying from | +| Allocator | internalAllocator | The allocator type used for internal data when this reader points directly at a buffer owned by someone else | + +### Properties + +#### IsInitialized + + +Gets a value indicating whether the reader has been initialized and a +handle allocated. + + + + + + +##### Declaration + + +``` lang-csharp +public readonly bool IsInitialized { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### Length + + +Get the total length of the buffer + + + + + + +##### Declaration + + +``` lang-csharp +public readonly int Length { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### Position + + +Get the current read position + + + + + + +##### Declaration + + +``` lang-csharp +public readonly int Position { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +### Methods + +#### Dispose() + + +System.IDisposable implementation that frees the allocated buffer + + + + + + +##### Declaration + + +``` lang-csharp +public void Dispose() +``` + + + +#### EnterBitwiseContext() + + +Retrieve a BitReader to be able to perform bitwise operations on the +buffer. No bytewise operations can be performed on the buffer until +bitReader.Dispose() has been called. At the end of the operation, +FastBufferReader will remain byte-aligned. + + + + + + +##### Declaration + + +``` lang-csharp +public BitReader EnterBitwiseContext() +``` + + + +##### Returns + +| Type | Description | +|-----------|-------------| +| BitReader | A BitReader | + +#### GetUnsafePtr() + + +Gets a direct pointer to the underlying buffer + + + + + + +##### Declaration + + +``` lang-csharp +public byte *GetUnsafePtr() +``` + + + +##### Returns + +| Type | Description | +|---------------|---------------------| +| System.Byte\* | System.Byte pointer | + +#### GetUnsafePtrAtCurrentPosition() + + +Gets a direct pointer to the underlying buffer at the current read +position + + + + + + +##### Declaration + + +``` lang-csharp +public byte *GetUnsafePtrAtCurrentPosition() +``` + + + +##### Returns + +| Type | Description | +|---------------|---------------------| +| System.Byte\* | System.Byte pointer | + +#### ReadByte(out Byte) + + +Read a byte to the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadByte(out byte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|-----------------------| +| System.Byte | value | Stores the read value | + +#### ReadBytes(Byte\*, Int32, Int32) + + +Read multiple bytes to the stream + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadBytes(byte *value, int size, int offset = 0) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|--------|---------------------------------------------------| +| System.Byte\* | value | Pointer to the destination buffer | +| System.Int32 | size | Number of bytes to read - MUST BE \<= BUFFER SIZE | +| System.Int32 | offset | Offset of the byte buffer to store into | + +#### ReadBytes(ref Byte\[\], Int32, Int32) + + +Read multiple bytes from the stream + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadBytes(ref byte[] value, int size, int offset = 0) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------|--------|---------------------------------------------------| +| System.Byte\[\] | value | Pointer to the destination buffer | +| System.Int32 | size | Number of bytes to read - MUST BE \<= BUFFER SIZE | +| System.Int32 | offset | Offset of the byte buffer to store into | + +#### ReadByteSafe(out Byte) + + +Read a byte to the stream. + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadByteSafe(out byte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|-----------------------| +| System.Byte | value | Stores the read value | + +#### ReadBytesSafe(Byte\*, Int32, Int32) + + +Read multiple bytes to the stream + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadBytesSafe(byte *value, int size, int offset = 0) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|--------|---------------------------------------------------| +| System.Byte\* | value | Pointer to the destination buffer | +| System.Int32 | size | Number of bytes to read - MUST BE \<= BUFFER SIZE | +| System.Int32 | offset | Offset of the byte buffer to store into | + +#### ReadBytesSafe(ref Byte\[\], Int32, Int32) + + +Read multiple bytes from the stream + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadBytesSafe(ref byte[] value, int size, int offset = 0) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------|--------|---------------------------------------------------| +| System.Byte\[\] | value | Pointer to the destination buffer | +| System.Int32 | size | Number of bytes to read - MUST BE \<= BUFFER SIZE | +| System.Int32 | offset | Offset of the byte buffer to store into | + +#### ReadNetworkSerializable\(out T) + + +Read an INetworkSerializable + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadNetworkSerializable(out T value) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|-------------------------------| +| T | value | INetworkSerializable instance | + +##### Type Parameters + +| Name | Description | +|------|-------------| +| T | | + +##### Exceptions + +| Type | Condition | +|--------------------------------|-----------| +| System.NotImplementedException | | + +#### ReadNetworkSerializable\(out T\[\]) + + +Read an array of INetworkSerializables + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadNetworkSerializable(out T[] value) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------------------| +| T\[\] | value | INetworkSerializable instance | + +##### Type Parameters + +| Name | Description | +|------|-----------------------------------------------| +| T | the array to read the values of type `T` into | + +##### Exceptions + +| Type | Condition | +|--------------------------------|-----------| +| System.NotImplementedException | | + +#### ReadPartialValue\(out T, Int32, Int32) + + +Read a partial value. The value is zero-initialized and then the +specified number of bytes is read into it. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadPartialValue(out T value, int bytesToRead, int offsetBytes = 0) + where T : struct +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------------|------------------------------------------| +| T | value | Value to read | +| System.Int32 | bytesToRead | Number of bytes | +| System.Int32 | offsetBytes | Offset into the value to write the bytes | + +##### Type Parameters + +| Name | Description | +|------|---------------------------------------| +| T | the type value to read the value into | + +##### Exceptions + +| Type | Condition | +|----------------------------------|-----------| +| System.InvalidOperationException | | +| System.OverflowException | | + +#### ReadValue(out Color) + + +Read a Color + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Color value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------| +| Color | value | the value to read | + +#### ReadValue(out Color\[\]) + + +Read a Color array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Color[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|--------------------| +| Color\[\] | value | the values to read | + +#### ReadValue(out Color32) + + +Read a Color32 + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Color32 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------| +| Color32 | value | the value to read | + +#### ReadValue(out Color32\[\]) + + +Read a Color32 array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Color32[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------| +| Color32\[\] | value | the values to read | + +#### ReadValue(out Quaternion) + + +Read a Quaternion + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Quaternion value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------| +| Quaternion | value | the value to read | + +#### ReadValue(out Quaternion\[\]) + + +Read a Quaternion array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Quaternion[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------| +| Quaternion\[\] | value | the values to read | + +#### ReadValue(out Ray) + + +Read a Ray + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Ray value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|-------------------| +| Ray | value | the value to read | + +#### ReadValue(out Ray\[\]) + + +Read a Ray array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Ray[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------| +| Ray\[\] | value | the values to read | + +#### ReadValue(out Ray2D) + + +Read a Ray2D + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Ray2D value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------| +| Ray2D | value | the value to read | + +#### ReadValue(out Ray2D\[\]) + + +Read a Ray2D array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Ray2D[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|--------------------| +| Ray2D\[\] | value | the values to read | + +#### ReadValue(out String, Boolean) + + +Reads a string NOTE: ALLOCATES + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out string s, bool oneByteChars = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------|--------------------------------------------------------------------------| +| System.String | s | Stores the read string | +| System.Boolean | oneByteChars | Whether or not to use one byte per character. This will only allow ASCII | + +#### ReadValue(out Vector2) + + +Read a Vector2 + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Vector2 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------| +| Vector2 | value | the value to read | + +#### ReadValue(out Vector2\[\]) + + +Read a Vector2 array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Vector2[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------| +| Vector2\[\] | value | the values to read | + +#### ReadValue(out Vector2Int) + + +Read a Vector2Int + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Vector2Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------| +| Vector2Int | value | the value to read | + +#### ReadValue(out Vector2Int\[\]) + + +Read a Vector2Int array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Vector2Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------| +| Vector2Int\[\] | value | the values to read | + +#### ReadValue(out Vector3) + + +Read a Vector3 + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Vector3 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------| +| Vector3 | value | the value to read | + +#### ReadValue(out Vector3\[\]) + + +Read a Vector3 array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Vector3[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------| +| Vector3\[\] | value | the values to read | + +#### ReadValue(out Vector3Int) + + +Read a Vector3Int + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Vector3Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------| +| Vector3Int | value | the value to read | + +#### ReadValue(out Vector3Int\[\]) + + +Read a Vector3Int array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Vector3Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|-------------------| +| Vector3Int\[\] | value | the value to read | + +#### ReadValue(out Vector4) + + +Read a Vector4 + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Vector4 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------| +| Vector4 | value | the value to read | + +#### ReadValue(out Vector4\[\]) + + +Read a Vector4 + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out Vector4[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------| +| Vector4\[\] | value | the values to read | + +#### ReadValue\(out T, FastBufferWriter.ForEnums) + + +Read an enum value + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out T value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValue\(out T, FastBufferWriter.ForFixedStrings) + + +Read a FixedString value. This method is a little difficult to use, +since you have to know the size of the string before reading it, but is +useful when the string is a known, fixed size. Note that the size of the +string is also encoded, so the size to call TryBeginRead on is actually +the fixed size (in bytes) plus sizeof(int) + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out T value, FastBufferWriter.ForFixedStrings unused = default(FastBufferWriter.ForFixedStrings)) + where T : struct, INativeList, IUTF8Bytes +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | the value to read | +| FastBufferWriter.ForFixedStrings | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValue\(out T, FastBufferWriter.ForNetworkSerializable) + + +Read a NetworkSerializable value + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out T value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValue\(out T, FastBufferWriter.ForPrimitives) + + +Read a primitive value (int, bool, etc) Accepts any value that +implements the given interfaces, but is not guaranteed to work correctly +on values that are not primitives. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out T value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValue\(out T, FastBufferWriter.ForStructs) + + +Read a struct + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out T value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValue\(out T\[\], FastBufferWriter.ForEnums) + + +Read an enum array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out T[] value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValue\(out T\[\], FastBufferWriter.ForNetworkSerializable) + + +Read a NetworkSerializable array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out T[] value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValue\(out T\[\], FastBufferWriter.ForPrimitives) + + +Read a primitive value array (int, bool, etc) Accepts any value that +implements the given interfaces, but is not guaranteed to work correctly +on values that are not primitives. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out T[] value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValue\(out T\[\], FastBufferWriter.ForStructs) + + +Read a struct array + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValue(out T[] value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValueSafe(out Color) + + +Read a Color + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Color value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------| +| Color | value | the value to read | + +#### ReadValueSafe(out Color\[\]) + + +Read a Collor array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Color[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|--------------------| +| Color\[\] | value | the values to read | + +#### ReadValueSafe(out Color32) + + +Read a Color32 + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Color32 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------| +| Color32 | value | the value to read | + +#### ReadValueSafe(out Color32\[\]) + + +Read a Color32 array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Color32[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------| +| Color32\[\] | value | the values to read | + +#### ReadValueSafe(out Quaternion) + + +Read a Quaternion + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Quaternion value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------| +| Quaternion | value | the value to read | + +#### ReadValueSafe(out Quaternion\[\]) + + +Read a Quaternion array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Quaternion[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------| +| Quaternion\[\] | value | the values to read | + +#### ReadValueSafe(out Ray) + + +Read a Ray + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Ray value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|-------------------| +| Ray | value | the value to read | + +#### ReadValueSafe(out Ray\[\]) + + +Read a Ray array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Ray[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------| +| Ray\[\] | value | the values to read | + +#### ReadValueSafe(out Ray2D) + + +Read a Ray2D + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Ray2D value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------| +| Ray2D | value | the value to read | + +#### ReadValueSafe(out Ray2D\[\]) + + +Read a Ray2D array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Ray2D[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|--------------------| +| Ray2D\[\] | value | the values to read | + +#### ReadValueSafe(out String, Boolean) + + +Reads a string. NOTE: ALLOCATES + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out string s, bool oneByteChars = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------|--------------------------------------------------------------------------| +| System.String | s | Stores the read string | +| System.Boolean | oneByteChars | Whether or not to use one byte per character. This will only allow ASCII | + +#### ReadValueSafe(out Vector2) + + +Read a Vector2 + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Vector2 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------| +| Vector2 | value | the value to read | + +#### ReadValueSafe(out Vector2\[\]) + + +Read a Vector2 array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Vector2[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------| +| Vector2\[\] | value | the values to read | + +#### ReadValueSafe(out Vector2Int) + + +Read a Vector2Int + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Vector2Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------| +| Vector2Int | value | the value to read | + +#### ReadValueSafe(out Vector2Int\[\]) + + +Read a Vector2Int array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Vector2Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------| +| Vector2Int\[\] | value | the values to read | + +#### ReadValueSafe(out Vector3) + + +Read a Vector3 + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Vector3 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------| +| Vector3 | value | the value to read | + +#### ReadValueSafe(out Vector3\[\]) + + +Read a Vector3 array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Vector3[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------| +| Vector3\[\] | value | the values to read | + +#### ReadValueSafe(out Vector3Int) + + +Read a Vector3Int + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Vector3Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------| +| Vector3Int | value | the value to read | + +#### ReadValueSafe(out Vector3Int\[\]) + + +Read a Vector3Int array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Vector3Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------| +| Vector3Int\[\] | value | the values to read | + +#### ReadValueSafe(out Vector4) + + +Read a Vector4 + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Vector4 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------| +| Vector4 | value | the value to read | + +#### ReadValueSafe(out Vector4\[\]) + + +Read a Vector4 array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out Vector4[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------| +| Vector4\[\] | value | the values to read | + +#### ReadValueSafe\(out T, FastBufferWriter.ForEnums) + + +Read an enum value + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out T value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValueSafe\(out T, FastBufferWriter.ForFixedStrings) + + +Read a FixedString value. + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out T value, FastBufferWriter.ForFixedStrings unused = default(FastBufferWriter.ForFixedStrings)) + where T : struct, INativeList, IUTF8Bytes +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | the value to read | +| FastBufferWriter.ForFixedStrings | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValueSafe\(out T, FastBufferWriter.ForNetworkSerializable) + + +Read a NetworkSerializable value + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out T value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValueSafe\(out T, FastBufferWriter.ForPrimitives) + + +Read a primitive value (int, bool, etc) Accepts any value that +implements the given interfaces, but is not guaranteed to work correctly +on values that are not primitives. + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out T value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValueSafe\(out T, FastBufferWriter.ForStructs) + + +Read a struct + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out T value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValueSafe\(out T\[\], FastBufferWriter.ForEnums) + + +Read an enum array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out T[] value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValueSafe\(out T\[\], FastBufferWriter.ForNetworkSerializable) + + +Read a NetworkSerializable array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out T[] value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValueSafe\(out T\[\], FastBufferWriter.ForPrimitives) + + +Read a primitive value (int, bool, etc) Accepts any value that +implements the given interfaces, but is not guaranteed to work correctly +on values that are not primitives. + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out T[] value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The value to read | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### ReadValueSafe\(out T\[\], FastBufferWriter.ForStructs) + + +Read a struct array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple reads at once by calling TryBeginRead. + + + + + + +##### Declaration + + +``` lang-csharp +public void ReadValueSafe(out T[] value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### Seek(Int32) + + +Move the read position in the stream + + + + + + +##### Declaration + + +``` lang-csharp +public void Seek(int where) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------|-------------------------------------------------------------| +| System.Int32 | where | Absolute value to move the position to, truncated to Length | + +#### ToArray() + + +Returns an array representation of the underlying byte buffer. +!!Allocates a new array!! + + + + + + +##### Declaration + + +``` lang-csharp +public byte[] ToArray() +``` + + + +##### Returns + +| Type | Description | +|-----------------|-------------| +| System.Byte\[\] | byte array | + +#### TryBeginRead(Int32) + + +Allows faster serialization by batching bounds checking. When you know +you will be reading multiple fields back-to-back and you know the total +size, you can call TryBeginRead() once on the total size, and then +follow it with calls to ReadValue() instead of ReadValueSafe() for +faster serialization. + +Unsafe read operations will throw OverflowException in editor and +development builds if you go past the point you've marked using +TryBeginRead(). In release builds, OverflowException will not be thrown +for performance reasons, since the point of using TryBeginRead is to +avoid bounds checking in the following operations in release builds. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TryBeginRead(int bytes) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------|-------------------------| +| System.Int32 | bytes | Amount of bytes to read | + +##### Returns + +| Type | Description | +|----------------|----------------------------------------------| +| System.Boolean | True if the read is allowed, false otherwise | + +##### Exceptions + +| Type | Condition | +|----------------------------------|--------------------------------------| +| System.InvalidOperationException | If called while in a bitwise context | + +#### TryBeginReadValue\(in T) + + +Allows faster serialization by batching bounds checking. When you know +you will be reading multiple fields back-to-back and you know the total +size, you can call TryBeginRead() once on the total size, and then +follow it with calls to ReadValue() instead of ReadValueSafe() for +faster serialization. + +Unsafe read operations will throw OverflowException in editor and +development builds if you go past the point you've marked using +TryBeginRead(). In release builds, OverflowException will not be thrown +for performance reasons, since the point of using TryBeginRead is to +avoid bounds checking in the following operations in release builds. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TryBeginReadValue(in T value) + where T : struct +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|----------------------------| +| T | value | The value you want to read | + +##### Returns + +| Type | Description | +|----------------|----------------------------------------------| +| System.Boolean | True if the read is allowed, false otherwise | + +##### Type Parameters + +| Name | Description | +|------|--------------------------------------------------| +| T | the type `T` of the value you are trying to read | + +##### Exceptions + +| Type | Condition | +|----------------------------------|--------------------------------------| +| System.InvalidOperationException | If called while in a bitwise context | + +### Implements + + + +System.IDisposable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForEnums.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForEnums.md new file mode 100644 index 000000000..da359b9e3 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForEnums.md @@ -0,0 +1,79 @@ +--- +id: Unity.Netcode.FastBufferWriter.ForEnums +title: Unity.Netcode.FastBufferWriter.ForEnums +--- + +# Struct FastBufferWriter.ForEnums + + +This empty struct exists to allow overloading WriteValue based on +generic constraints. At the bytecode level, constraints aren't included +in the method signature, so if multiple methods exist with the same +signature, it causes a compile error because they would end up being +emitted as the same method, even if the constraints are different. +Adding an empty struct with a default value gives them different +signatures in the bytecode, which then allows the compiler to do +overload resolution based on the generic constraints without the user +having to pass the struct in themselves. + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ForEnums +``` + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForFixedStrings.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForFixedStrings.md new file mode 100644 index 000000000..67db70d45 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForFixedStrings.md @@ -0,0 +1,79 @@ +--- +id: Unity.Netcode.FastBufferWriter.ForFixedStrings +title: Unity.Netcode.FastBufferWriter.ForFixedStrings +--- + +# Struct FastBufferWriter.ForFixedStrings + + +This empty struct exists to allow overloading WriteValue based on +generic constraints. At the bytecode level, constraints aren't included +in the method signature, so if multiple methods exist with the same +signature, it causes a compile error because they would end up being +emitted as the same method, even if the constraints are different. +Adding an empty struct with a default value gives them different +signatures in the bytecode, which then allows the compiler to do +overload resolution based on the generic constraints without the user +having to pass the struct in themselves. + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ForFixedStrings +``` + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForNetworkSerializable.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForNetworkSerializable.md new file mode 100644 index 000000000..a22b81baa --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForNetworkSerializable.md @@ -0,0 +1,79 @@ +--- +id: Unity.Netcode.FastBufferWriter.ForNetworkSerializable +title: Unity.Netcode.FastBufferWriter.ForNetworkSerializable +--- + +# Struct FastBufferWriter.ForNetworkSerializable + + +This empty struct exists to allow overloading WriteValue based on +generic constraints. At the bytecode level, constraints aren't included +in the method signature, so if multiple methods exist with the same +signature, it causes a compile error because they would end up being +emitted as the same method, even if the constraints are different. +Adding an empty struct with a default value gives them different +signatures in the bytecode, which then allows the compiler to do +overload resolution based on the generic constraints without the user +having to pass the struct in themselves. + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ForNetworkSerializable +``` + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForPrimitives.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForPrimitives.md new file mode 100644 index 000000000..f13ef9e15 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForPrimitives.md @@ -0,0 +1,79 @@ +--- +id: Unity.Netcode.FastBufferWriter.ForPrimitives +title: Unity.Netcode.FastBufferWriter.ForPrimitives +--- + +# Struct FastBufferWriter.ForPrimitives + + +This empty struct exists to allow overloading WriteValue based on +generic constraints. At the bytecode level, constraints aren't included +in the method signature, so if multiple methods exist with the same +signature, it causes a compile error because they would end up being +emitted as the same method, even if the constraints are different. +Adding an empty struct with a default value gives them different +signatures in the bytecode, which then allows the compiler to do +overload resolution based on the generic constraints without the user +having to pass the struct in themselves. + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ForPrimitives +``` + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForStructs.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForStructs.md new file mode 100644 index 000000000..97acaa0ef --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForStructs.md @@ -0,0 +1,79 @@ +--- +id: Unity.Netcode.FastBufferWriter.ForStructs +title: Unity.Netcode.FastBufferWriter.ForStructs +--- + +# Struct FastBufferWriter.ForStructs + + +This empty struct exists to allow overloading WriteValue based on +generic constraints. At the bytecode level, constraints aren't included +in the method signature, so if multiple methods exist with the same +signature, it causes a compile error because they would end up being +emitted as the same method, even if the constraints are different. +Adding an empty struct with a default value gives them different +signatures in the bytecode, which then allows the compiler to do +overload resolution based on the generic constraints without the user +having to pass the struct in themselves. + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ForStructs +``` + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.md new file mode 100644 index 000000000..4a1463397 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.FastBufferWriter.md @@ -0,0 +1,2864 @@ +--- +id: Unity.Netcode.FastBufferWriter +title: Unity.Netcode.FastBufferWriter +--- + +# Struct FastBufferWriter + + +Optimized class used for writing values into a byte stream +FastBufferReader BytePacker ByteUnpacker + + + + + + + +##### Implements + + + +System.IDisposable + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct FastBufferWriter : IDisposable +``` + + + +### Constructors + +#### FastBufferWriter(Int32, Allocator, Int32) + + +Create a FastBufferWriter. + + + + + + +##### Declaration + + +``` lang-csharp +public FastBufferWriter(int size, Allocator allocator, int maxSize = -1) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-----------|-----------------------------------------------------------------------------| +| System.Int32 | size | Size of the buffer to create | +| Allocator | allocator | Allocator to use in creating it | +| System.Int32 | maxSize | Maximum size the buffer can grow to. If less than size, buffer cannot grow. | + +### Properties + +#### Capacity + + +The current total buffer size + + + + + + +##### Declaration + + +``` lang-csharp +public readonly int Capacity { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### IsInitialized + + +Gets a value indicating whether the writer has been initialized and a +handle allocated. + + + + + + +##### Declaration + + +``` lang-csharp +public readonly bool IsInitialized { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### Length + + +The total amount of bytes that have been written to the stream + + + + + + +##### Declaration + + +``` lang-csharp +public readonly int Length { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### MaxCapacity + + +The maximum possible total buffer size + + + + + + +##### Declaration + + +``` lang-csharp +public readonly int MaxCapacity { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### Position + + +The current write position + + + + + + +##### Declaration + + +``` lang-csharp +public readonly int Position { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +### Methods + +#### CopyFrom(FastBufferWriter) + + +Copy the contents of another writer into this writer. The contents will +be copied from the beginning of the other writer to its current +position. They will be copied to this writer starting at this writer's +current position. + + + + + + +##### Declaration + + +``` lang-csharp +public void CopyFrom(FastBufferWriter other) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|-------|-------------------| +| FastBufferWriter | other | Writer to copy to | + +#### CopyTo(FastBufferWriter) + + +Copy the contents of this writer into another writer. The contents will +be copied from the beginning of this writer to its current position. +They will be copied to the other writer starting at the other writer's +current position. + + + + + + +##### Declaration + + +``` lang-csharp +public void CopyTo(FastBufferWriter other) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|-------|-------------------| +| FastBufferWriter | other | Writer to copy to | + +#### Dispose() + + +System.IDisposable implementation that frees the allocated buffer + + + + + + +##### Declaration + + +``` lang-csharp +public void Dispose() +``` + + + +#### EnterBitwiseContext() + + +Retrieve a BitWriter to be able to perform bitwise operations on the +buffer. No bytewise operations can be performed on the buffer until +bitWriter.Dispose() has been called. At the end of the operation, +FastBufferWriter will remain byte-aligned. + + + + + + +##### Declaration + + +``` lang-csharp +public BitWriter EnterBitwiseContext() +``` + + + +##### Returns + +| Type | Description | +|-----------|-------------| +| BitWriter | A BitWriter | + +#### GetUnsafePtr() + + +Gets a direct pointer to the underlying buffer + + + + + + +##### Declaration + + +``` lang-csharp +public byte *GetUnsafePtr() +``` + + + +##### Returns + +| Type | Description | +|---------------|-------------| +| System.Byte\* | | + +#### GetUnsafePtrAtCurrentPosition() + + +Gets a direct pointer to the underlying buffer at the current read +position + + + + + + +##### Declaration + + +``` lang-csharp +public byte *GetUnsafePtrAtCurrentPosition() +``` + + + +##### Returns + +| Type | Description | +|---------------|-------------| +| System.Byte\* | | + +#### GetWriteSize(String, Boolean) + + +Get the required size to write a string + + + + + + +##### Declaration + + +``` lang-csharp +public static int GetWriteSize(string s, bool oneByteChars = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------|--------------------------------------------------------------------------| +| System.String | s | The string to write | +| System.Boolean | oneByteChars | Whether or not to use one byte per character. This will only allow ASCII | + +##### Returns + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### GetWriteSize\() + + +Get the size required to write an unmanaged value of type T + + + + + + +##### Declaration + + +``` lang-csharp +public static int GetWriteSize() + where T : struct +``` + + + +##### Returns + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +##### Type Parameters + +| Name | Description | +|------|-------------| +| T | | + +#### GetWriteSize\(in T) + + +Get the write size for a FixedString + + + + + + +##### Declaration + + +``` lang-csharp +public static int GetWriteSize(in T value) + where T : struct, INativeList, IUTF8Bytes +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|-------------| +| T | value | | + +##### Returns + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +##### Type Parameters + +| Name | Description | +|------|-------------| +| T | | + +#### GetWriteSize\(in T, FastBufferWriter.ForStructs) + + +Get the write size for any general unmanaged value The ForStructs value +here makes this the lowest-priority overload so other versions will be +prioritized over this if they match + + + + + + +##### Declaration + + +``` lang-csharp +public static int GetWriteSize(in T value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|-------------| +| T | value | | +| FastBufferWriter.ForStructs | unused | | + +##### Returns + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +##### Type Parameters + +| Name | Description | +|------|-------------| +| T | | + +#### GetWriteSize\(T\[\], Int32, Int32) + + +Get the required size to write an unmanaged array + + + + + + +##### Declaration + + +``` lang-csharp +public static int GetWriteSize(T[] array, int count = -1, int offset = 0) + where T : struct +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|--------|---------------------------------| +| T\[\] | array | The array to write | +| System.Int32 | count | The amount of elements to write | +| System.Int32 | offset | Where in the array to start | + +##### Returns + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +##### Type Parameters + +| Name | Description | +|------|-------------| +| T | | + +#### Seek(Int32) + + +Move the write position in the stream. Note that moving forward past the +current length will extend the buffer's Length value even if you don't +write. + + + + + + +##### Declaration + + +``` lang-csharp +public void Seek(int where) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------|---------------------------------------------------------------| +| System.Int32 | where | Absolute value to move the position to, truncated to Capacity | + +#### ToArray() + + +Returns an array representation of the underlying byte buffer. +!!Allocates a new array!! + + + + + + +##### Declaration + + +``` lang-csharp +public byte[] ToArray() +``` + + + +##### Returns + +| Type | Description | +|-----------------|-------------| +| System.Byte\[\] | | + +#### Truncate(Int32) + + +Truncate the stream by setting Length to the specified value. If +Position is greater than the specified value, it will be moved as well. + + + + + + +##### Declaration + + +``` lang-csharp +public void Truncate(int where = -1) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------|---------------------------------------------------------------------| +| System.Int32 | where | The value to truncate to. If -1, the current position will be used. | + +#### TryBeginWrite(Int32) + + +Allows faster serialization by batching bounds checking. When you know +you will be writing multiple fields back-to-back and you know the total +size, you can call TryBeginWrite() once on the total size, and then +follow it with calls to WriteValue() instead of WriteValueSafe() for +faster serialization. + +Unsafe write operations will throw OverflowException in editor and +development builds if you go past the point you've marked using +TryBeginWrite(). In release builds, OverflowException will not be thrown +for performance reasons, since the point of using TryBeginWrite is to +avoid bounds checking in the following operations in release builds. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TryBeginWrite(int bytes) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------|--------------------------| +| System.Int32 | bytes | Amount of bytes to write | + +##### Returns + +| Type | Description | +|----------------|-----------------------------------------------| +| System.Boolean | True if the write is allowed, false otherwise | + +##### Exceptions + +| Type | Condition | +|----------------------------------|--------------------------------------| +| System.InvalidOperationException | If called while in a bitwise context | + +#### TryBeginWriteInternal(Int32) + + +Internal version of TryBeginWrite. Differs from TryBeginWrite only in +that it won't ever move the AllowedWriteMark backward. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TryBeginWriteInternal(int bytes) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------|-------------| +| System.Int32 | bytes | | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +##### Exceptions + +| Type | Condition | +|----------------------------------|-----------| +| System.InvalidOperationException | | + +#### TryBeginWriteValue\(in T) + + +Allows faster serialization by batching bounds checking. When you know +you will be writing multiple fields back-to-back and you know the total +size, you can call TryBeginWrite() once on the total size, and then +follow it with calls to WriteValue() instead of WriteValueSafe() for +faster serialization. + +Unsafe write operations will throw OverflowException in editor and +development builds if you go past the point you've marked using +TryBeginWrite(). In release builds, OverflowException will not be thrown +for performance reasons, since the point of using TryBeginWrite is to +avoid bounds checking in the following operations in release builds. +Instead, attempting to write past the marked position in release builds +will write to random memory and cause undefined behavior, likely +including instability and crashes. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TryBeginWriteValue(in T value) + where T : struct +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|---------------------------------------------| +| T | value | The value of the type `T` you want to write | + +##### Returns + +| Type | Description | +|----------------|-----------------------------------------------| +| System.Boolean | True if the write is allowed, false otherwise | + +##### Type Parameters + +| Name | Description | +|------|-------------------------| +| T | The value type to write | + +##### Exceptions + +| Type | Condition | +|----------------------------------|--------------------------------------| +| System.InvalidOperationException | If called while in a bitwise context | + +#### WriteByte(Byte) + + +Write a byte to the stream. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteByte(byte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|----------------| +| System.Byte | value | Value to write | + +#### WriteBytes(Byte\*, Int32, Int32) + + +Write multiple bytes to the stream + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteBytes(byte *value, int size, int offset = 0) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|--------|-----------------------------------------| +| System.Byte\* | value | Value to write | +| System.Int32 | size | Number of bytes to write | +| System.Int32 | offset | Offset into the buffer to begin writing | + +#### WriteBytes(Byte\[\], Int32, Int32) + + +Write multiple bytes to the stream + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteBytes(byte[] value, int size = -1, int offset = 0) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------|--------|-----------------------------------------| +| System.Byte\[\] | value | Value to write | +| System.Int32 | size | Number of bytes to write | +| System.Int32 | offset | Offset into the buffer to begin writing | + +#### WriteByteSafe(Byte) + + +Write a byte to the stream. + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteByteSafe(byte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|----------------| +| System.Byte | value | Value to write | + +#### WriteBytesSafe(Byte\*, Int32, Int32) + + +Write multiple bytes to the stream + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteBytesSafe(byte *value, int size, int offset = 0) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|--------|-----------------------------------------| +| System.Byte\* | value | Value to write | +| System.Int32 | size | Number of bytes to write | +| System.Int32 | offset | Offset into the buffer to begin writing | + +#### WriteBytesSafe(Byte\[\], Int32, Int32) + + +Write multiple bytes to the stream + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteBytesSafe(byte[] value, int size = -1, int offset = 0) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------|--------|-----------------------------------------| +| System.Byte\[\] | value | Value to write | +| System.Int32 | size | Number of bytes to write | +| System.Int32 | offset | Offset into the buffer to begin writing | + +#### WriteNetworkSerializable\(in T) + + +Write an INetworkSerializable + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteNetworkSerializable(in T value) + where T : INetworkSerializable +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|--------------------| +| T | value | The value to write | + +##### Type Parameters + +| Name | Description | +|------|-------------| +| T | | + +#### WriteNetworkSerializable\(T\[\], Int32, Int32) + + +Write an array of INetworkSerializables + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteNetworkSerializable(T[] array, int count = -1, int offset = 0) + where T : INetworkSerializable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|--------|--------------------| +| T\[\] | array | The value to write | +| System.Int32 | count | | +| System.Int32 | offset | | + +##### Type Parameters + +| Name | Description | +|------|-------------| +| T | | + +#### WritePartialValue\(T, Int32, Int32) + + +Write a partial value. The specified number of bytes is written from the +value and the rest is ignored. + + + + + + +##### Declaration + + +``` lang-csharp +public void WritePartialValue(T value, int bytesToWrite, int offsetBytes = 0) + where T : struct +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|--------------|--------------------------------------------------| +| T | value | Value to write | +| System.Int32 | bytesToWrite | Number of bytes | +| System.Int32 | offsetBytes | Offset into the value to begin reading the bytes | + +##### Type Parameters + +| Name | Description | +|------|-------------| +| T | | + +##### Exceptions + +| Type | Condition | +|----------------------------------|-----------| +| System.InvalidOperationException | | +| System.OverflowException | | + +#### WriteValue(in Color) + + +Write a Color + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in Color value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|--------------------| +| Color | value | the value to write | + +#### WriteValue(Color\[\]) + + +Write a Color array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(Color[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|---------------------| +| Color\[\] | value | the values to write | + +#### WriteValue(in Color32) + + +Write a Color32 + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in Color32 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------| +| Color32 | value | the value to write | + +#### WriteValue(Color32\[\]) + + +Write a Color32 array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(Color32[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|---------------------| +| Color32\[\] | value | the values to write | + +#### WriteValue(in Quaternion) + + +Write a Quaternion + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in Quaternion value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|--------------------| +| Quaternion | value | the value to write | + +#### WriteValue(Quaternion\[\]) + + +Write a Quaternion array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(Quaternion[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|---------------------| +| Quaternion\[\] | value | the values to write | + +#### WriteValue(in Ray) + + +Write a Ray + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in Ray value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|--------------------| +| Ray | value | the value to write | + +#### WriteValue(Ray\[\]) + + +Write a Ray array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(Ray[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|---------------------| +| Ray\[\] | value | the values to write | + +#### WriteValue(in Ray2D) + + +Write a Ray2D + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in Ray2D value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|--------------------| +| Ray2D | value | the value to write | + +#### WriteValue(Ray2D\[\]) + + +Write a Ray2D array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(Ray2D[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|---------------------| +| Ray2D\[\] | value | the values to write | + +#### WriteValue(String, Boolean) + + +Writes a string + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(string s, bool oneByteChars = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------|--------------------------------------------------------------------------| +| System.String | s | The string to write | +| System.Boolean | oneByteChars | Whether or not to use one byte per character. This will only allow ASCII | + +#### WriteValue(in Vector2) + + +Write a Vector2 + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in Vector2 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------| +| Vector2 | value | the value to write | + +#### WriteValue(Vector2\[\]) + + +Write a Vector2 array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(Vector2[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|---------------------| +| Vector2\[\] | value | the values to write | + +#### WriteValue(in Vector2Int) + + +Write a Vector2Int + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in Vector2Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|--------------------| +| Vector2Int | value | the value to write | + +#### WriteValue(Vector2Int\[\]) + + +Write a Vector2Int array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(Vector2Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|---------------------| +| Vector2Int\[\] | value | the values to write | + +#### WriteValue(in Vector3) + + +Write a Vector3 + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in Vector3 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------| +| Vector3 | value | the value to write | + +#### WriteValue(Vector3\[\]) + + +Write a Vector3 array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(Vector3[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|---------------------| +| Vector3\[\] | value | the values to write | + +#### WriteValue(in Vector3Int) + + +Write a Vector3Int + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in Vector3Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|--------------------| +| Vector3Int | value | the value to write | + +#### WriteValue(Vector3Int\[\]) + + +Write a Vector3Int array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(Vector3Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------| +| Vector3Int\[\] | value | the value to write | + +#### WriteValue(in Vector4) + + +Write a Vector4 + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in Vector4 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------| +| Vector4 | value | the value to write | + +#### WriteValue(Vector4\[\]) + + +Write a Vector4 + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(Vector4[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|---------------------| +| Vector4\[\] | value | the values to write | + +#### WriteValue\(in T, FastBufferWriter.ForEnums) + + +Write an enum value + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in T value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to write | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValue\(in T, FastBufferWriter.ForFixedStrings) + + +Write a FixedString value. Writes only the part of the string that's +actually used. When calling TryBeginWrite, ensure you calculate the +write size correctly (preferably by calling +FastBufferWriter.GetWriteSize()) + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in T value, FastBufferWriter.ForFixedStrings unused = default(FastBufferWriter.ForFixedStrings)) + where T : struct, INativeList, IUTF8Bytes +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | the value to write | +| FastBufferWriter.ForFixedStrings | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValue\(in T, FastBufferWriter.ForNetworkSerializable) + + +Write a NetworkSerializable value + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in T value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to write | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValue\(in T, FastBufferWriter.ForPrimitives) + + +Write a primitive value (int, bool, etc) Accepts any value that +implements the given interfaces, but is not guaranteed to work correctly +on values that are not primitives. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in T value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValue\(in T, FastBufferWriter.ForStructs) + + +Write a struct + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(in T value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to write | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValue\(T\[\], FastBufferWriter.ForEnums) + + +Write an enum array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(T[] value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to write | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValue\(T\[\], FastBufferWriter.ForNetworkSerializable) + + +Write a NetworkSerializable array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(T[] value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to write | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValue\(T\[\], FastBufferWriter.ForPrimitives) + + +Write a primitive value array (int, bool, etc) Accepts any value that +implements the given interfaces, but is not guaranteed to work correctly +on values that are not primitives. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(T[] value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValue\(T\[\], FastBufferWriter.ForStructs) + + +Write a struct array + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValue(T[] value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to write | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValueSafe(in Color) + + +Write a Color + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in Color value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|--------------------| +| Color | value | the value to write | + +#### WriteValueSafe(Color\[\]) + + +Write a Collor array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(Color[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|---------------------| +| Color\[\] | value | the values to write | + +#### WriteValueSafe(in Color32) + + +Write a Color32 + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in Color32 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------| +| Color32 | value | the value to write | + +#### WriteValueSafe(Color32\[\]) + + +Write a Color32 array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(Color32[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|---------------------| +| Color32\[\] | value | the values to write | + +#### WriteValueSafe(in Quaternion) + + +Write a Quaternion + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in Quaternion value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|--------------------| +| Quaternion | value | the value to write | + +#### WriteValueSafe(Quaternion\[\]) + + +Write a Quaternion array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(Quaternion[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|---------------------| +| Quaternion\[\] | value | the values to write | + +#### WriteValueSafe(in Ray) + + +Write a Ray + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in Ray value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|--------------------| +| Ray | value | the value to write | + +#### WriteValueSafe(Ray\[\]) + + +Write a Ray array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(Ray[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|---------------------| +| Ray\[\] | value | the values to write | + +#### WriteValueSafe(in Ray2D) + + +Write a Ray2D + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in Ray2D value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|--------------------| +| Ray2D | value | the value to write | + +#### WriteValueSafe(Ray2D\[\]) + + +Write a Ray2D array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(Ray2D[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|---------------------| +| Ray2D\[\] | value | the values to write | + +#### WriteValueSafe(String, Boolean) + + +Writes a string + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(string s, bool oneByteChars = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------|--------------------------------------------------------------------------| +| System.String | s | The string to write | +| System.Boolean | oneByteChars | Whether or not to use one byte per character. This will only allow ASCII | + +#### WriteValueSafe(in Vector2) + + +Write a Vector2 + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in Vector2 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------| +| Vector2 | value | the value to write | + +#### WriteValueSafe(Vector2\[\]) + + +Write a Vector2 array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(Vector2[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|---------------------| +| Vector2\[\] | value | the values to write | + +#### WriteValueSafe(in Vector2Int) + + +Write a Vector2Int + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in Vector2Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|--------------------| +| Vector2Int | value | the value to write | + +#### WriteValueSafe(Vector2Int\[\]) + + +Write a Vector2Int array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(Vector2Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|---------------------| +| Vector2Int\[\] | value | the values to write | + +#### WriteValueSafe(in Vector3) + + +Write a Vector3 + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in Vector3 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------| +| Vector3 | value | the value to write | + +#### WriteValueSafe(Vector3\[\]) + + +Write a Vector3 array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(Vector3[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|---------------------| +| Vector3\[\] | value | the values to write | + +#### WriteValueSafe(in Vector3Int) + + +Write a Vector3Int + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in Vector3Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|--------------------| +| Vector3Int | value | the value to write | + +#### WriteValueSafe(Vector3Int\[\]) + + +Write a Vector3Int array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(Vector3Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|---------------------| +| Vector3Int\[\] | value | the values to write | + +#### WriteValueSafe(in Vector4) + + +Write a Vector4 + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in Vector4 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------| +| Vector4 | value | the value to write | + +#### WriteValueSafe(Vector4\[\]) + + +Write a Vector4 array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(Vector4[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|---------------------| +| Vector4\[\] | value | the values to write | + +#### WriteValueSafe\(in T, FastBufferWriter.ForEnums) + + +Write an enum value + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in T value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to write | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValueSafe\(in T, FastBufferWriter.ForFixedStrings) + + +Write a FixedString value. Writes only the part of the string that's +actually used. + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in T value, FastBufferWriter.ForFixedStrings unused = default(FastBufferWriter.ForFixedStrings)) + where T : struct, INativeList, IUTF8Bytes +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | the value to write | +| FastBufferWriter.ForFixedStrings | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValueSafe\(in T, FastBufferWriter.ForNetworkSerializable) + + +Write a NetworkSerializable value + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in T value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to write | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValueSafe\(in T, FastBufferWriter.ForPrimitives) + + +Write a primitive value (int, bool, etc) Accepts any value that +implements the given interfaces, but is not guaranteed to work correctly +on values that are not primitives. + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in T value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValueSafe\(in T, FastBufferWriter.ForStructs) + + +Write a struct + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(in T value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to write | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValueSafe\(T\[\], FastBufferWriter.ForEnums) + + +Write an enum array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(T[] value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to write | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValueSafe\(T\[\], FastBufferWriter.ForNetworkSerializable) + + +Write a NetworkSerializable array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(T[] value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to write | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValueSafe\(T\[\], FastBufferWriter.ForPrimitives) + + +Write a primitive value (int, bool, etc) Accepts any value that +implements the given interfaces, but is not guaranteed to work correctly +on values that are not primitives. + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(T[] value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The value to write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### WriteValueSafe\(T\[\], FastBufferWriter.ForStructs) + + +Write a struct array + +"Safe" version - automatically performs bounds checking. Less efficient +than bounds checking for multiple writes at once by calling +TryBeginWrite. + + + + + + +##### Declaration + + +``` lang-csharp +public void WriteValueSafe(T[] value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to write | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +### Implements + + + +System.IDisposable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.ForceNetworkSerializeByMemcpy-1.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.ForceNetworkSerializeByMemcpy-1.md new file mode 100644 index 000000000..8cc74cd3c --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.ForceNetworkSerializeByMemcpy-1.md @@ -0,0 +1,323 @@ +--- +id: Unity.Netcode.ForceNetworkSerializeByMemcpy-1 +title: Unity.Netcode.ForceNetworkSerializeByMemcpy-1 +--- + +# Struct ForceNetworkSerializeByMemcpy\ + + +This is a wrapper that adds `INetworkSerializeByMemcpy` support to +existing structs that the developer doesn't have the ability to modify +(for example, external structs like `Guid`). + + + + + + + +##### Implements + + + +INetworkSerializeByMemcpy + + + + + +System.IEquatable\\> + + + + + + +##### Inherited Members + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ForceNetworkSerializeByMemcpy : INetworkSerializeByMemcpy, IEquatable> where T : struct, IEquatable +``` + + + +##### Type Parameters + +| Name | Description | +|------|-------------| +| T | | + +### Constructors + +#### ForceNetworkSerializeByMemcpy(T) + + +The default constructor for ForceNetworkSerializeByMemcpy\ + + + + + + +##### Declaration + + +``` lang-csharp +public ForceNetworkSerializeByMemcpy(T value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|------------------------------------| +| T | value | sets the initial value of type `T` | + +### Fields + +#### Value + + +The wrapped value + + + + + + +##### Declaration + + +``` lang-csharp +public T Value +``` + + + +##### Field Value + +| Type | Description | +|------|-------------| +| T | | + +### Methods + +#### Equals(Object) + + +Check if this value is equal to a boxed object value + + + + + + +##### Declaration + + +``` lang-csharp +public override bool Equals(object obj) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|------|----------------------------------| +| System.Object | obj | The boxed value to check against | + +##### Returns + +| Type | Description | +|----------------|---------------| +| System.Boolean | true if equal | + +##### Overrides + + + +System.ValueType.Equals(System.Object) + + + +#### Equals(ForceNetworkSerializeByMemcpy\) + + +Check if wrapped values are equal + + + + + + +##### Declaration + + +``` lang-csharp +public bool Equals(ForceNetworkSerializeByMemcpy other) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------------------|-------|---------------| +| ForceNetworkSerializeByMemcpy\ | other | Other wrapper | + +##### Returns + +| Type | Description | +|----------------|---------------| +| System.Boolean | true if equal | + +#### GetHashCode() + + +Obtains the wrapped value's hash code + + + + + + +##### Declaration + + +``` lang-csharp +public override int GetHashCode() +``` + + + +##### Returns + +| Type | Description | +|--------------|---------------------------| +| System.Int32 | Wrapped value's hash code | + +##### Overrides + + + +System.ValueType.GetHashCode() + + + +### Operators + +#### Implicit(T to ForceNetworkSerializeByMemcpy\) + + +Convert implicitly from a T value to a ForceNetworkSerializeByMemcpy +wrapper + + + + + + +##### Declaration + + +``` lang-csharp +public static implicit operator ForceNetworkSerializeByMemcpy(T underlyingValue) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-----------------|-------------| +| T | underlyingValue | the value | + +##### Returns + +| Type | Description | +|------------------------------------|---------------| +| ForceNetworkSerializeByMemcpy\ | a new wrapper | + +#### Implicit(ForceNetworkSerializeByMemcpy\ to T) + + +Convert implicitly from the ForceNetworkSerializeByMemcpy wrapper to the +underlying value + + + + + + +##### Declaration + + +``` lang-csharp +public static implicit operator T(ForceNetworkSerializeByMemcpy container) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------------------|-----------|-------------| +| ForceNetworkSerializeByMemcpy\ | container | The wrapper | + +##### Returns + +| Type | Description | +|------|----------------------| +| T | The underlying value | + +### Implements + + + +INetworkSerializeByMemcpy + + + + + +System.IEquatable\ + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.HashSize.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.HashSize.md new file mode 100644 index 000000000..7dd66c93a --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.HashSize.md @@ -0,0 +1,52 @@ +--- +id: Unity.Netcode.HashSize +title: Unity.Netcode.HashSize +--- + +# Enum HashSize + + +Represents the length of a var int encoded hash Note that the HashSize +does not say anything about the actual final output due to the var int +encoding It just says how many bytes the maximum will be + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum HashSize : byte +``` + + + +### Fields + +Name + + + + + + + + + +Description + +VarIntEightBytes + +Eight byte hash + +VarIntFourBytes + +Four byte hash + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkPrefabInstanceHandler.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkPrefabInstanceHandler.md new file mode 100644 index 000000000..08b70bc48 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkPrefabInstanceHandler.md @@ -0,0 +1,114 @@ +--- +id: Unity.Netcode.INetworkPrefabInstanceHandler +title: Unity.Netcode.INetworkPrefabInstanceHandler +--- + +# Interface INetworkPrefabInstanceHandler + + +Interface for customizing, overriding, spawning, and destroying Network +Prefabs Used by NetworkPrefabHandler + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public interface INetworkPrefabInstanceHandler +``` + + + +### Methods + +#### Destroy(NetworkObject) + + +Invoked on Client and Server Once an implementation is registered with +the NetworkPrefabHandler, this method will be called when a Network +Prefab associated NetworkObject is: + +Server Side: destroyed or despawned with the destroy parameter equal to +true If Despawn(Boolean) is invoked with the default destroy parameter +(i.e. false) then this method will NOT be invoked! + +Client Side: destroyed when the client receives a destroy object message +from the server or host. + +Note on Pooling: When this method is invoked, you do not need to destroy +the NetworkObject as long as you want your pool to persist. The most +common approach is to make the NetworkObject inactive by calling . + + + + + + +##### Declaration + + +``` lang-csharp +void Destroy(NetworkObject networkObject) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|-----------------------------------| +| NetworkObject | networkObject | The NetworkObject being destroyed | + +#### Instantiate(UInt64, Vector3, Quaternion) + + +Client Side Only Once an implementation is registered with the +NetworkPrefabHandler, this method will be called every time a Network +Prefab associated NetworkObject is spawned on clients + +Note On Hosts: Use the RegisterHostGlobalObjectIdHashValues(GameObject, +List\) method to register all targeted NetworkPrefab +overrides manually since the host will be acting as both a server and +client. + +Note on Pooling: If you are using a NetworkObject pool, don't forget to +make the NetworkObject active via the method. + + + + + + +##### Declaration + + +``` lang-csharp +NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaternion rotation) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|-----------------------------------------------------------------------| +| System.UInt64 | ownerClientId | the owner for the NetworkObject to be instantiated | +| Vector3 | position | the initial/default position for the NetworkObject to be instantiated | +| Quaternion | rotation | the initial/default rotation for the NetworkObject to be instantiated | + +##### Returns + +| Type | Description | +|---------------|-------------| +| NetworkObject | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkSerializable.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkSerializable.md new file mode 100644 index 000000000..4f666846e --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkSerializable.md @@ -0,0 +1,65 @@ +--- +id: Unity.Netcode.INetworkSerializable +title: Unity.Netcode.INetworkSerializable +--- + +# Interface INetworkSerializable + + +Interface for implementing custom serializable types. + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public interface INetworkSerializable +``` + + + +### Methods + +#### NetworkSerialize\(BufferSerializer\) + + +Provides bi-directional serialization to read and write the desired data +to serialize this type. + + + + + + +##### Declaration + + +``` lang-csharp +void NetworkSerialize(BufferSerializer serializer) + where T : IReaderWriter +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------|------------|---------------------------------------------------| +| BufferSerializer\ | serializer | The serializer to use to read and write the data. | + +##### Type Parameters + +| Name | Description | +|------|--------------------------------------------------------------------------------------------------------------------------| +| T | Either BufferSerializerReader or BufferSerializerWriter, depending whether the serializer is in read mode or write mode. | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkSerializeByMemcpy.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkSerializeByMemcpy.md new file mode 100644 index 000000000..05d939cf4 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkSerializeByMemcpy.md @@ -0,0 +1,37 @@ +--- +id: Unity.Netcode.INetworkSerializeByMemcpy +title: Unity.Netcode.INetworkSerializeByMemcpy +--- + +# Interface INetworkSerializeByMemcpy + + +This interface is a "tag" that can be applied to a struct to mark that +struct as being serializable by memcpy. It's up to the developer of the +struct to analyze the struct's contents and ensure it is actually +serializable by memcpy. This requires all of the members of the struct +to be `unmanaged` Plain-Old-Data values - if your struct contains a +pointer (or a type that contains a pointer, like `NativeList<T>`), it +should be serialized via `INetworkSerializable` or via +`FastBufferReader`/`FastBufferWriter` extension methods. + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public interface INetworkSerializeByMemcpy +``` + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkUpdateSystem.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkUpdateSystem.md new file mode 100644 index 000000000..7199ac02e --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.INetworkUpdateSystem.md @@ -0,0 +1,87 @@ +--- +id: Unity.Netcode.INetworkUpdateSystem +title: Unity.Netcode.INetworkUpdateSystem +--- + +# Interface INetworkUpdateSystem + + +Defines the required interface of a network update system being executed +by the NetworkUpdateLoop. + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public interface INetworkUpdateSystem +``` + + + +### Methods + +#### NetworkUpdate(NetworkUpdateStage) + + +The update method that is being executed in the context of related +NetworkUpdateStage. + + + + + + +##### Declaration + + +``` lang-csharp +void NetworkUpdate(NetworkUpdateStage updateStage) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------|-------------|------------------------------------------------| +| NetworkUpdateStage | updateStage | The NetworkUpdateStage that is being executed. | + +### Extension Methods + + + +NetworkUpdateLoop.RegisterAllNetworkUpdates(INetworkUpdateSystem) + + + + + +NetworkUpdateLoop.RegisterNetworkUpdate(INetworkUpdateSystem, +NetworkUpdateStage) + + + + + +NetworkUpdateLoop.UnregisterAllNetworkUpdates(INetworkUpdateSystem) + + + + + +NetworkUpdateLoop.UnregisterNetworkUpdate(INetworkUpdateSystem, +NetworkUpdateStage) + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.IReaderWriter.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.IReaderWriter.md new file mode 100644 index 000000000..a9bc4916d --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.IReaderWriter.md @@ -0,0 +1,1958 @@ +--- +id: Unity.Netcode.IReaderWriter +title: Unity.Netcode.IReaderWriter +--- + +# Interface IReaderWriter + + +Interface for an implementation of one side of a two-way serializer + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public interface IReaderWriter +``` + + + +### Properties + +#### IsReader + + +Check whether this implementation is a "reader" - if it's been +constructed to deserialize data + + + + + + +##### Declaration + + +``` lang-csharp +bool IsReader { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsWriter + + +Check whether this implementation is a "writer" - if it's been +constructed to serialize data + + + + + + +##### Declaration + + +``` lang-csharp +bool IsWriter { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +### Methods + +#### GetFastBufferReader() + + +Get the underlying FastBufferReader struct. Only valid when IsReader == +true + + + + + + +##### Declaration + + +``` lang-csharp +FastBufferReader GetFastBufferReader() +``` + + + +##### Returns + +| Type | Description | +|------------------|-----------------------------| +| FastBufferReader | underlying FastBufferReader | + +#### GetFastBufferWriter() + + +Get the underlying FastBufferWriter struct. Only valid when IsWriter == +true + + + + + + +##### Declaration + + +``` lang-csharp +FastBufferWriter GetFastBufferWriter() +``` + + + +##### Returns + +| Type | Description | +|------------------|-----------------------------| +| FastBufferWriter | underlying FastBufferWriter | + +#### PreCheck(Int32) + + +Performs an advance check to ensure space is available to read/write one +or more values. This provides a performance benefit for serializing +multiple values using the SerializeValuePreChecked methods. But note +that the benefit is small and only likely to be noticeable if +serializing a very large number of items. + + + + + + +##### Declaration + + +``` lang-csharp +bool PreCheck(int amount) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|--------|-------------| +| System.Int32 | amount | | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### SerializeNetworkSerializable\(ref T) + + +Read or write a NetworkSerializable value. SerializeValue() is the +preferred method to do this - this is provided for backward +compatibility only. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeNetworkSerializable(ref T value) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|-------------------------| +| T | value | The value to read/write | + +##### Type Parameters + +| Name | Description | +|------|-------------------------------| +| T | The network serializable type | + +#### SerializeValue(ref Color) + + +Read or write a Color value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Color value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------------| +| Color | value | The value to read/write | + +#### SerializeValue(ref Color\[\]) + + +Read or write an array of Color values + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Color[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|--------------------------| +| Color\[\] | value | The values to read/write | + +#### SerializeValue(ref Color32) + + +Read or write a Color32 value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Color32 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Color32 | value | The value to read/write | + +#### SerializeValue(ref Color32\[\]) + + +Read or write an array of Color32 values + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Color32[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Color32\[\] | value | The values to read/write | + +#### SerializeValue(ref Quaternion) + + +Read or write a Quaternion value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Quaternion value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Quaternion | value | The value to read/write | + +#### SerializeValue(ref Quaternion\[\]) + + +Read or write an array of Quaternion values + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Quaternion[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------------| +| Quaternion\[\] | value | The values to read/write | + +#### SerializeValue(ref Ray) + + +Read or write a Ray value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Ray value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|-------------------------| +| Ray | value | The value to read/write | + +#### SerializeValue(ref Ray\[\]) + + +Read or write an array of Ray values + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Ray[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|--------------------------| +| Ray\[\] | value | The values to read/write | + +#### SerializeValue(ref Ray2D) + + +Read or write a Ray2D value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Ray2D value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------------| +| Ray2D | value | The value to read/write | + +#### SerializeValue(ref Ray2D\[\]) + + +Read or write an array of Ray2D values + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Ray2D[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|--------------------------| +| Ray2D\[\] | value | The values to read/write | + +#### SerializeValue(ref Byte) + + +Read or write a single byte + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref byte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|-------------------------| +| System.Byte | value | The value to read/write | + +#### SerializeValue(ref String, Boolean) + + +Read or write a string + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref string s, bool oneByteChars = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------|------------------------------------------------------------------| +| System.String | s | The value to read/write | +| System.Boolean | oneByteChars | If true, characters will be limited to one-byte ASCII characters | + +#### SerializeValue(ref Vector2) + + +Read or write a Vector2 value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Vector2 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector2 | value | The value to read/write | + +#### SerializeValue(ref Vector2\[\]) + + +Read or write an array of Vector2 values + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Vector2[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Vector2\[\] | value | The values to read/write | + +#### SerializeValue(ref Vector2Int) + + +Read or write a Vector2Int value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Vector2Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Vector2Int | value | The value to read/write | + +#### SerializeValue(ref Vector2Int\[\]) + + +Read or write an array of Vector2Int values + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Vector2Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------------| +| Vector2Int\[\] | value | The values to read/write | + +#### SerializeValue(ref Vector3) + + +Read or write a Vector3 value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Vector3 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector3 | value | The value to read/write | + +#### SerializeValue(ref Vector3\[\]) + + +Read or write an array of Vector3 values + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Vector3[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Vector3\[\] | value | The values to read/write | + +#### SerializeValue(ref Vector3Int) + + +Read or write a Vector3Int value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Vector3Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Vector3Int | value | The value to read/write | + +#### SerializeValue(ref Vector3Int\[\]) + + +Read or write an array of Vector3Int values + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Vector3Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------------| +| Vector3Int\[\] | value | The values to read/write | + +#### SerializeValue(ref Vector4) + + +Read or write a Vector4 value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Vector4 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector4 | value | The value to read/write | + +#### SerializeValue(ref Vector4\[\]) + + +Read or write an array of Vector4 values + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref Vector4[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Vector4\[\] | value | The values to read/write | + +#### SerializeValue\(ref T, FastBufferWriter.ForEnums) + + +Read or write an enum value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref T value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T, FastBufferWriter.ForFixedStrings) + + +Read or write a FixedString value + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref T value, FastBufferWriter.ForFixedStrings unused = default(FastBufferWriter.ForFixedStrings)) + where T : struct, INativeList, IUTF8Bytes +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForFixedStrings | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T, FastBufferWriter.ForNetworkSerializable) + + +Read or write a struct or class value implementing INetworkSerializable + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref T value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T, FastBufferWriter.ForPrimitives) + + +Read or write a primitive value (int, bool, etc) Accepts any value that +implements the given interfaces, but is not guaranteed to work correctly +on values that are not primitives. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref T value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T, FastBufferWriter.ForStructs) + + +Read or write a struct value implementing ISerializeByMemcpy + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref T value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T\[\], FastBufferWriter.ForEnums) + + +Read or write an array of enum values + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref T[] value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The value to read/write | +| FastBufferWriter.ForEnums | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T\[\], FastBufferWriter.ForNetworkSerializable) + + +Read or write an array of struct or class values implementing +INetworkSerializable + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref T[] value, FastBufferWriter.ForNetworkSerializable unused = default(FastBufferWriter.ForNetworkSerializable)) + where T : INetworkSerializable, new() +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForNetworkSerializable | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T\[\], FastBufferWriter.ForPrimitives) + + +Read or write an array of primitive values (int, bool, etc) Accepts any +value that implements the given interfaces, but is not guaranteed to +work correctly on values that are not primitives. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref T[] value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValue\(ref T\[\], FastBufferWriter.ForStructs) + + +Read or write an array of struct values implementing ISerializeByMemcpy + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValue(ref T[] value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForStructs | unused | An unused parameter used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValuePreChecked(ref Color) + + +Serialize a Color, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Color value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------------| +| Color | value | The value to read/write | + +#### SerializeValuePreChecked(ref Color\[\]) + + +Serialize a Color array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Color[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|-------------------------| +| Color\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Color32) + + +Serialize a Color32, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Color32 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Color32 | value | The value to read/write | + +#### SerializeValuePreChecked(ref Color32\[\]) + + +Serialize a Color32 array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Color32[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|-------------------------| +| Color32\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Quaternion) + + +Serialize a Quaternion, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Quaternion value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Quaternion | value | The value to read/write | + +#### SerializeValuePreChecked(ref Quaternion\[\]) + + +Serialize a Quaternion array, "pre-checked", which skips buffer checks. +In debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Quaternion[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|-------------------------| +| Quaternion\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Ray) + + +Serialize a Ray, "pre-checked", which skips buffer checks. In debug and +editor builds, a check is made to ensure you've called "PreCheck" before +calling this. In release builds, calling this without calling "PreCheck" +may read or write past the end of the buffer, which will cause memory +corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Ray value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|-------|-------------------------| +| Ray | value | The value to read/write | + +#### SerializeValuePreChecked(ref Ray\[\]) + + +Serialize a Ray array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Ray[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Ray\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Ray2D) + + +Serialize a Ray2D, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Ray2D value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------------------| +| Ray2D | value | The value to read/write | + +#### SerializeValuePreChecked(ref Ray2D\[\]) + + +Serialize a Ray2D array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Ray2D[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------|-------|-------------------------| +| Ray2D\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Byte) + + +Serialize a byte, "pre-checked", which skips buffer checks. In debug and +editor builds, a check is made to ensure you've called "PreCheck" before +calling this. In release builds, calling this without calling "PreCheck" +may read or write past the end of the buffer, which will cause memory +corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref byte value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|-------------------------| +| System.Byte | value | The value to read/write | + +#### SerializeValuePreChecked(ref String, Boolean) + + +Serialize a string, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref string s, bool oneByteChars = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------|------------------------------------------------------------------| +| System.String | s | The value to read/write | +| System.Boolean | oneByteChars | If true, characters will be limited to one-byte ASCII characters | + +#### SerializeValuePreChecked(ref Vector2) + + +Serialize a Vector2, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Vector2 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector2 | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector2\[\]) + + +Serialize a Vector2 array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Vector2[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Vector2\[\] | value | The values to read/write | + +#### SerializeValuePreChecked(ref Vector2Int) + + +Serialize a Vector2Int, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Vector2Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Vector2Int | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector2Int\[\]) + + +Serialize a Vector2Int array, "pre-checked", which skips buffer checks. +In debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Vector2Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|--------------------------| +| Vector2Int\[\] | value | The values to read/write | + +#### SerializeValuePreChecked(ref Vector3) + + +Serialize a Vector3, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Vector3 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector3 | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector3\[\]) + + +Serialize a Vector3 array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Vector3[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|--------------------------| +| Vector3\[\] | value | The values to read/write | + +#### SerializeValuePreChecked(ref Vector3Int) + + +Serialize a Vector3Int, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Vector3Int value) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|-------|-------------------------| +| Vector3Int | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector3Int\[\]) + + +Serialize a Vector3Int array, "pre-checked", which skips buffer checks. +In debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Vector3Int[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|-------------------------| +| Vector3Int\[\] | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector4) + + +Serialize a Vector4, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Vector4 value) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------|-------|-------------------------| +| Vector4 | value | The value to read/write | + +#### SerializeValuePreChecked(ref Vector4\[\]) + + +Serialize a Vector4Array, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref Vector4[] value) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|-------|-------------------------| +| Vector4\[\] | value | The value to read/write | + +#### SerializeValuePreChecked\(ref T, FastBufferWriter.ForEnums) + + +Serialize an enum, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref T value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForEnums | unused | An unused parameter that can be used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValuePreChecked\(ref T, FastBufferWriter.ForFixedStrings) + + +Serialize a FixedString, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref T value, FastBufferWriter.ForFixedStrings unused = default(FastBufferWriter.ForFixedStrings)) + where T : struct, INativeList, IUTF8Bytes +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------------------|--------|----------------------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForFixedStrings | unused | An unused parameter that can be used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValuePreChecked\(ref T, FastBufferWriter.ForPrimitives) + + +Serialize a primitive, "pre-checked", which skips buffer checks. In +debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref T value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter that can be used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValuePreChecked\(ref T, FastBufferWriter.ForStructs) + + +Serialize a struct, "pre-checked", which skips buffer checks. In debug +and editor builds, a check is made to ensure you've called "PreCheck" +before calling this. In release builds, calling this without calling +"PreCheck" may read or write past the end of the buffer, which will +cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref T value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------------------| +| T | value | The value to read/write | +| FastBufferWriter.ForStructs | unused | An unused parameter that can be used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValuePreChecked\(ref T\[\], FastBufferWriter.ForEnums) + + +Serialize an array of enums, "pre-checked", which skips buffer checks. +In debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref T[] value, FastBufferWriter.ForEnums unused = default(FastBufferWriter.ForEnums)) + where T : struct, Enum +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|--------|----------------------------------------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForEnums | unused | An unused parameter that can be used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValuePreChecked\(ref T\[\], FastBufferWriter.ForPrimitives) + + +Serialize an array of primitives, "pre-checked", which skips buffer +checks. In debug and editor builds, a check is made to ensure you've +called "PreCheck" before calling this. In release builds, calling this +without calling "PreCheck" may read or write past the end of the buffer, +which will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref T[] value, FastBufferWriter.ForPrimitives unused = default(FastBufferWriter.ForPrimitives)) + where T : struct, IComparable, IConvertible, IComparable, IEquatable +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|--------|----------------------------------------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForPrimitives | unused | An unused parameter that can be used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + +#### SerializeValuePreChecked\(ref T\[\], FastBufferWriter.ForStructs) + + +Serialize an array of structs, "pre-checked", which skips buffer checks. +In debug and editor builds, a check is made to ensure you've called +"PreCheck" before calling this. In release builds, calling this without +calling "PreCheck" may read or write past the end of the buffer, which +will cause memory corruption and undefined behavior. + + + + + + +##### Declaration + + +``` lang-csharp +void SerializeValuePreChecked(ref T[] value, FastBufferWriter.ForStructs unused = default(FastBufferWriter.ForStructs)) + where T : struct, INetworkSerializeByMemcpy +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------|--------|----------------------------------------------------------------------------------------------------| +| T\[\] | value | The values to read/write | +| FastBufferWriter.ForStructs | unused | An unused parameter that can be used for enabling overload resolution based on generic constraints | + +##### Type Parameters + +| Name | Description | +|------|---------------------------| +| T | The type being serialized | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.InvalidChannelException.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.InvalidChannelException.md new file mode 100644 index 000000000..7329b646f --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.InvalidChannelException.md @@ -0,0 +1,216 @@ +--- +id: Unity.Netcode.InvalidChannelException +title: Unity.Netcode.InvalidChannelException +--- + +# Class InvalidChannelException + + +Exception thrown when a specified network channel is invalid + + + + + + + +##### Inheritance + + +System.Object + + + + +System.Exception + + + + +InvalidChannelException + + + + + + +##### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + + +##### Inherited Members + + + +System.Exception.GetBaseException() + + + + + +System.Exception.GetObjectData(System.Runtime.Serialization.SerializationInfo, +System.Runtime.Serialization.StreamingContext) + + + + + +System.Exception.GetType() + + + + + +System.Exception.ToString() + + + + + +System.Exception.Data + + + + + +System.Exception.HelpLink + + + + + +System.Exception.HResult + + + + + +System.Exception.InnerException + + + + + +System.Exception.Message + + + + + +System.Exception.Source + + + + + +System.Exception.StackTrace + + + + + +System.Exception.TargetSite + + + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class InvalidChannelException : Exception, _Exception, ISerializable +``` + + + +### Constructors + +#### InvalidChannelException(String) + + +Constructs an InvalidChannelException with a message + + + + + + +##### Declaration + + +``` lang-csharp +public InvalidChannelException(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|-------------| +| System.String | message | the message | + +### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.InvalidParentException.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.InvalidParentException.md new file mode 100644 index 000000000..8e2e16089 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.InvalidParentException.md @@ -0,0 +1,258 @@ +--- +id: Unity.Netcode.InvalidParentException +title: Unity.Netcode.InvalideParentException +--- + +# Class InvalidParentException + + +Exception thrown when the new parent candidate of the NetworkObject is +not valid + + + + + + + +##### Inheritance + + +System.Object + + + + +System.Exception + + + + +InvalidParentException + + + + + + +##### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + + +##### Inherited Members + + + +System.Exception.GetBaseException() + + + + + +System.Exception.GetObjectData(System.Runtime.Serialization.SerializationInfo, +System.Runtime.Serialization.StreamingContext) + + + + + +System.Exception.GetType() + + + + + +System.Exception.ToString() + + + + + +System.Exception.Data + + + + + +System.Exception.HelpLink + + + + + +System.Exception.HResult + + + + + +System.Exception.InnerException + + + + + +System.Exception.Message + + + + + +System.Exception.Source + + + + + +System.Exception.StackTrace + + + + + +System.Exception.TargetSite + + + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class InvalidParentException : Exception, _Exception, ISerializable +``` + + + +### Constructors + +#### InvalidParentException() + + +Constructor for InvalidParentException + + + + + + +##### Declaration + + +``` lang-csharp +public InvalidParentException() +``` + + + +#### InvalidParentException(String) + + + + + + + +##### Declaration + + +``` lang-csharp +public InvalidParentException(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|-------------| +| System.String | message | | + +#### InvalidParentException(String, Exception) + + + + + + + +##### Declaration + + +``` lang-csharp +public InvalidParentException(string message, Exception innerException) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|----------------|-------------| +| System.String | message | | +| System.Exception | innerException | | + +### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.LogLevel.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.LogLevel.md new file mode 100644 index 000000000..86c94345a --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.LogLevel.md @@ -0,0 +1,58 @@ +--- +id: Unity.Netcode.LogLevel +title: Unity.Netcode.LogLevel +--- + +# Enum LogLevel + + +Log level + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum LogLevel +``` + + + +### Fields + +Name + + + + + + + + + +Description + +Developer + +Developer logging level, most verbose + +Error + +Error logging level, very quiet + +Normal + +Normal logging level, medium verbose + +Nothing + +Nothing logging level, no logging will be done + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkBehaviour.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkBehaviour.md new file mode 100644 index 000000000..8f0d25ca8 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkBehaviour.md @@ -0,0 +1,569 @@ +--- +id: Unity.Netcode.NetworkBehaviour +title: Unity.Netcode.NetworkBehaviour +--- + +# Class NetworkBehaviour + + +The base class to override to write network code. Inherits MonoBehaviour + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkBehaviour + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public abstract class NetworkBehaviour : MonoBehaviour +``` + + + +### Properties + +#### HasNetworkObject + + +Gets whether or not this NetworkBehaviour instance has a NetworkObject +owner. + + + + + + +##### Declaration + + +``` lang-csharp +public bool HasNetworkObject { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsClient + + +Gets if we are executing as client + + + + + + +##### Declaration + + +``` lang-csharp +protected bool IsClient { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsHost + + +Gets if we are executing as Host, I.E Server and Client + + + + + + +##### Declaration + + +``` lang-csharp +protected bool IsHost { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsLocalPlayer + + +If a NetworkObject is assigned, it will return whether or not this +NetworkObject is the local player object. If no NetworkObject is +assigned it will always return false. + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsLocalPlayer { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsOwnedByServer + + +Gets Whether or not the object has a owner + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsOwnedByServer { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsOwner + + +Gets if the object is owned by the local player or if the object is the +local player object + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsOwner { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsServer + + +Gets if we are executing as server + + + + + + +##### Declaration + + +``` lang-csharp +protected bool IsServer { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsSpawned + + +Used to determine if it is safe to access NetworkObject and +NetworkManager from within a NetworkBehaviour component Primarily useful +when checking NetworkObject/NetworkManager properties within FixedUpate + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsSpawned { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### NetworkBehaviourId + + +Gets NetworkId for this NetworkBehaviour from the owner NetworkObject + + + + + + +##### Declaration + + +``` lang-csharp +public ushort NetworkBehaviourId { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt16 | | + +#### NetworkManager + + +Gets the NetworkManager that owns this NetworkBehaviour instance See +note around `NetworkObject` for how there is a chicken / egg problem +when we are not initialized + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkManager NetworkManager { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| NetworkManager | | + +#### NetworkObject + + +Gets the NetworkObject that owns this NetworkBehaviour instance. + + + + + +##### Declaration + + +``` lang-csharp +public NetworkObject NetworkObject { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| NetworkObject | | + +#### NetworkObjectId + + +Gets the NetworkId of the NetworkObject that owns this NetworkBehaviour + + + + + + +##### Declaration + + +``` lang-csharp +public ulong NetworkObjectId { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +#### OwnerClientId + + +Gets the ClientId that owns the NetworkObject + + + + + + +##### Declaration + + +``` lang-csharp +public ulong OwnerClientId { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +### Methods + +#### GetNetworkBehaviour(UInt16) + + +Returns a the NetworkBehaviour with a given BehaviourId for the current +NetworkObject + + + + + + +##### Declaration + + +``` lang-csharp +protected NetworkBehaviour GetNetworkBehaviour(ushort behaviourId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|-------------|---------------------------| +| System.UInt16 | behaviourId | The behaviourId to return | + +##### Returns + +| Type | Description | +|------------------|-------------------------------------------------| +| NetworkBehaviour | Returns NetworkBehaviour with given behaviourId | + +#### GetNetworkObject(UInt64) + + +Gets the local instance of a object with a given NetworkId + + + + + + +##### Declaration + + +``` lang-csharp +protected NetworkObject GetNetworkObject(ulong networkId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|-----------|-------------| +| System.UInt64 | networkId | | + +##### Returns + +| Type | Description | +|---------------|-------------| +| NetworkObject | | + +#### OnDestroy() + + +Invoked when the the NetworkBehaviour is attached to. NOTE: If you +override this, you will want to always invoke this base class version of +this OnDestroy() method!! + + + + + + +##### Declaration + + +``` lang-csharp +public virtual void OnDestroy() +``` + + + +#### OnGainedOwnership() + + +Gets called when the local client gains ownership of this object + + + + + + +##### Declaration + + +``` lang-csharp +public virtual void OnGainedOwnership() +``` + + + +#### OnLostOwnership() + + +Gets called when we loose ownership of this object + + + + + + +##### Declaration + + +``` lang-csharp +public virtual void OnLostOwnership() +``` + + + +#### OnNetworkDespawn() + + +Gets called when the NetworkObject gets despawned. Is called both on the +server and clients. + + + + + + +##### Declaration + + +``` lang-csharp +public virtual void OnNetworkDespawn() +``` + + + +#### OnNetworkObjectParentChanged(NetworkObject) + + +Gets called when the parent NetworkObject of this NetworkBehaviour's +NetworkObject has changed + + + + + + +##### Declaration + + +``` lang-csharp +public virtual void OnNetworkObjectParentChanged(NetworkObject parentNetworkObject) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------------|------------------------------| +| NetworkObject | parentNetworkObject | the new NetworkObject parent | + +#### OnNetworkSpawn() + + +Gets called when the NetworkObject gets spawned, message handlers are +ready to be registered and the network is setup. + + + + + + +##### Declaration + + +``` lang-csharp +public virtual void OnNetworkSpawn() +``` + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkBehaviourReference.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkBehaviourReference.md new file mode 100644 index 000000000..d5a3bbf49 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkBehaviourReference.md @@ -0,0 +1,392 @@ +--- +id: Unity.Netcode.NetworkBehaviourReference +title: Unity.Netcode.NetworkBehaviourReference +--- + +# Struct NetworkBehaviourReference + + +A helper struct for serializing NetworkBehaviours over the network. Can +be used in RPCs and NetworkVariable\. Note: network ids get recycled +by the NetworkManager after a while. So a reference pointing to + + + + + + + +##### Implements + + + +INetworkSerializable + + + + + +System.IEquatable\ + + + + + + +##### Inherited Members + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct NetworkBehaviourReference : INetworkSerializable, IEquatable +``` + + + +### Constructors + +#### NetworkBehaviourReference(NetworkBehaviour) + + +Creates a new instance of the struct. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkBehaviourReference(NetworkBehaviour networkBehaviour) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|------------------|------------------------------------| +| NetworkBehaviour | networkBehaviour | The NetworkBehaviour to reference. | + +##### Exceptions + +| Type | Condition | +|--------------------------|-----------| +| System.ArgumentException | | + +### Methods + +#### Equals(Object) + + + + + + + +##### Declaration + + +``` lang-csharp +public override bool Equals(object obj) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|------|-------------| +| System.Object | obj | | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +##### Overrides + + + +System.ValueType.Equals(System.Object) + + + +#### Equals(NetworkBehaviourReference) + + + + + + + +##### Declaration + + +``` lang-csharp +public bool Equals(NetworkBehaviourReference other) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|-------|-------------| +| NetworkBehaviourReference | other | | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### GetHashCode() + + + + + + + +##### Declaration + + +``` lang-csharp +public override int GetHashCode() +``` + + + +##### Returns + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +##### Overrides + + + +System.ValueType.GetHashCode() + + + +#### NetworkSerialize\(BufferSerializer\) + + +Provides bi-directional serialization to read and write the desired data +to serialize this type. + + + + + + +##### Declaration + + +``` lang-csharp +public void NetworkSerialize(BufferSerializer serializer) + where T : IReaderWriter +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------|------------|---------------------------------------------------| +| BufferSerializer\ | serializer | The serializer to use to read and write the data. | + +##### Type Parameters + +| Name | Description | +|------|--------------------------------------------------------------------------------------------------------------------------| +| T | Either BufferSerializerReader or BufferSerializerWriter, depending whether the serializer is in read mode or write mode. | + +#### TryGet(out NetworkBehaviour, NetworkManager) + + +Tries to get the NetworkBehaviour referenced by this reference. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TryGet(out NetworkBehaviour networkBehaviour, NetworkManager networkManager = null) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|------------------|----------------------------------------------------------------------------------------------| +| NetworkBehaviour | networkBehaviour | The NetworkBehaviour which was found. Null if the corresponding NetworkObject was not found. | +| NetworkManager | networkManager | The networkmanager. Uses Singleton to resolve if null. | + +##### Returns + +| Type | Description | +|----------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| System.Boolean | True if the NetworkBehaviour was found; False if the NetworkBehaviour was not found. This can happen if the corresponding NetworkObject has not been spawned yet. you can try getting the reference at a later point in time. | + +#### TryGet\(out T, NetworkManager) + + +Tries to get the NetworkBehaviour referenced by this reference. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TryGet(out T networkBehaviour, NetworkManager networkManager = null) + where T : NetworkBehaviour +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|------------------|----------------------------------------------------------------------------------------------| +| T | networkBehaviour | The NetworkBehaviour which was found. Null if the corresponding NetworkObject was not found. | +| NetworkManager | networkManager | The networkmanager. Uses Singleton to resolve if null. | + +##### Returns + +| Type | Description | +|----------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| System.Boolean | True if the NetworkBehaviour was found; False if the NetworkBehaviour was not found. This can happen if the corresponding NetworkObject has not been spawned yet. you can try getting the reference at a later point in time. | + +##### Type Parameters + +| Name | Description | +|------|---------------------------------------------------| +| T | The type of the networkBehaviour for convenience. | + +### Operators + +#### Implicit(NetworkBehaviour to NetworkBehaviourReference) + + +Implicitly convert NetworkBehaviour to NetworkBehaviourReference. + + + + + + +##### Declaration + + +``` lang-csharp +public static implicit operator NetworkBehaviourReference(NetworkBehaviour networkBehaviour) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|------------------|---------------------------------------| +| NetworkBehaviour | networkBehaviour | The NetworkBehaviour to convert from. | + +##### Returns + +| Type | Description | +|---------------------------|------------------------------------------------------------------------------------------| +| NetworkBehaviourReference | The NetworkBehaviourReference created from the NetworkBehaviour passed in as a parameter | + +#### Implicit(NetworkBehaviourReference to NetworkBehaviour) + + +Implicitly convert NetworkBehaviourReference to NetworkBehaviour. + + + + + + +##### Declaration + + +``` lang-csharp +public static implicit operator NetworkBehaviour(NetworkBehaviourReference networkBehaviourRef) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------|---------------------|------------------------------------------------| +| NetworkBehaviourReference | networkBehaviourRef | The NetworkBehaviourReference to convert from. | + +##### Returns + +| Type | Description | +|------------------|-----------------------------------------------------------| +| NetworkBehaviour | The NetworkBehaviour this class is holding a reference to | + +### Implements + + + +INetworkSerializable + + + + + +System.IEquatable\ + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkBehaviourUpdater.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkBehaviourUpdater.md new file mode 100644 index 000000000..2ed8a6238 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkBehaviourUpdater.md @@ -0,0 +1,93 @@ +--- +id: Unity.Netcode.NetworkBehaviourUpdater +title: Unity.Netcode.NetworkBehaviourUpdater +--- + +# Class NetworkBehaviourUpdater + + +An helper class that helps NetworkManager update NetworkBehaviours and +replicate them down to connected clients. + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkBehaviourUpdater + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NetworkBehaviourUpdater +``` + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkClient.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkClient.md new file mode 100644 index 000000000..b3bf85e5b --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkClient.md @@ -0,0 +1,171 @@ +--- +id: Unity.Netcode.NetworkClient +title: Unity.Netcode.NetworkClient +--- + +# Class NetworkClient + + +A NetworkClient + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkClient + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NetworkClient +``` + + + +### Fields + +#### ClientId + + +The ClientId of the NetworkClient + + + + + + +##### Declaration + + +``` lang-csharp +public ulong ClientId +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +#### PlayerObject + + +The PlayerObject of the Client + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkObject PlayerObject +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| NetworkObject | | + +### Properties + +#### OwnedObjects + + +The NetworkObject's owned by this Client + + + + + + +##### Declaration + + +``` lang-csharp +public List OwnedObjects { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------------------------------------------|-------------| +| System.Collections.Generic.List\ | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkConfig.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkConfig.md new file mode 100644 index 000000000..1259cd510 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkConfig.md @@ -0,0 +1,747 @@ +--- +id: Unity.Netcode.NetworkConfig +title: Unity.Netcode.NetworkConfig +--- + +# Class NetworkConfig + + +The configuration object used to start server, client and hosts + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkConfig + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +[Serializable] +public class NetworkConfig +``` + + + +### Fields + +#### ClientConnectionBufferTimeout + + +The amount of seconds for the server to wait for the connection approval +handshake to complete before the client is disconnected. + +If the timeout is reached before approval is completed the client will +be disconnected. + + + + + + +##### Declaration + + +``` lang-csharp +public int ClientConnectionBufferTimeout +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +##### Remarks + + +The period begins after the Connect is received on the server. The +period ends once the server finishes processing a +Unity.Netcode.ConnectionRequestMessage from the client. + +This setting is independent of any Transport-level timeouts that may be +in effect. It covers the time between the connection being established +on the Transport layer, the client sending a +Unity.Netcode.ConnectionRequestMessage, and the server processing that +message through ConnectionApproval. + +This setting is server-side only. + + + +#### ConnectionApproval + + +Whether or not to use connection approval + + + + + + +##### Declaration + + +``` lang-csharp +public bool ConnectionApproval +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### ConnectionData + + +The data to send during connection which can be used to decide on if a +client should get accepted + + + + + + +##### Declaration + + +``` lang-csharp +public byte[] ConnectionData +``` + + + +##### Field Value + +| Type | Description | +|-----------------|-------------| +| System.Byte\[\] | | + +#### EnableNetworkLogs + + +Whether or not to enable network logs. + + + + + + +##### Declaration + + +``` lang-csharp +public bool EnableNetworkLogs +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### EnableSceneManagement + + +Enables scene management. This will allow network scene switches and +automatic scene difference corrections upon connect. SoftSynced scene +objects wont work with this disabled. That means that disabling +SceneManagement also enables PrefabSync. + + + + + + +##### Declaration + + +``` lang-csharp +public bool EnableSceneManagement +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### EnableTimeResync + + +If your logic uses the NetworkTime, this should probably be turned off. +If however it's needed to maximize accuracy, this is recommended to be +turned on + + + + + + +##### Declaration + + +``` lang-csharp +public bool EnableTimeResync +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### EnsureNetworkVariableLengthSafety + + +Whether or not to ensure that NetworkVariables can be read even if a +client accidentally writes where its not allowed to. This costs some CPU +and bandwidth. + + + + + + +##### Declaration + + +``` lang-csharp +public bool EnsureNetworkVariableLengthSafety +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### ForceSamePrefabs + + +Whether or not the netcode should check for differences in the prefabs +at connection. If you dynamically add prefabs at runtime, turn this OFF + + + + + + +##### Declaration + + +``` lang-csharp +public bool ForceSamePrefabs +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### LoadSceneTimeOut + + +The amount of seconds to wait for all clients to load or unload a +requested scene + + + + + + +##### Declaration + + +``` lang-csharp +public int LoadSceneTimeOut +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### NetworkIdRecycleDelay + + +The amount of seconds a NetworkId has to be unused in order for it to be +reused. + + + + + + +##### Declaration + + +``` lang-csharp +public float NetworkIdRecycleDelay +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.Single | | + +#### NetworkTransport + + +The transport hosts the sever uses + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTransport NetworkTransport +``` + + + +##### Field Value + +| Type | Description | +|------------------|-------------| +| NetworkTransport | | + +#### PlayerPrefab + + +The default player prefab + + + + + + +##### Declaration + + +``` lang-csharp +public GameObject PlayerPrefab +``` + + + +##### Field Value + +| Type | Description | +|------------|-------------| +| GameObject | | + +#### ProtocolVersion + + +The protocol version. Different versions doesn't talk to each other. + + + + + + +##### Declaration + + +``` lang-csharp +public ushort ProtocolVersion +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt16 | | + +#### RecycleNetworkIds + + +If true, NetworkIds will be reused after the NetworkIdRecycleDelay. + + + + + + +##### Declaration + + +``` lang-csharp +public bool RecycleNetworkIds +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### RpcHashSize + + +Decides how many bytes to use for Rpc messaging. Leave this to 2 bytes +unless you are facing hash collisions + + + + + + +##### Declaration + + +``` lang-csharp +public HashSize RpcHashSize +``` + + + +##### Field Value + +| Type | Description | +|----------|-------------| +| HashSize | | + +#### RttAverageSamples + + +The number of RTT samples that is kept as an average for calculations + + + + + + +##### Declaration + + +``` lang-csharp +public const int RttAverageSamples = 5 +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### RttWindowSize + + +The number of slots used for RTT calculations. This is the maximum +amount of in-flight messages + + + + + + +##### Declaration + + +``` lang-csharp +public const int RttWindowSize = 64 +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### SpawnTimeout + + +The amount of time a message should be buffered if the asset or object +needed to process it doesn't exist yet. If the asset is not added/object +is not spawned within this time, it will be dropped. + + + + + + +##### Declaration + + +``` lang-csharp +public float SpawnTimeout +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.Single | | + +#### TickRate + + +The tickrate of network ticks. This value controls how often netcode +runs user code and sends out data. + + + + + + +##### Declaration + + +``` lang-csharp +public uint TickRate +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt32 | | + +#### TimeResyncInterval + + +If time re-sync is turned on, this specifies the interval between syncs +in seconds. + + + + + + +##### Declaration + + +``` lang-csharp +public int TimeResyncInterval +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +### Methods + +#### CompareConfig(UInt64) + + +Compares a SHA256 hash with the current NetworkConfig instances hash + + + + + + +##### Declaration + + +``` lang-csharp +public bool CompareConfig(ulong hash) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|------|-------------| +| System.UInt64 | hash | | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### FromBase64(String) + + +Sets the NetworkConfig data with that from a base64 encoded version + + + + + + +##### Declaration + + +``` lang-csharp +public void FromBase64(string base64) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|--------|----------------------------| +| System.String | base64 | The base64 encoded version | + +#### GetConfig(Boolean) + + +Gets a SHA256 hash of parts of the NetworkConfig instance + + + + + + +##### Declaration + + +``` lang-csharp +public ulong GetConfig(bool cache = true) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|-------|-------------| +| System.Boolean | cache | | + +##### Returns + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +#### ToBase64() + + +Returns a base64 encoded version of the configuration + + + + + + +##### Declaration + + +``` lang-csharp +public string ToBase64() +``` + + + +##### Returns + +| Type | Description | +|---------------|-------------| +| System.String | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkConfigurationException.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkConfigurationException.md new file mode 100644 index 000000000..27b41fbda --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkConfigurationException.md @@ -0,0 +1,262 @@ +--- +id: Unity.Netcode.NetworkConfigurationException +title: Unity.Netcode.NetworkConfigurationException +--- + +# Class NetworkConfigurationException + + +Exception thrown when a change to a configuration is wrong + + + + + + + +##### Inheritance + + +System.Object + + + + +System.Exception + + + + +NetworkConfigurationException + + + + + + +##### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + + +##### Inherited Members + + + +System.Exception.GetBaseException() + + + + + +System.Exception.GetObjectData(System.Runtime.Serialization.SerializationInfo, +System.Runtime.Serialization.StreamingContext) + + + + + +System.Exception.GetType() + + + + + +System.Exception.ToString() + + + + + +System.Exception.Data + + + + + +System.Exception.HelpLink + + + + + +System.Exception.HResult + + + + + +System.Exception.InnerException + + + + + +System.Exception.Message + + + + + +System.Exception.Source + + + + + +System.Exception.StackTrace + + + + + +System.Exception.TargetSite + + + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NetworkConfigurationException : Exception, _Exception, ISerializable +``` + + + +### Constructors + +#### NetworkConfigurationException() + + +Constructs a NetworkConfigurationException + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkConfigurationException() +``` + + + +#### NetworkConfigurationException(String) + + +Constructs a NetworkConfigurationException with a message + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkConfigurationException(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|-----------------------| +| System.String | message | The exception message | + +#### NetworkConfigurationException(String, Exception) + + +Constructs a NetworkConfigurationException with a message and a inner +exception + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkConfigurationException(string message, Exception inner) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|---------|-----------------------| +| System.String | message | The exception message | +| System.Exception | inner | The inner exception | + +### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkDelivery.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkDelivery.md new file mode 100644 index 000000000..f9e8caef8 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkDelivery.md @@ -0,0 +1,62 @@ +--- +id: Unity.Netcode.NetworkDelivery +title: Unity.Netcode.NetworkDelivery +--- + +# Enum NetworkDelivery + + +Delivery methods + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum NetworkDelivery +``` + + + +### Fields + +Name + + + + + + + + + +Description + +Reliable + +Reliable message + +ReliableFragmentedSequenced + +A reliable message with guaranteed order with fragmentation support + +ReliableSequenced + +Reliable message where messages are guaranteed to be in the right order + +Unreliable + +Unreliable message + +UnreliableSequenced + +Unreliable with sequencing + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkEvent.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkEvent.md new file mode 100644 index 000000000..eddb1c444 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkEvent.md @@ -0,0 +1,62 @@ +--- +id: Unity.Netcode.NetworkEvent +title: Unity.Netcode.NetworkEvent +--- + +# Enum NetworkEvent + + +Represents a netEvent when polling + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum NetworkEvent +``` + + + +### Fields + +Name + + + + + + + + + +Description + +Connect + +A client is connected, or client connected to server + +Data + +New data is received + +Disconnect + +A client disconnected, or client disconnected from server + +Nothing + +No new event + +TransportFailure + +Transport has encountered an unrecoverable failure + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkList-1.OnListChangedDelegate.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkList-1.OnListChangedDelegate.md new file mode 100644 index 000000000..f08aa326a --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkList-1.OnListChangedDelegate.md @@ -0,0 +1,36 @@ +--- +id: Unity.Netcode.NetworkList-1.OnListChangedDelegate +title: Unity.Netcode.NetworkList-1.OnListChangedDelegate +--- + +# Delegate NetworkList\.OnListChangedDelegate + + +Delegate type for list changed event + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void OnListChangedDelegate(NetworkListEvent changeEvent); +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------|-------------|------------------------------------------------------| +| NetworkListEvent\ | changeEvent | Struct containing information about the change event | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkList-1.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkList-1.md new file mode 100644 index 000000000..95997f3fa --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkList-1.md @@ -0,0 +1,750 @@ +--- +id: Unity.Netcode.NetworkList-1 +title: Unity.Netcode.NetworkList-1 +--- + +# Class NetworkList\ + + +Event based NetworkVariable container for syncing Lists + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkVariableBase + + + + +NetworkList\ + + + + + + +##### Implements + + + +System.IDisposable + + + + + + +##### Inherited Members + + + +NetworkVariableBase.Initialize(NetworkBehaviour) + + + + + +NetworkVariableBase.DefaultReadPerm + + + + + +NetworkVariableBase.DefaultWritePerm + + + + + +NetworkVariableBase.Name + + + + + +NetworkVariableBase.ReadPerm + + + + + +NetworkVariableBase.WritePerm + + + + + +NetworkVariableBase.SetDirty(Boolean) + + + + + +NetworkVariableBase.CanClientRead(UInt64) + + + + + +NetworkVariableBase.CanClientWrite(UInt64) + + + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NetworkList : NetworkVariableBase, IDisposable where T : struct, IEquatable +``` + + + +##### Type Parameters + +| Name | Description | +|------|-----------------------| +| T | The type for the list | + +### Constructors + +#### NetworkList() + + +Constructor method for + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkList() +``` + + + +#### NetworkList(IEnumerable\, NetworkVariableReadPermission, NetworkVariableWritePermission) + + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkList(IEnumerable values = null, NetworkVariableReadPermission readPerm = NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission writePerm = NetworkVariableWritePermission.Server) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------------------------|-----------|-------------| +| System.Collections.Generic.IEnumerable\ | values | | +| NetworkVariableReadPermission | readPerm | | +| NetworkVariableWritePermission | writePerm | | + +### Properties + +#### Count + + + + + + + +##### Declaration + + +``` lang-csharp +public int Count { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### Item\[Int32\] + + + + + + + +##### Declaration + + +``` lang-csharp +public T this[int index] { get; set; } +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------|-------------| +| System.Int32 | index | | + +##### Property Value + +| Type | Description | +|------|-------------| +| T | | + +#### LastModifiedTick + + +This is actually unused left-over from a previous interface + + + + + + +##### Declaration + + +``` lang-csharp +public int LastModifiedTick { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +### Methods + +#### Add(T) + + + + + + + +##### Declaration + + +``` lang-csharp +public void Add(T item) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|------|-------------| +| T | item | | + +#### Clear() + + + + + + + +##### Declaration + + +``` lang-csharp +public void Clear() +``` + + + +#### Contains(T) + + + + + + + +##### Declaration + + +``` lang-csharp +public bool Contains(T item) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|------|-------------| +| T | item | | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### Dispose() + + +Overridden System.IDisposable implementation. CAUTION: If you derive +from this class and override the Dispose() method, you **must** always +invoke the base.Dispose() method! + + + + + + +##### Declaration + + +``` lang-csharp +public override void Dispose() +``` + + + +##### Overrides + + + +NetworkVariableBase.Dispose() + + + +#### GetEnumerator() + + + + + + + +##### Declaration + + +``` lang-csharp +public IEnumerator GetEnumerator() +``` + + + +##### Returns + +| Type | Description | +|---------------------------------------------|-------------| +| System.Collections.Generic.IEnumerator\ | | + +#### IndexOf(T) + + + + + + + +##### Declaration + + +``` lang-csharp +public int IndexOf(T item) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|------|-------------| +| T | item | | + +##### Returns + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### Insert(Int32, T) + + + + + + + +##### Declaration + + +``` lang-csharp +public void Insert(int index, T item) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------|-------------| +| System.Int32 | index | | +| T | item | | + +#### IsDirty() + + +Gets Whether or not the container is dirty + + + + + + +##### Declaration + + +``` lang-csharp +public override bool IsDirty() +``` + + + +##### Returns + +| Type | Description | +|----------------|---------------------------------------| +| System.Boolean | Whether or not the container is dirty | + +##### Overrides + + + +NetworkVariableBase.IsDirty() + + + +#### ReadDelta(FastBufferReader, Boolean) + + +Reads delta from the reader and applies them to the internal value + + + + + + +##### Declaration + + +``` lang-csharp +public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|----------------|--------------------------------------------------------------| +| FastBufferReader | reader | The stream to read the delta from | +| System.Boolean | keepDirtyDelta | Whether or not the delta should be kept as dirty or consumed | + +##### Overrides + + + +NetworkVariableBase.ReadDelta(FastBufferReader, Boolean) + + + +#### ReadField(FastBufferReader) + + +Reads the complete state from the reader and applies it + + + + + + +##### Declaration + + +``` lang-csharp +public override void ReadField(FastBufferReader reader) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-----------------------------------| +| FastBufferReader | reader | The stream to read the state from | + +##### Overrides + + + +NetworkVariableBase.ReadField(FastBufferReader) + + + +#### Remove(T) + + + + + + + +##### Declaration + + +``` lang-csharp +public bool Remove(T item) +``` + + + +##### Parameters + +| Type | Name | Description | +|------|------|-------------| +| T | item | | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### RemoveAt(Int32) + + + + + + + +##### Declaration + + +``` lang-csharp +public void RemoveAt(int index) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------|-------------| +| System.Int32 | index | | + +#### ResetDirty() + + +Resets the dirty state and marks the variable as synced / clean + + + + + + +##### Declaration + + +``` lang-csharp +public override void ResetDirty() +``` + + + +##### Overrides + + + +NetworkVariableBase.ResetDirty() + + + +#### WriteDelta(FastBufferWriter) + + +Writes the dirty changes, that is, the changes since the variable was +last dirty, to the writer + + + + + + +##### Declaration + + +``` lang-csharp +public override void WriteDelta(FastBufferWriter writer) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------------------------| +| FastBufferWriter | writer | The stream to write the dirty changes to | + +##### Overrides + + + +NetworkVariableBase.WriteDelta(FastBufferWriter) + + + +#### WriteField(FastBufferWriter) + + +Writes the complete state of the variable to the writer + + + + + + +##### Declaration + + +``` lang-csharp +public override void WriteField(FastBufferWriter writer) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|----------------------------------| +| FastBufferWriter | writer | The stream to write the state to | + +##### Overrides + + + +NetworkVariableBase.WriteField(FastBufferWriter) + + + +### Events + +#### OnListChanged + + +The callback to be invoked when the list gets changed + + + + + + +##### Declaration + + +``` lang-csharp +public event NetworkList.OnListChangedDelegate OnListChanged +``` + + + +##### Event Type + +| Type | Description | +|---------------------------------------|-------------| +| NetworkList.OnListChangedDelegate\<\> | | + +### Implements + + + +System.IDisposable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkListEvent-1.EventType.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkListEvent-1.EventType.md new file mode 100644 index 000000000..413765e17 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkListEvent-1.EventType.md @@ -0,0 +1,71 @@ +--- +id: Unity.Netcode.NetworkListEvent-1.EventType +title: Unity.Netcode.NetworkListEvent-1.EventType +--- + +# Enum NetworkListEvent\.EventType + + +Enum representing the different operations available for triggering an +event. + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum EventType : byte +``` + + + +### Fields + +Name + + + + + + + + + +Description + +Add + +Add + +Clear + +Clear + +Full + +Full list refresh + +Insert + +Insert + +Remove + +Remove + +RemoveAt + +Remove at + +Value + +Value changed + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkListEvent-1.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkListEvent-1.md new file mode 100644 index 000000000..8ead6fa42 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkListEvent-1.md @@ -0,0 +1,179 @@ +--- +id: Unity.Netcode.NetworkListEvent-1 +title: Unity.Netcode.NetworkListEvent-1 +--- + +# Struct NetworkListEvent\ + + +Struct containing event information about changes to a NetworkList. + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct NetworkListEvent +``` + + + +##### Type Parameters + +| Name | Description | +|------|-----------------------------------------------| +| T | The type for the list that the event is about | + +### Fields + +#### Index + + +the index changed, added or removed if available + + + + + + +##### Declaration + + +``` lang-csharp +public int Index +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### PreviousValue + + +The previous value when "Value" has changed, if available. + + + + + + +##### Declaration + + +``` lang-csharp +public T PreviousValue +``` + + + +##### Field Value + +| Type | Description | +|------|-------------| +| T | | + +#### Type + + +Enum representing the operation made to the list. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkListEvent.EventType Type +``` + + + +##### Field Value + +| Type | Description | +|--------------------------------|-------------| +| NetworkListEvent.EventType\<\> | | + +#### Value + + +The value changed, added or removed if available. + + + + + + +##### Declaration + + +``` lang-csharp +public T Value +``` + + + +##### Field Value + +| Type | Description | +|------|-------------| +| T | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkLog.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkLog.md new file mode 100644 index 000000000..e1049e22b --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkLog.md @@ -0,0 +1,271 @@ +--- +id: Unity.Netcode.NetworkLog +title: Unity.Netcode.NetworkLog +--- + +# Class NetworkLog + + +Helper class for logging + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkLog + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public static class NetworkLog +``` + + + +### Properties + +#### CurrentLogLevel + + +Gets the current log level. + + + + + + +##### Declaration + + +``` lang-csharp +public static LogLevel CurrentLogLevel { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------|------------------------| +| LogLevel | The current log level. | + +### Methods + +#### LogError(String) + + +Locally logs a error log with Netcode prefixing. + + + + + + +##### Declaration + + +``` lang-csharp +public static void LogError(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|--------------------| +| System.String | message | The message to log | + +#### LogErrorServer(String) + + +Logs an error log locally and on the server if possible. + + + + + + +##### Declaration + + +``` lang-csharp +public static void LogErrorServer(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|--------------------| +| System.String | message | The message to log | + +#### LogInfo(String) + + +Locally logs a info log with Netcode prefixing. + + + + + + +##### Declaration + + +``` lang-csharp +public static void LogInfo(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|--------------------| +| System.String | message | The message to log | + +#### LogInfoServer(String) + + +Logs an info log locally and on the server if possible. + + + + + + +##### Declaration + + +``` lang-csharp +public static void LogInfoServer(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|--------------------| +| System.String | message | The message to log | + +#### LogWarning(String) + + +Locally logs a warning log with Netcode prefixing. + + + + + + +##### Declaration + + +``` lang-csharp +public static void LogWarning(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|--------------------| +| System.String | message | The message to log | + +#### LogWarningServer(String) + + +Logs a warning log locally and on the server if possible. + + + + + + +##### Declaration + + +``` lang-csharp +public static void LogWarningServer(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|--------------------| +| System.String | message | The message to log | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkManager.ConnectionApprovalRequest.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkManager.ConnectionApprovalRequest.md new file mode 100644 index 000000000..6e9c4c771 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkManager.ConnectionApprovalRequest.md @@ -0,0 +1,123 @@ +--- +id: Unity.Netcode.NetworkManager.ConnectionApprovalRequest +title: Unity.Netcode.NetworkManager.ConnectionApprovalRequest +--- + +# Struct NetworkManager.ConnectionApprovalRequest + + +Connection Approval Request + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ConnectionApprovalRequest +``` + + + +### Fields + +#### ClientNetworkId + + +The Network Id of the client we are about to handle + + + + + + +##### Declaration + + +``` lang-csharp +public ulong ClientNetworkId +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +#### Payload + + +The connection data payload + + + + + + +##### Declaration + + +``` lang-csharp +public byte[] Payload +``` + + + +##### Field Value + +| Type | Description | +|-----------------|-------------| +| System.Byte\[\] | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkManager.ConnectionApprovalResponse.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkManager.ConnectionApprovalResponse.md new file mode 100644 index 000000000..a9b4aa93a --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkManager.ConnectionApprovalResponse.md @@ -0,0 +1,255 @@ +--- +id: Unity.Netcode.NetworkManager.ConnectionApprovalResponse +title: Unity.Netcode.NetworkManager.ConnectionApprovalResponse +--- + +# Class NetworkManager.ConnectionApprovalResponse + + +Connection Approval Response + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkManager.ConnectionApprovalResponse + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class ConnectionApprovalResponse +``` + + + +### Fields + +#### Approved + + +Whether or not the client was approved + + + + + + +##### Declaration + + +``` lang-csharp +public bool Approved +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### CreatePlayerObject + + +If true, a player object will be created. Otherwise the client will have +no object. + + + + + + +##### Declaration + + +``` lang-csharp +public bool CreatePlayerObject +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### Pending + + +If the Approval decision cannot be made immediately, the client code can +set Pending to true, keep a reference to the ConnectionApprovalResponse +object and write to it later. Client code must exercise care to setting +all the members to the value it wants before marking Pending to false, +to indicate completion. If the field is set as Pending = true, we'll +monitor the object until it gets set to not pending anymore and use the +parameters then. + + + + + + +##### Declaration + + +``` lang-csharp +public bool Pending +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### PlayerPrefabHash + + +The prefabHash to use for the client. If createPlayerObject is false, +this is ignored. If playerPrefabHash is null, the default player prefab +is used. + + + + + + +##### Declaration + + +``` lang-csharp +public uint? PlayerPrefabHash +``` + + + +##### Field Value + +| Type | Description | +|----------------------------------|-------------| +| System.Nullable\ | | + +#### Position + + +The position to spawn the client at. If null, the prefab position is +used. + + + + + + +##### Declaration + + +``` lang-csharp +public Vector3? Position +``` + + + +##### Field Value + +| Type | Description | +|----------------------------|-------------| +| System.Nullable\ | | + +#### Rotation + + +The rotation to spawn the client with. If null, the prefab position is +used. + + + + + + +##### Declaration + + +``` lang-csharp +public Quaternion? Rotation +``` + + + +##### Field Value + +| Type | Description | +|-------------------------------|-------------| +| System.Nullable\ | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkManager.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkManager.md new file mode 100644 index 000000000..09de6979b --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkManager.md @@ -0,0 +1,1187 @@ +--- +id: Unity.Netcode.NetworkManager +title: Unity.Netcode.NetworkManager +--- + +# Class NetworkManager + + +The main component of the library + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkManager + + + + + + +##### Implements + + + +INetworkUpdateSystem + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NetworkManager : MonoBehaviour, INetworkUpdateSystem +``` + + + +### Fields + +#### LogLevel + + +The log level to use + + + + + + +##### Declaration + + +``` lang-csharp +public LogLevel LogLevel +``` + + + +##### Field Value + +| Type | Description | +|----------|-------------| +| LogLevel | | + +#### NetworkConfig + + +The current NetworkConfig + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkConfig NetworkConfig +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| NetworkConfig | | + +#### PendingClients + + +Gets a dictionary of the clients that have been accepted by the +transport but are still pending by the Netcode. This is only populated +on the server. + + + + + + +##### Declaration + + +``` lang-csharp +public readonly Dictionary PendingClients +``` + + + +##### Field Value + +| Type | Description | +|-----------------------------------------------------------------------|-------------| +| System.Collections.Generic.Dictionary\ | | + +#### RunInBackground + + +Gets or sets if the application should be set to run in background + + + + + + +##### Declaration + + +``` lang-csharp +public bool RunInBackground +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### ServerClientId + + +The client id used to represent the server + + + + + + +##### Declaration + + +``` lang-csharp +public const ulong ServerClientId = 0UL +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +### Properties + +#### ConnectedClients + + +Gets a dictionary of connected clients and their clientId keys. This is +only accessible on the server. + + + + + + +##### Declaration + + +``` lang-csharp +public IReadOnlyDictionary ConnectedClients { get; } +``` + + + +##### Property Value + +| Type | Description | +|-----------------------------------------------------|-------------| +| IReadOnlyDictionary\ | | + +#### ConnectedClientsIds + + +Gets a list of just the IDs of all connected clients. This is only +accessible on the server. + + + + + + +##### Declaration + + +``` lang-csharp +public IReadOnlyList ConnectedClientsIds { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------------------------|-------------| +| IReadOnlyList\ | | + +#### ConnectedClientsList + + +Gets a list of connected clients. This is only accessible on the server. + + + + + + +##### Declaration + + +``` lang-csharp +public IReadOnlyList ConnectedClientsList { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------------------------|-------------| +| IReadOnlyList\ | | + +#### ConnectedHostname + + +The current host name we are connected to, used to validate certificate + + + + + + +##### Declaration + + +``` lang-csharp +public string ConnectedHostname { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.String | | + +#### ConnectionApprovalCallback + + +The callback to invoke during connection approval. Allows client code to +decide whether or not to allow incoming client connection + + + + + + +##### Declaration + + +``` lang-csharp +public Action ConnectionApprovalCallback { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|------------------------------------------------------------------------------------------------------|-------------| +| System.Action\ | | + +#### CustomMessagingManager + + +Gets the CustomMessagingManager for this NetworkManager + + + + + + +##### Declaration + + +``` lang-csharp +public CustomMessagingManager CustomMessagingManager { get; } +``` + + + +##### Property Value + +| Type | Description | +|------------------------|-------------| +| CustomMessagingManager | | + +#### IsClient + + +Gets Whether or not a client is running + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsClient { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsConnectedClient + + +Gets if we are connected as a client + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsConnectedClient { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsHost + + +Gets if we are running as host + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsHost { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsListening + + +Gets Whether or not we are listening for connections + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsListening { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsServer + + +Gets Whether or not a server is running + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsServer { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### LocalClient + + +Gets the local NetworkClient for this client. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkClient LocalClient { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| NetworkClient | | + +#### LocalClientId + + +Returns ServerClientId if IsServer or LocalClientId if not + + + + + + +##### Declaration + + +``` lang-csharp +public ulong LocalClientId { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +#### LocalTime + + +The local NetworkTime + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTime LocalTime { get; } +``` + + + +##### Property Value + +| Type | Description | +|-------------|-------------| +| NetworkTime | | + +#### NetworkTickSystem + + +Accessor for the NetworkTickSystem of the NetworkManager. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTickSystem NetworkTickSystem { get; } +``` + + + +##### Property Value + +| Type | Description | +|-------------------|-------------| +| NetworkTickSystem | | + +#### NetworkTimeSystem + + +Accessor for the NetworkTimeSystem of the NetworkManager. Prefer the use +of the LocalTime and ServerTime properties + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTimeSystem NetworkTimeSystem { get; } +``` + + + +##### Property Value + +| Type | Description | +|-------------------|-------------| +| NetworkTimeSystem | | + +#### PrefabHandler + + +The NetworkPrefabHandler instance created after starting the +NetworkManager + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkPrefabHandler PrefabHandler { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------------|-------------| +| NetworkPrefabHandler | | + +#### SceneManager + + +The NetworkSceneManager instance created after starting the +NetworkManager + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkSceneManager SceneManager { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------------|-------------| +| NetworkSceneManager | | + +#### ServerTime + + +The NetworkTime on the server + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTime ServerTime { get; } +``` + + + +##### Property Value + +| Type | Description | +|-------------|-------------| +| NetworkTime | | + +#### ShutdownInProgress + + +Can be used to determine if the NetworkManager is currently shutting +itself down + + + + + + +##### Declaration + + +``` lang-csharp +public bool ShutdownInProgress { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### Singleton + + +The singleton instance of the NetworkManager + + + + + + +##### Declaration + + +``` lang-csharp +public static NetworkManager Singleton { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| NetworkManager | | + +#### SpawnManager + + +Gets the SpawnManager for this NetworkManager + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkSpawnManager SpawnManager { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------------|-------------| +| NetworkSpawnManager | | + +### Methods + +#### AddNetworkPrefab(GameObject) + + +Adds a new prefab to the network prefab list. This can be any GameObject +with a NetworkObject component, from any source (addressables, asset +bundles, Resource.Load, dynamically created, etc) + +There are three limitations to this method: + +- If you have NetworkConfig.ForceSamePrefabs enabled, you can only do + this before starting networking, and the server and all connected + clients must all have the same exact set of prefabs added via this + method before connecting +- Adding a prefab on the server does not automatically add it on the + client - it's up to you to make sure the client and server are + synchronized via whatever method makes sense for your game (RPCs, + configs, deterministic loading, etc) +- If the server sends a Spawn message to a client that has not yet + added a prefab for, the spawn message and any other relevant + messages will be held for a configurable time (default 1 second, + configured via NetworkConfig.SpawnTimeout) before an error is + logged. This is intented to enable the SDK to gracefully handle + unexpected conditions (slow disks, slow network, etc) that slow down + asset loading. This timeout should not be relied on and code + shouldn't be written around it - your code should be written so that + the asset is expected to be loaded before it's needed. + + + + + + +##### Declaration + + +``` lang-csharp +public void AddNetworkPrefab(GameObject prefab) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|--------|-------------| +| GameObject | prefab | | + +##### Exceptions + +| Type | Condition | +|------------------|-----------| +| System.Exception | | + +#### DisconnectClient(UInt64) + + +Disconnects the remote client. + + + + + + +##### Declaration + + +``` lang-csharp +public void DisconnectClient(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|----------------------------| +| System.UInt64 | clientId | The ClientId to disconnect | + +#### GetNetworkPrefabOverride(GameObject) + + +Returns the to use as the override as could be defined within the +NetworkPrefab list Note: This should be used to create pools (with +NetworkObject components) under the scenario where you are using the +Host model as it spawns everything locally. As such, the override will +not be applied when spawning locally on a Host. Related Classes and +Interfaces: NetworkPrefabHandler INetworkPrefabInstanceHandler + + + + + + +##### Declaration + + +``` lang-csharp +public GameObject GetNetworkPrefabOverride(GameObject gameObject) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|------------|-----------------------------------------------------------------------| +| GameObject | gameObject | the to be checked for a NetworkManager defined NetworkPrefab override | + +##### Returns + +| Type | Description | +|------------|----------------------------------------------------------------------------------------------------------------| +| GameObject | a that is either the override or if no overrides exist it returns the same as the one passed in as a parameter | + +#### NetworkUpdate(NetworkUpdateStage) + + +The update method that is being executed in the context of related +NetworkUpdateStage. + + + + + + +##### Declaration + + +``` lang-csharp +public void NetworkUpdate(NetworkUpdateStage updateStage) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------|-------------|------------------------------------------------| +| NetworkUpdateStage | updateStage | The NetworkUpdateStage that is being executed. | + +#### RemoveNetworkPrefab(GameObject) + + +Remove a prefab from the prefab list. As with AddNetworkPrefab, this is +specific to the client it's called on - calling it on the server does +not automatically remove anything on any of the client processes. + +Like AddNetworkPrefab, when NetworkConfig.ForceSamePrefabs is enabled, +this cannot be called after connecting. + + + + + + +##### Declaration + + +``` lang-csharp +public void RemoveNetworkPrefab(GameObject prefab) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|--------|-------------| +| GameObject | prefab | | + +#### SetSingleton() + + +Set this NetworkManager instance as the static NetworkManager singleton + + + + + + +##### Declaration + + +``` lang-csharp +public void SetSingleton() +``` + + + +#### Shutdown(Boolean) + + +Globally shuts down the library. Disconnects clients if connected and +stops server if running. + + + + + + +##### Declaration + + +``` lang-csharp +public void Shutdown(bool discardMessageQueue = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|---------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| System.Boolean | discardMessageQueue | If false, any messages that are currently in the incoming queue will be handled, and any messages in the outgoing queue will be sent, before the shutdown is processed. If true, NetworkManager will shut down immediately, and any unprocessed or unsent messages will be discarded. | + +#### StartClient() + + +Starts a client + + + + + + +##### Declaration + + +``` lang-csharp +public bool StartClient() +``` + + + +##### Returns + +| Type | Description | +|----------------|-------------------------------------------------------------------------| +| System.Boolean | (/) returns true if NetworkManager started in client mode successfully. | + +#### StartHost() + + +Starts a Host + + + + + + +##### Declaration + + +``` lang-csharp +public bool StartHost() +``` + + + +##### Returns + +| Type | Description | +|----------------|-----------------------------------------------------------------------| +| System.Boolean | (/) returns true if NetworkManager started in host mode successfully. | + +#### StartServer() + + +Starts a server + + + + + + +##### Declaration + + +``` lang-csharp +public bool StartServer() +``` + + + +##### Returns + +| Type | Description | +|----------------|-------------------------------------------------------------------------| +| System.Boolean | (/) returns true if NetworkManager started in server mode successfully. | + +### Events + +#### OnClientConnectedCallback + + +The callback to invoke once a client connects. This callback is only ran +on the server and on the local client that connects. + + + + + + +##### Declaration + + +``` lang-csharp +public event Action OnClientConnectedCallback +``` + + + +##### Event Type + +| Type | Description | +|--------------------------------|-------------| +| System.Action\ | | + +#### OnClientDisconnectCallback + + +The callback to invoke when a client disconnects. This callback is only +ran on the server and on the local client that disconnects. + + + + + + +##### Declaration + + +``` lang-csharp +public event Action OnClientDisconnectCallback +``` + + + +##### Event Type + +| Type | Description | +|--------------------------------|-------------| +| System.Action\ | | + +#### OnServerStarted + + +The callback to invoke once the server is ready + + + + + + +##### Declaration + + +``` lang-csharp +public event Action OnServerStarted +``` + + + +##### Event Type + +| Type | Description | +|---------------|-------------| +| System.Action | | + +#### OnTransportFailure + + +The callback to invoke if the NetworkTransport fails. + + + + + + +##### Declaration + + +``` lang-csharp +public event Action OnTransportFailure +``` + + + +##### Event Type + +| Type | Description | +|---------------|-------------| +| System.Action | | + +##### Remarks + + +A failure of the transport is always followed by the NetworkManager +shutting down. Recovering from a transport failure would normally entail +reconfiguring the transport (e.g. re-authenticating, or recreating a new +service allocation depending on the transport) and restarting the +client/server/host. + + + +### Implements + + + +INetworkUpdateSystem + + + +### Extension Methods + + + +NetworkUpdateLoop.RegisterAllNetworkUpdates(INetworkUpdateSystem) + + + + + +NetworkUpdateLoop.RegisterNetworkUpdate(INetworkUpdateSystem, +NetworkUpdateStage) + + + + + +NetworkUpdateLoop.UnregisterAllNetworkUpdates(INetworkUpdateSystem) + + + + + +NetworkUpdateLoop.UnregisterNetworkUpdate(INetworkUpdateSystem, +NetworkUpdateStage) + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObject.SpawnDelegate.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObject.SpawnDelegate.md new file mode 100644 index 000000000..d06450c78 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObject.SpawnDelegate.md @@ -0,0 +1,42 @@ +--- +id: Unity.Netcode.NetworkObject.SpawnDelegate +title: Unity.Netcode.NetworkObject.SpawnDelegate +--- + +# Delegate NetworkObject.SpawnDelegate + + +Delegate type for checking spawn options + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate bool SpawnDelegate(ulong clientId); +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|-----------------------------------------| +| System.UInt64 | clientId | The clientId to check spawn options for | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObject.VisibilityDelegate.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObject.VisibilityDelegate.md new file mode 100644 index 000000000..ac3485694 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObject.VisibilityDelegate.md @@ -0,0 +1,42 @@ +--- +id: Unity.Netcode.NetworkObject.VisibilityDelegate +title: Unity.Netcode.NetworkObject.VisibilityDelegate +--- + +# Delegate NetworkObject.VisibilityDelegate + + +Delegate type for checking visibility + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate bool VisibilityDelegate(ulong clientId); +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|--------------------------------------| +| System.UInt64 | clientId | The clientId to check visibility for | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObject.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObject.md new file mode 100644 index 000000000..da41e2b40 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObject.md @@ -0,0 +1,838 @@ +--- +id: Unity.Netcode.NetworkObject +title: Unity.Netcode.NetworkObject +--- + +# Class NetworkObject + + +A component used to identify that a GameObject in the network + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkObject + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public sealed class NetworkObject : MonoBehaviour +``` + + + +### Fields + +#### AlwaysReplicateAsRoot + + +If true, the object will always be replicated as root on clients and the +parent will be ignored. + + + + + + +##### Declaration + + +``` lang-csharp +public bool AlwaysReplicateAsRoot +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### AutoObjectParentSync + + +Whether or not to enable automatic NetworkObject parent synchronization. + + + + + + +##### Declaration + + +``` lang-csharp +public bool AutoObjectParentSync +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### CheckObjectVisibility + + +Delegate invoked when the netcode needs to know if the object should be +visible to a client, if null it will assume true + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkObject.VisibilityDelegate CheckObjectVisibility +``` + + + +##### Field Value + +| Type | Description | +|----------------------------------|-------------| +| NetworkObject.VisibilityDelegate | | + +#### DontDestroyWithOwner + + +Whether or not to destroy this object if it's owner is destroyed. If +false, the objects ownership will be given to the server. + + + + + + +##### Declaration + + +``` lang-csharp +public bool DontDestroyWithOwner +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IncludeTransformWhenSpawning + + +Delegate invoked when the netcode needs to know if it should include the +transform when spawning the object, if null it will assume true + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkObject.SpawnDelegate IncludeTransformWhenSpawning +``` + + + +##### Field Value + +| Type | Description | +|-----------------------------|-------------| +| NetworkObject.SpawnDelegate | | + +### Properties + +#### DestroyWithScene + + +Gets whether or not the object should be automatically removed when the +scene is unloaded. + + + + + + +##### Declaration + + +``` lang-csharp +public bool DestroyWithScene { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsLocalPlayer + + +Gets if the object is the personal clients player object + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsLocalPlayer { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsOwnedByServer + + +Gets Whether or not the object is owned by anyone + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsOwnedByServer { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsOwner + + +Gets if the object is owned by the local player or if the object is the +local player object + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsOwner { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsPlayerObject + + +Gets if this object is a player object + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsPlayerObject { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### IsSceneObject + + +Gets if the object is a SceneObject, null if it's not yet spawned but is +a scene object. + + + + + + +##### Declaration + + +``` lang-csharp +public bool? IsSceneObject { get; } +``` + + + +##### Property Value + +| Type | Description | +|-----------------------------------|-------------| +| System.Nullable\ | | + +#### IsSpawned + + +Gets if the object has yet been spawned across the network + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsSpawned { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### NetworkManager + + +Gets the NetworkManager that owns this NetworkObject instance + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkManager NetworkManager { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| NetworkManager | | + +#### NetworkObjectId + + +Gets the unique Id of this object that is synced across the network + + + + + + +##### Declaration + + +``` lang-csharp +public ulong NetworkObjectId { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +#### OwnerClientId + + +Gets the ClientId of the owner of this NetworkObject + + + + + + +##### Declaration + + +``` lang-csharp +public ulong OwnerClientId { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +### Methods + +#### ChangeOwnership(UInt64) + + +Changes the owner of the object. Can only be called from server + + + + + + +##### Declaration + + +``` lang-csharp +public void ChangeOwnership(ulong newOwnerClientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|------------------|------------------------| +| System.UInt64 | newOwnerClientId | The new owner clientId | + +#### Despawn(Boolean) + + +Despawns the of this NetworkObject and sends a destroy message for it to +all connected clients. + + + + + + +##### Declaration + + +``` lang-csharp +public void Despawn(bool destroy = true) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|---------|-----------------------------------------------------------------------------| +| System.Boolean | destroy | (true) the will be destroyed (false) the will persist after being despawned | + +#### GetObservers() + + +Returns Observers enumerator + + + + + + +##### Declaration + + +``` lang-csharp +public HashSet.Enumerator GetObservers() +``` + + + +##### Returns + +| Type | Description | +|---------------------------------------------------|----------------------| +| System.Collections.Generic.HashSet.Enumerator\<\> | Observers enumerator | + +#### IsNetworkVisibleTo(UInt64) + + +Whether or not this object is visible to a specific client + + + + + + +##### Declaration + + +``` lang-csharp +public bool IsNetworkVisibleTo(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|----------------------------| +| System.UInt64 | clientId | The clientId of the client | + +##### Returns + +| Type | Description | +|----------------|-------------------------------------------| +| System.Boolean | True if the client knows about the object | + +#### NetworkHide(List\, UInt64) + + +Hides a list of objects from a client + + + + + + +##### Declaration + + +``` lang-csharp +public static void NetworkHide(List networkObjects, ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------------------------|----------------|-------------------------------------| +| System.Collections.Generic.List\ | networkObjects | The objects to hide | +| System.UInt64 | clientId | The client to hide the objects from | + +#### NetworkHide(UInt64) + + +Hides a object from a specific client + + + + + + +##### Declaration + + +``` lang-csharp +public void NetworkHide(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|-----------------------------------| +| System.UInt64 | clientId | The client to hide the object for | + +#### NetworkShow(List\, UInt64) + + +Shows a list of previously hidden NetworkObjects to a client + + + + + + +##### Declaration + + +``` lang-csharp +public static void NetworkShow(List networkObjects, ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------------------------|----------------|-----------------------------------| +| System.Collections.Generic.List\ | networkObjects | The NetworkObjects to show | +| System.UInt64 | clientId | The client to show the objects to | + +#### NetworkShow(UInt64) + + +Shows a previously hidden NetworkObject to a client + + + + + + +##### Declaration + + +``` lang-csharp +public void NetworkShow(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|-----------------------------------------| +| System.UInt64 | clientId | The client to show the NetworkObject to | + +#### RemoveOwnership() + + +Removes all ownership of an object from any client. Can only be called +from server + + + + + + +##### Declaration + + +``` lang-csharp +public void RemoveOwnership() +``` + + + +#### Spawn(Boolean) + + +Spawns this NetworkObject across the network. Can only be called from +the Server + + + + + + +##### Declaration + + +``` lang-csharp +public void Spawn(bool destroyWithScene = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|------------------|----------------------------------------------------------| +| System.Boolean | destroyWithScene | Should the object be destroyed when the scene is changed | + +#### SpawnAsPlayerObject(UInt64, Boolean) + + +Spawns a NetworkObject across the network and makes it the player object +for the given client + + + + + + +##### Declaration + + +``` lang-csharp +public void SpawnAsPlayerObject(ulong clientId, bool destroyWithScene = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|------------------|---------------------------------------------------------| +| System.UInt64 | clientId | The clientId whos player object this is | +| System.Boolean | destroyWithScene | Should the object be destroyd when the scene is changed | + +#### SpawnWithOwnership(UInt64, Boolean) + + +Spawns a NetworkObject across the network with a given owner. Can only +be called from server + + + + + + +##### Declaration + + +``` lang-csharp +public void SpawnWithOwnership(ulong clientId, bool destroyWithScene = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|------------------|----------------------------------------------------------| +| System.UInt64 | clientId | The clientId to own the object | +| System.Boolean | destroyWithScene | Should the object be destroyed when the scene is changed | + +#### TrySetParent(GameObject, Boolean) + + +Set the parent of the NetworkObject transform. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TrySetParent(GameObject parent, bool worldPositionStays = true) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| GameObject | parent | The new parent for this NetworkObject transform will be the child of. | +| System.Boolean | worldPositionStays | If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before. | + +##### Returns + +| Type | Description | +|----------------|--------------------------------------------| +| System.Boolean | Whether or not reparenting was successful. | + +#### TrySetParent(Transform, Boolean) + + +Set the parent of the NetworkObject transform. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TrySetParent(Transform parent, bool worldPositionStays = true) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Transform | parent | The new parent for this NetworkObject transform will be the child of. | +| System.Boolean | worldPositionStays | If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before. | + +##### Returns + +| Type | Description | +|----------------|--------------------------------------------| +| System.Boolean | Whether or not reparenting was successful. | + +#### TrySetParent(NetworkObject, Boolean) + + +Set the parent of the NetworkObject transform. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TrySetParent(NetworkObject parent, bool worldPositionStays = true) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|--------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------| +| NetworkObject | parent | The new parent for this NetworkObject transform will be the child of. | +| System.Boolean | worldPositionStays | If true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before. | + +##### Returns + +| Type | Description | +|----------------|--------------------------------------------| +| System.Boolean | Whether or not reparenting was successful. | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObjectReference.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObjectReference.md new file mode 100644 index 000000000..2a7c745b6 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkObjectReference.md @@ -0,0 +1,474 @@ +--- +id: Unity.Netcode.NetworkObjectReference +title: Unity.Netcode.NetworkObjectReference +--- + +# Struct NetworkObjectReference + + +A helper struct for serializing NetworkObjects over the network. Can be +used in RPCs and NetworkVariable\. + + + + + + + +##### Implements + + + +INetworkSerializable + + + + + +System.IEquatable\ + + + + + + +##### Inherited Members + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct NetworkObjectReference : INetworkSerializable, IEquatable +``` + + + +### Constructors + +#### NetworkObjectReference(GameObject) + + +Creates a new instance of the NetworkObjectReference struct. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkObjectReference(GameObject gameObject) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|------------|---------------------------------------------------------------------------| +| GameObject | gameObject | The GameObject from which the NetworkObject component will be referenced. | + +##### Exceptions + +| Type | Condition | +|------------------------------|-----------| +| System.ArgumentNullException | | +| System.ArgumentException | | + +#### NetworkObjectReference(NetworkObject) + + +Creates a new instance of the NetworkObjectReference struct. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkObjectReference(NetworkObject networkObject) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|---------------------------------| +| NetworkObject | networkObject | The NetworkObject to reference. | + +##### Exceptions + +| Type | Condition | +|------------------------------|-----------| +| System.ArgumentNullException | | +| System.ArgumentException | | + +### Properties + +#### NetworkObjectId + + +The NetworkObjectId of the referenced NetworkObject. + + + + + + +##### Declaration + + +``` lang-csharp +public ulong NetworkObjectId { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +### Methods + +#### Equals(Object) + + + + + + + +##### Declaration + + +``` lang-csharp +public override bool Equals(object obj) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|------|-------------| +| System.Object | obj | | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +##### Overrides + + + +System.ValueType.Equals(System.Object) + + + +#### Equals(NetworkObjectReference) + + + + + + + +##### Declaration + + +``` lang-csharp +public bool Equals(NetworkObjectReference other) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------|-------|-------------| +| NetworkObjectReference | other | | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### GetHashCode() + + + + + + + +##### Declaration + + +``` lang-csharp +public override int GetHashCode() +``` + + + +##### Returns + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +##### Overrides + + + +System.ValueType.GetHashCode() + + + +#### NetworkSerialize\(BufferSerializer\) + + +Provides bi-directional serialization to read and write the desired data +to serialize this type. + + + + + + +##### Declaration + + +``` lang-csharp +public void NetworkSerialize(BufferSerializer serializer) + where T : IReaderWriter +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------|------------|---------------------------------------------------| +| BufferSerializer\ | serializer | The serializer to use to read and write the data. | + +##### Type Parameters + +| Name | Description | +|------|--------------------------------------------------------------------------------------------------------------------------| +| T | Either BufferSerializerReader or BufferSerializerWriter, depending whether the serializer is in read mode or write mode. | + +#### TryGet(out NetworkObject, NetworkManager) + + +Tries to get the NetworkObject referenced by this reference. + + + + + + +##### Declaration + + +``` lang-csharp +public bool TryGet(out NetworkObject networkObject, NetworkManager networkManager = null) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|----------------|-----------------------------------------------------------------| +| NetworkObject | networkObject | The NetworkObject which was found. Null if no object was found. | +| NetworkManager | networkManager | The networkmanager. Uses Singleton to resolve if null. | + +##### Returns + +| Type | Description | +|----------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| System.Boolean | True if the NetworkObject was found; False if the NetworkObject was not found. This can happen if the NetworkObject has not been spawned yet. you can try getting the reference at a later point in time. | + +### Operators + +#### Implicit(GameObject to NetworkObjectReference) + + +Implicitly convert to NetworkObject. + + + + + + +##### Declaration + + +``` lang-csharp +public static implicit operator NetworkObjectReference(GameObject gameObject) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|------------|----------------------| +| GameObject | gameObject | The to convert from. | + +##### Returns + +| Type | Description | +|------------------------|---------------------------------------------------------------------------------------------------------| +| NetworkObjectReference | The NetworkObjectReference created from the parameter that has a NetworkObject component attached to it | + +#### Implicit(NetworkObject to NetworkObjectReference) + + +Implicitly convert NetworkObject to NetworkObjectReference. + + + + + + +##### Declaration + + +``` lang-csharp +public static implicit operator NetworkObjectReference(NetworkObject networkObject) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|------------------------------------| +| NetworkObject | networkObject | The NetworkObject to convert from. | + +##### Returns + +| Type | Description | +|------------------------|---------------------------------------------------------------------| +| NetworkObjectReference | The NetworkObjectReference created from the NetworkObject parameter | + +#### Implicit(NetworkObjectReference to GameObject) + + +Implicitly convert NetworkObjectReference to . + + + + + + +##### Declaration + + +``` lang-csharp +public static implicit operator GameObject(NetworkObjectReference networkObjectRef) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------|------------------|---------------------------------------------| +| NetworkObjectReference | networkObjectRef | The NetworkObjectReference to convert from. | + +##### Returns + +| Type | Description | +|------------|---------------------------------------------------------------------------------------------------------------------------------| +| GameObject | This returns the that the NetworkObject is attached to and is referenced by the NetworkObjectReference passed in as a parameter | + +#### Implicit(NetworkObjectReference to NetworkObject) + + +Implicitly convert NetworkObjectReference to NetworkObject. + + + + + + +##### Declaration + + +``` lang-csharp +public static implicit operator NetworkObject(NetworkObjectReference networkObjectRef) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------|------------------|---------------------------------------------| +| NetworkObjectReference | networkObjectRef | The NetworkObjectReference to convert from. | + +##### Returns + +| Type | Description | +|---------------|-------------------------------------------------------------| +| NetworkObject | The NetworkObject the NetworkObjectReference is referencing | + +### Implements + + + +INetworkSerializable + + + + + +System.IEquatable\ + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkPrefabHandler.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkPrefabHandler.md new file mode 100644 index 000000000..d0e6d7812 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkPrefabHandler.md @@ -0,0 +1,323 @@ +--- +id: Unity.Netcode.NetworkPrefabHandler +title: Unity.Netcode.NetworkPrefabHandler +--- + +# Class NetworkPrefabHandler + + +Primary handler to add or remove customized spawn and destroy handlers +for a network prefab (i.e. a prefab with a NetworkObject component) +Register custom prefab handlers by implementing the +INetworkPrefabInstanceHandler interface. + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkPrefabHandler + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NetworkPrefabHandler +``` + + + +### Methods + +#### AddHandler(GameObject, INetworkPrefabInstanceHandler) + + +Use a to register a class that implements the +INetworkPrefabInstanceHandler interface with the NetworkPrefabHandler + + + + + + +##### Declaration + + +``` lang-csharp +public bool AddHandler(GameObject networkPrefabAsset, INetworkPrefabInstanceHandler instanceHandler) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------------------------|--------------------|------------------------------------------------------------------------------------| +| GameObject | networkPrefabAsset | the of the network prefab asset to be overridden | +| INetworkPrefabInstanceHandler | instanceHandler | class that implements the INetworkPrefabInstanceHandler interface to be registered | + +##### Returns + +| Type | Description | +|----------------|----------------------------------------------| +| System.Boolean | true (registered) false (failed to register) | + +#### AddHandler(UInt32, INetworkPrefabInstanceHandler) + + +Use a Unity.Netcode.NetworkObject.GlobalObjectIdHash to register a class +that implements the INetworkPrefabInstanceHandler interface with the +NetworkPrefabHandler + + + + + + +##### Declaration + + +``` lang-csharp +public bool AddHandler(uint globalObjectIdHash, INetworkPrefabInstanceHandler instanceHandler) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------------------------|--------------------|-------------------------------------------------------------------------------------------------------| +| System.UInt32 | globalObjectIdHash | the Unity.Netcode.NetworkObject.GlobalObjectIdHash value of the network prefab asset being overridden | +| INetworkPrefabInstanceHandler | instanceHandler | a class that implements the INetworkPrefabInstanceHandler interface | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### AddHandler(NetworkObject, INetworkPrefabInstanceHandler) + + +Use a NetworkObject to register a class that implements the +INetworkPrefabInstanceHandler interface with the NetworkPrefabHandler + + + + + + +##### Declaration + + +``` lang-csharp +public bool AddHandler(NetworkObject prefabAssetNetworkObject, INetworkPrefabInstanceHandler instanceHandler) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------------------------|--------------------------|----------------------------------------------------------------------------------------| +| NetworkObject | prefabAssetNetworkObject | the NetworkObject of the network prefab asset to be overridden | +| INetworkPrefabInstanceHandler | instanceHandler | the class that implements the INetworkPrefabInstanceHandler interface to be registered | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### RegisterHostGlobalObjectIdHashValues(GameObject, List\) + + +HOST ONLY! Since a host is unique and is considered both a client and a +server, for each source NetworkPrefab you must manually register all +potential target overrides that have the NetworkObject component. + + + + + + +##### Declaration + + +``` lang-csharp +public void RegisterHostGlobalObjectIdHashValues(GameObject sourceNetworkPrefab, List networkPrefabOverrides) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------------------------------------|------------------------|-------------------------------------------------------------------------------| +| GameObject | sourceNetworkPrefab | source NetworkPrefab to be overridden | +| System.Collections.Generic.List\ | networkPrefabOverrides | one or more NetworkPrefabs could be used to override the source NetworkPrefab | + +#### RemoveHandler(GameObject) + + +Use the of the overridden network prefab asset to remove a registered +class that implements the INetworkPrefabInstanceHandler interface. + + + + + + +##### Declaration + + +``` lang-csharp +public bool RemoveHandler(GameObject networkPrefabAsset) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|--------------------|-------------------------------------------------------| +| GameObject | networkPrefabAsset | of the network prefab asset that was being overridden | + +##### Returns + +| Type | Description | +|----------------|-----------------------------------| +| System.Boolean | true (success) or false (failure) | + +#### RemoveHandler(UInt32) + + +Use the Unity.Netcode.NetworkObject.GlobalObjectIdHash of the overridden +network prefab asset to remove a registered class that implements the +INetworkPrefabInstanceHandler interface. + + + + + + +##### Declaration + + +``` lang-csharp +public bool RemoveHandler(uint globalObjectIdHash) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|--------------------|------------------------------------------------------------------------------------------------------| +| System.UInt32 | globalObjectIdHash | Unity.Netcode.NetworkObject.GlobalObjectIdHash of the source NetworkPrefab that was being overridden | + +##### Returns + +| Type | Description | +|----------------|-----------------------------------| +| System.Boolean | true (success) or false (failure) | + +#### RemoveHandler(NetworkObject) + + +Use the NetworkObject of the overridden network prefab asset to remove a +registered class that implements the INetworkPrefabInstanceHandler +interface. + + + + + + +##### Declaration + + +``` lang-csharp +public bool RemoveHandler(NetworkObject networkObject) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|---------------------------------------------------------------------| +| NetworkObject | networkObject | NetworkObject of the source NetworkPrefab that was being overridden | + +##### Returns + +| Type | Description | +|----------------|-----------------------------------| +| System.Boolean | true (success) or false (failure) | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnEventCompletedDelegateHandler.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnEventCompletedDelegateHandler.md new file mode 100644 index 000000000..16b9ef273 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnEventCompletedDelegateHandler.md @@ -0,0 +1,43 @@ +--- +id: Unity.Netcode.NetworkSceneManager.OnEventCompletedDelegateHandler +title: Unity.Netcode.NetworkSceneManager.OnEventCompletedDelegateHandler +--- + +# Delegate NetworkSceneManager.OnEventCompletedDelegateHandler + + +Delegate declaration for the OnLoadEventCompleted and +OnUnloadEventCompleted events. +See also: +LoadEventCompleted +UnloadEventCompleted + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void OnEventCompletedDelegateHandler(string sceneName, LoadSceneMode loadSceneMode, List clientsCompleted, List clientsTimedOut); +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------------------------|------------------|--------------------------------------------------------------| +| System.String | sceneName | scene pertaining to this event | +| LoadSceneMode | loadSceneMode | of the associated event completed | +| System.Collections.Generic.List\ | clientsCompleted | the clients that completed the loading event | +| System.Collections.Generic.List\ | clientsTimedOut | the clients (if any) that timed out during the loading event | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnLoadCompleteDelegateHandler.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnLoadCompleteDelegateHandler.md new file mode 100644 index 000000000..b74caa9fb --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnLoadCompleteDelegateHandler.md @@ -0,0 +1,40 @@ +--- +id: Unity.Netcode.NetworkSceneManager.OnLoadCompleteDelegateHandler +title: Unity.Netcode.OnLoadCompleteDelegateHandler +--- + +# Delegate NetworkSceneManager.OnLoadCompleteDelegateHandler + + +Delegate declaration for the OnLoadComplete event. +See also: +LoadComplete for more information + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void OnLoadCompleteDelegateHandler(ulong clientId, string sceneName, LoadSceneMode loadSceneMode); +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|--------------------------------------------------------------------------------------------------------------------| +| System.UInt64 | clientId | the client that is processing this event (the server will receive all of these events for every client and itself) | +| System.String | sceneName | the scene name pertaining to this event | +| LoadSceneMode | loadSceneMode | the mode the scene was loaded in | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnLoadDelegateHandler.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnLoadDelegateHandler.md new file mode 100644 index 000000000..8186a871c --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnLoadDelegateHandler.md @@ -0,0 +1,41 @@ +--- +id: Unity.Netcode.NetworkSceneManager.OnLoadDelegateHandler +title: Unity.Netcode.NetworkSceneManager.OnLoadDelegateHandler +--- + +# Delegate NetworkSceneManager.OnLoadDelegateHandler + + +Delegate declaration for the OnLoad event. +See also: +Loadfor more information + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void OnLoadDelegateHandler(ulong clientId, string sceneName, LoadSceneMode loadSceneMode, AsyncOperation asyncOperation); +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|----------------|--------------------------------------------------------------------------------------------------------------------| +| System.UInt64 | clientId | the client that is processing this event (the server will receive all of these events for every client and itself) | +| System.String | sceneName | name of the scene being processed | +| LoadSceneMode | loadSceneMode | the LoadSceneMode mode for the scene being loaded | +| AsyncOperation | asyncOperation | the associated that can be used for scene loading progress | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnSynchronizeCompleteDelegateHandler.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnSynchronizeCompleteDelegateHandler.md new file mode 100644 index 000000000..e1dd01dd4 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnSynchronizeCompleteDelegateHandler.md @@ -0,0 +1,38 @@ +--- +id: Unity.Netcode.NetworkSceneManager.OnSynchronizeCompleteDelegateHandler +title: Unity.Netcode.NetworkSceneManager.OnSynchronizeCompleteDelegateHandler +--- + +# Delegate NetworkSceneManager.OnSynchronizeCompleteDelegateHandler + + +Delegate declaration for the OnSynchronizeComplete event. +See also: +SynchronizeComplete for more information + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void OnSynchronizeCompleteDelegateHandler(ulong clientId); +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|--------------------------------------| +| System.UInt64 | clientId | the client that completed this event | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnSynchronizeDelegateHandler.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnSynchronizeDelegateHandler.md new file mode 100644 index 000000000..24256adac --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnSynchronizeDelegateHandler.md @@ -0,0 +1,38 @@ +--- +id: Unity.Netcode.NetworkSceneManager.OnSynchronizeDelegateHandler +title: Unity.Netcode.NetworkSceneManager.OnSynchronizeDelegateHandler +--- + +# Delegate NetworkSceneManager.OnSynchronizeDelegateHandler + + +Delegate declaration for the OnSynchronize event. +See also: +Synchronize for more information + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void OnSynchronizeDelegateHandler(ulong clientId); +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|--------------------------------------------------------------------------------------------------------------------| +| System.UInt64 | clientId | the client that is processing this event (the server will receive all of these events for every client and itself) | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnUnloadCompleteDelegateHandler.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnUnloadCompleteDelegateHandler.md new file mode 100644 index 000000000..87a0dd7a3 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnUnloadCompleteDelegateHandler.md @@ -0,0 +1,39 @@ +--- +id: Unity.Netcode.NetworkSceneManager.OnUnloadCompleteDelegateHandler +title: Unity.Netcode.NetworkSceneManager.OnUnloadCompleteDelegateHandler +--- + +# Delegate NetworkSceneManager.OnUnloadCompleteDelegateHandler + + +Delegate declaration for the OnUnloadComplete event. +See also: +UnloadComplete for more information + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void OnUnloadCompleteDelegateHandler(ulong clientId, string sceneName); +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|-----------|--------------------------------------------------------------------------------------------------------------------| +| System.UInt64 | clientId | the client that is processing this event (the server will receive all of these events for every client and itself) | +| System.String | sceneName | the scene name pertaining to this event | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnUnloadDelegateHandler.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnUnloadDelegateHandler.md new file mode 100644 index 000000000..40f9d4bef --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnUnloadDelegateHandler.md @@ -0,0 +1,40 @@ +--- +id: Unity.Netcode.NetworkSceneManager.OnUnloadDelegateHandler +title: Unity.Netcode.NetworkSceneManager.OnUnloadDelegateHandler +--- + +# Delegate NetworkSceneManager.OnUnloadDelegateHandler + + +Delegate declaration for the OnUnload event. +See also: +Unload for more information + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void OnUnloadDelegateHandler(ulong clientId, string sceneName, AsyncOperation asyncOperation); +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|----------------|--------------------------------------------------------------------------------------------------------------------| +| System.UInt64 | clientId | the client that is processing this event (the server will receive all of these events for every client and itself) | +| System.String | sceneName | name of the scene being processed | +| AsyncOperation | asyncOperation | the associated that can be used for scene unloading progress | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.SceneEventDelegate.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.SceneEventDelegate.md new file mode 100644 index 000000000..df01466f9 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.SceneEventDelegate.md @@ -0,0 +1,39 @@ +--- +id: Unity.Netcode.NetworkSceneManager.SceneEventDelegate +title: Unity.Netcode.NetworkSceneManager.SceneEventDelegate +--- + +# Delegate NetworkSceneManager.SceneEventDelegate + + +The delegate callback definition for scene event notifications. +See also: +SceneEvent +Unity.Netcode.SceneEventData + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void SceneEventDelegate(SceneEvent sceneEvent); +``` + + + +##### Parameters + +| Type | Name | Description | +|------------|------------|-------------| +| SceneEvent | sceneEvent | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler.md new file mode 100644 index 000000000..c88401f81 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler.md @@ -0,0 +1,47 @@ +--- +id: Unity.Netcode.NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler +title: Unity.Netcode.NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler +--- + +# Delegate NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler + + +Delegate declaration for the VerifySceneBeforeLoading handler that +provides an additional level of scene loading security and/or validation +to assure the scene being loaded is valid scene to be loaded in the +LoadSceneMode specified. + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate bool VerifySceneBeforeLoadingDelegateHandler(int sceneIndex, string sceneName, LoadSceneMode loadSceneMode); +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|--------------------------------------------------------| +| System.Int32 | sceneIndex | Build Settings Scenes in Build List index of the scene | +| System.String | sceneName | Name of the scene | +| LoadSceneMode | loadSceneMode | LoadSceneMode the scene is going to be loaded | + +##### Returns + +| Type | Description | +|----------------|-----------------------------------| +| System.Boolean | true (valid) or false (not valid) | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.md new file mode 100644 index 000000000..3f18cc7fe --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSceneManager.md @@ -0,0 +1,624 @@ +--- +id: Unity.Netcode.NetworkSceneManager +title: Unity.Netcode.NetworkSceneManager +--- + +# Class NetworkSceneManager + + +Main class for managing network scenes when EnableSceneManagement is +enabled. Uses the Unity.Netcode.SceneEventMessage message to communicate +Unity.Netcode.SceneEventData between the server and client(s) + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkSceneManager + + + + + + +##### Implements + + + +System.IDisposable + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NetworkSceneManager : IDisposable +``` + + + +### Fields + +#### VerifySceneBeforeLoading + + +Delegate handler defined by +NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler that is +invoked before the server or client loads a scene during an active +netcode game session. +**Client Side:** In order for clients to be notified of this condition +you must assign the VerifySceneBeforeLoading delegate handler. +**Server Side:** LoadScene(String, LoadSceneMode) will return +SceneEventProgressStatus. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler VerifySceneBeforeLoading +``` + + + +##### Field Value + +| Type | Description | +|-------------------------------------------------------------|-------------| +| NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler | | + +### Properties + +#### ClientSynchronizationMode + + +**LoadSceneMode.Single:** All currently loaded scenes on the client will +be unloaded and the server's currently active scene will be loaded in +single mode on the client unless it was already loaded. +**LoadSceneMode.Additive:** All currently loaded scenes are left as they +are and any newly loaded scenes will be loaded additively. Users need to +determine which scenes are valid to load via the +VerifySceneBeforeLoading method. + + + + + + +##### Declaration + + +``` lang-csharp +public LoadSceneMode ClientSynchronizationMode { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| LoadSceneMode | | + +### Methods + +#### DisableValidationWarnings(Boolean) + + +When set to true, this will disable the console warnings about a scene +being invalidated. + + + + + + +##### Declaration + + +``` lang-csharp +public void DisableValidationWarnings(bool disabled) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|----------|-------------| +| System.Boolean | disabled | true/false | + +#### Dispose() + + +Handle NetworkSeneManager clean up + + + + + + +##### Declaration + + +``` lang-csharp +public void Dispose() +``` + + + +#### LoadScene(String, LoadSceneMode) + + +**Server side:** Loads the scene name in either additive or single +loading mode. When applicable, the is delivered within the SceneEvent +via OnSceneEvent + + + + + + +##### Declaration + + +``` lang-csharp +public SceneEventProgressStatus LoadScene(string sceneName, LoadSceneMode loadSceneMode) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|--------------------------------------------------------| +| System.String | sceneName | the name of the scene to be loaded | +| LoadSceneMode | loadSceneMode | how the scene will be loaded (single or additive mode) | + +##### Returns + +| Type | Description | +|--------------------------|------------------------------------------------------------| +| SceneEventProgressStatus | SceneEventProgressStatus (Started means it was successful) | + +#### SetClientSynchronizationMode(LoadSceneMode) + + +This will change how clients are initially synchronized. +**LoadSceneMode.Single:** All currently loaded scenes on the client will +be unloaded and the server's currently active scene will be loaded in +single mode on the client unless it was already loaded. +**LoadSceneMode.Additive:** All currently loaded scenes are left as they +are and any newly loaded scenes will be loaded additively. Users need to +determine which scenes are valid to load via the +VerifySceneBeforeLoading method. + + + + + + +##### Declaration + + +``` lang-csharp +public void SetClientSynchronizationMode(LoadSceneMode mode) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|------|------------------------------------| +| LoadSceneMode | mode | for initial client synchronization | + +#### UnloadScene(Scene) + + +**Server Side:** Unloads an additively loaded scene. If you want to +unload a mode loaded scene load another scene. When applicable, the is +delivered within the SceneEvent via the OnSceneEvent + + + + + + +##### Declaration + + +``` lang-csharp +public SceneEventProgressStatus UnloadScene(Scene scene) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------|-------|-------------| +| Scene | scene | | + +##### Returns + +| Type | Description | +|--------------------------|------------------------------------------------------------| +| SceneEventProgressStatus | SceneEventProgressStatus (Started means it was successful) | + +### Events + +#### OnLoad + + +Invoked when a Load event is started by the server. +*Note: The server and connected client(s) will always receive this +notification.* +*\*\*\* Do not start new scene events within scene event notification +callbacks.* + + + + + + +##### Declaration + + +``` lang-csharp +public event NetworkSceneManager.OnLoadDelegateHandler OnLoad +``` + + + +##### Event Type + +| Type | Description | +|-------------------------------------------|-------------| +| NetworkSceneManager.OnLoadDelegateHandler | | + +#### OnLoadComplete + + +Invoked when a LoadComplete event is generated by a client or server. +*Note: The server receives this message from all clients (including +itself). Each client receives their own notification sent to the +server.* +*\*\*\* Do not start new scene events within scene event notification +callbacks.* + + + + + + +##### Declaration + + +``` lang-csharp +public event NetworkSceneManager.OnLoadCompleteDelegateHandler OnLoadComplete +``` + + + +##### Event Type + +| Type | Description | +|---------------------------------------------------|-------------| +| NetworkSceneManager.OnLoadCompleteDelegateHandler | | + +#### OnLoadEventCompleted + + +Invoked when a LoadEventCompleted event is generated by the server. This +event signifies the end of an existing Load event as it pertains to all +clients connected when the event was started. This event signifies that +all clients (and server) have finished the Load event. +*Note: this is useful to know when all clients have loaded the same +scene (single or additive mode)* +*\*\*\* Do not start new scene events within scene event notification +callbacks.* + + + + + + +##### Declaration + + +``` lang-csharp +public event NetworkSceneManager.OnEventCompletedDelegateHandler OnLoadEventCompleted +``` + + + +##### Event Type + +| Type | Description | +|-----------------------------------------------------|-------------| +| NetworkSceneManager.OnEventCompletedDelegateHandler | | + +#### OnSceneEvent + + +Subscribe to this event to receive all SceneEventType notifications. +For more details review over SceneEvent and SceneEventType. +**Alternate Single Event Type Notification Registration Options** +To receive only a specific event type notification or a limited set of +notifications you can alternately subscribe to each notification type +individually via the following events: + +- OnLoad Invoked only when a Load event is being processed +- OnUnload Invoked only when an Unload event is being processed +- OnSynchronize Invoked only when a Synchronize event is being + processed +- OnLoadEventCompleted Invoked only when a LoadEventCompleted event is + being processed +- OnUnloadEventCompleted Invoked only when an UnloadEventCompleted + event is being processed +- OnLoadComplete Invoked only when a LoadComplete event is being + processed +- OnUnloadComplete Invoked only when an UnloadComplete event is being + processed +- OnSynchronizeComplete Invoked only when a SynchronizeComplete event + is being processed + +*Note: Do not start new scene events within NetworkSceneManager scene +event notification callbacks.* + + + + + + +##### Declaration + + +``` lang-csharp +public event NetworkSceneManager.SceneEventDelegate OnSceneEvent +``` + + + +##### Event Type + +| Type | Description | +|----------------------------------------|-------------| +| NetworkSceneManager.SceneEventDelegate | | + +#### OnSynchronize + + +Invoked when a Synchronize event is started by the server after a client +is approved for connection in order to synchronize the client with the +currently loaded scenes and NetworkObjects. This event signifies the +beginning of the synchronization event. +*Note: The server and connected client(s) will always receive this +notification. This event is generated on a per newly connected and +approved client basis.* +*\*\*\* Do not start new scene events within scene event notification +callbacks.* + + + + + + +##### Declaration + + +``` lang-csharp +public event NetworkSceneManager.OnSynchronizeDelegateHandler OnSynchronize +``` + + + +##### Event Type + +| Type | Description | +|--------------------------------------------------|-------------| +| NetworkSceneManager.OnSynchronizeDelegateHandler | | + +#### OnSynchronizeComplete + + +Invoked when a SynchronizeComplete event is generated by a client. +*Note: The server receives this message from the client, but will never +generate this event for itself. Each client receives their own +notification sent to the server. This is useful to know that a client +has completed the entire connection sequence, loaded all scenes, and +synchronized all NetworkObjects.* *\*\*\* Do not start new scene events +within scene event notification callbacks.* + + + + + + +##### Declaration + + +``` lang-csharp +public event NetworkSceneManager.OnSynchronizeCompleteDelegateHandler OnSynchronizeComplete +``` + + + +##### Event Type + +| Type | Description | +|----------------------------------------------------------|-------------| +| NetworkSceneManager.OnSynchronizeCompleteDelegateHandler | | + +#### OnUnload + + +Invoked when a Unload event is started by the server. +*Note: The server and connected client(s) will always receive this +notification.* +*\*\*\* Do not start new scene events within scene event notification +callbacks.* + + + + + + +##### Declaration + + +``` lang-csharp +public event NetworkSceneManager.OnUnloadDelegateHandler OnUnload +``` + + + +##### Event Type + +| Type | Description | +|---------------------------------------------|-------------| +| NetworkSceneManager.OnUnloadDelegateHandler | | + +#### OnUnloadComplete + + +Invoked when a UnloadComplete event is generated by a client or +server. +*Note: The server receives this message from all clients (including +itself). Each client receives their own notification sent to the +server.* +*\*\*\* Do not start new scene events within scene event notification +callbacks.* + + + + + + +##### Declaration + + +``` lang-csharp +public event NetworkSceneManager.OnUnloadCompleteDelegateHandler OnUnloadComplete +``` + + + +##### Event Type + +| Type | Description | +|-----------------------------------------------------|-------------| +| NetworkSceneManager.OnUnloadCompleteDelegateHandler | | + +#### OnUnloadEventCompleted + + +Invoked when a UnloadEventCompleted event is generated by the server. +This event signifies the end of an existing Unload event as it pertains +to all clients connected when the event was started. This event +signifies that all clients (and server) have finished the Unload +event. +*Note: this is useful to know when all clients have unloaded a specific +scene. The will always be for this event.* +*\*\*\* Do not start new scene events within scene event notification +callbacks.* + + + + + + +##### Declaration + + +``` lang-csharp +public event NetworkSceneManager.OnEventCompletedDelegateHandler OnUnloadEventCompleted +``` + + + +##### Event Type + +| Type | Description | +|-----------------------------------------------------|-------------| +| NetworkSceneManager.OnEventCompletedDelegateHandler | | + +### Implements + + + +System.IDisposable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSpawnManager.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSpawnManager.md new file mode 100644 index 000000000..3de1fb4ab --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkSpawnManager.md @@ -0,0 +1,289 @@ +--- +id: Unity.Netcode.NetworkSpawnManager +title: Unity.Netcode.NetworkSpawnManager +--- + +# Class NetworkSpawnManager + + +Class that handles object spawning + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkSpawnManager + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NetworkSpawnManager +``` + + + +### Fields + +#### OwnershipToObjectsTable + + +Use to get all NetworkObjects owned by a client Ownership to Objects +Table Format: \[ClientId\]\[NetworkObjectId\]\[NetworkObject\] Server: +Keeps track of all clients' ownership Client: Keeps track of only its +ownership + + + + + + +##### Declaration + + +``` lang-csharp +public readonly Dictionary> OwnershipToObjectsTable +``` + + + +##### Field Value + +| Type | Description | +|-------------------------------------------------------------------------------------------------------------------------------|-------------| +| System.Collections.Generic.Dictionary\\> | | + +#### SpawnedObjects + + +The currently spawned objects + + + + + + +##### Declaration + + +``` lang-csharp +public readonly Dictionary SpawnedObjects +``` + + + +##### Field Value + +| Type | Description | +|-----------------------------------------------------------------------|-------------| +| System.Collections.Generic.Dictionary\ | | + +#### SpawnedObjectsList + + +A list of the spawned objects + + + + + + +##### Declaration + + +``` lang-csharp +public readonly HashSet SpawnedObjectsList +``` + + + +##### Field Value + +| Type | Description | +|-----------------------------------------------------|-------------| +| System.Collections.Generic.HashSet\ | | + +### Properties + +#### NetworkManager + + +Gets the NetworkManager associated with this SpawnManager. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkManager NetworkManager { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|-------------| +| NetworkManager | | + +### Methods + +#### GetClientOwnedObjects(UInt64) + + +Returns a list of all NetworkObjects that belong to a client. + + + + + + +##### Declaration + + +``` lang-csharp +public List GetClientOwnedObjects(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|-------------------------------| +| System.UInt64 | clientId | the client's id LocalClientId | + +##### Returns + +| Type | Description | +|--------------------------------------------------|--------------------------------------------------------| +| System.Collections.Generic.List\ | returns the list of NetworkObjects owned by the client | + +#### GetLocalPlayerObject() + + +Returns the local player object or null if one does not exist + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkObject GetLocalPlayerObject() +``` + + + +##### Returns + +| Type | Description | +|---------------|-------------------------------------------------------| +| NetworkObject | The local player object or null if one does not exist | + +#### GetPlayerNetworkObject(UInt64) + + +Returns the player object with a given clientId or null if one does not +exist. This is only valid server side. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkObject GetPlayerNetworkObject(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|-------------------------------------| +| System.UInt64 | clientId | the client identifier of the player | + +##### Returns + +| Type | Description | +|---------------|-----------------------------------------------------------------------| +| NetworkObject | The player object with a given clientId or null if one does not exist | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTickSystem.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTickSystem.md new file mode 100644 index 000000000..abcbfe663 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTickSystem.md @@ -0,0 +1,314 @@ +--- +id: Unity.Netcode.NetworkTickSystem +title: Unity.Netcode.NetworkTickSystem +--- + +# Class NetworkTickSystem + + +Provides discretized time. This is useful for games that require ticks +happening at regular interval on the server and clients. + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkTickSystem + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NetworkTickSystem +``` + + + +### Constructors + +#### NetworkTickSystem(UInt32, Double, Double) + + +Creates a new instance of the NetworkTickSystem class. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTickSystem(uint tickRate, double localTimeSec, double serverTimeSec) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|--------------------------------------| +| System.UInt32 | tickRate | The tick rate | +| System.Double | localTimeSec | The initial local time to start at. | +| System.Double | serverTimeSec | The initial server time to start at. | + +### Fields + +#### NoTick + + +Special value to indicate "No tick information" + + + + + + +##### Declaration + + +``` lang-csharp +public const int NoTick = -2147483648 +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +### Properties + +#### LocalTime + + +The current local time. This is the time at which predicted or client +authoritative objects move. This value is accurate when called in Update +or during the Tick event but does not work correctly for FixedUpdate. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTime LocalTime { get; } +``` + + + +##### Property Value + +| Type | Description | +|-------------|-------------| +| NetworkTime | | + +#### ServerTime + + +The current server time. This value is mostly used for internal purposes +and to interpolate state received from the server. This value is +accurate when called in Update or during the Tick event but does not +work correctly for FixedUpdate. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTime ServerTime { get; } +``` + + + +##### Property Value + +| Type | Description | +|-------------|-------------| +| NetworkTime | | + +#### TickRate + + +The TickRate of the tick system. This is used to decide how often a +fixed network tick is run. + + + + + + +##### Declaration + + +``` lang-csharp +public uint TickRate { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt32 | | + +### Methods + +#### Reset(Double, Double) + + +Resets the tick system to the given network time. + + + + + + +##### Declaration + + +``` lang-csharp +public void Reset(double localTimeSec, double serverTimeSec) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|-----------------------------| +| System.Double | localTimeSec | The local time in seconds. | +| System.Double | serverTimeSec | The server time in seconds. | + +#### UpdateTick(Double, Double) + + +Called after advancing the time system to run ticks based on the +difference in time. + + + + + + +##### Declaration + + +``` lang-csharp +public void UpdateTick(double localTimeSec, double serverTimeSec) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|----------------------------| +| System.Double | localTimeSec | The local time in seconds | +| System.Double | serverTimeSec | The server time in seconds | + +### Events + +#### Tick + + +Gets invoked before every network tick. + + + + + + +##### Declaration + + +``` lang-csharp +public event Action Tick +``` + + + +##### Event Type + +| Type | Description | +|---------------|-------------| +| System.Action | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTime.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTime.md new file mode 100644 index 000000000..40558c44a --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTime.md @@ -0,0 +1,522 @@ +--- +id: Unity.Netcode.NetworkTime +title: Unity.Netcode.NetworkTime +--- + +# Struct NetworkTime + + +A struct to represent a point of time in a networked game. Time is +stored as a combination of amount of passed ticks + a duration offset. +This struct is meant to replace the Unity Time API for multiplayer +gameplay. + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct NetworkTime +``` + + + +### Constructors + +#### NetworkTime(UInt32) + + +Creates a new instance of the NetworkTime struct. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTime(uint tickRate) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|---------------| +| System.UInt32 | tickRate | The tickrate. | + +#### NetworkTime(UInt32, Double) + + +Creates a new instance of the NetworkTime struct. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTime(uint tickRate, double timeSec) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|----------------------------| +| System.UInt32 | tickRate | The tickrate. | +| System.Double | timeSec | The time value as a float. | + +#### NetworkTime(UInt32, Int32, Double) + + +Creates a new instance of the NetworkTime struct. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTime(uint tickRate, int tick, double tickOffset = 0) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|------------|--------------------------------------------------------------------------------------------------------------| +| System.UInt32 | tickRate | The tickrate. | +| System.Int32 | tick | The time will be created with a value where this many tick have already passed. | +| System.Double | tickOffset | Can be used to create a NetworkTime with a non fixed time value by adding an offset to the given tick value. | + +### Properties + +#### FixedDeltaTime + + +Gets the fixed delta time. This value is based on the TickRate and stays +constant. Similar to There is no equivalent to + + + + + + +##### Declaration + + +``` lang-csharp +public readonly float FixedDeltaTime { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.Single | | + +#### FixedTime + + +Gets he current fixed network time. This is the time value of the last +network tick. Similar to + + + + + + +##### Declaration + + +``` lang-csharp +public readonly double FixedTime { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.Double | | + +#### Tick + + +Gets the amount of network ticks which have passed until reaching the +current time value. + + + + + + +##### Declaration + + +``` lang-csharp +public readonly int Tick { get; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### TickOffset + + +Gets the amount of time which has passed since the last network tick. + + + + + + +##### Declaration + + +``` lang-csharp +public readonly double TickOffset { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.Double | | + +#### TickRate + + +Gets the tickrate of the system of this NetworkTime. Ticks per second. + + + + + + +##### Declaration + + +``` lang-csharp +public readonly uint TickRate { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt32 | | + +#### Time + + +Gets the current time. This is a non fixed time value and similar to + + + + + + +##### Declaration + + +``` lang-csharp +public readonly double Time { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.Double | | + +#### TimeAsFloat + + +Gets the current time as a float. + + + + + + +##### Declaration + + +``` lang-csharp +public readonly float TimeAsFloat { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.Single | | + +### Methods + +#### TimeTicksAgo(Int32) + + +Returns the time a number of ticks in the past. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTime TimeTicksAgo(int ticks) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|-------|-------------------------------------------------| +| System.Int32 | ticks | The number of ticks ago we're querying the time | + +##### Returns + +| Type | Description | +|-------------|-------------| +| NetworkTime | | + +#### ToFixedTime() + + +Converts the network time into a fixed time value. + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTime ToFixedTime() +``` + + + +##### Returns + +| Type | Description | +|-------------|-------------------------------------------------------------------| +| NetworkTime | A NetworkTime where Time is the FixedTime value of this instance. | + +### Operators + +#### Addition(NetworkTime, Double) + + +Computes the time a number of seconds later + + + + + + +##### Declaration + + +``` lang-csharp +public static NetworkTime operator +(NetworkTime a, double b) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|------|------------------------------| +| NetworkTime | a | The start time | +| System.Double | b | The number of seconds to add | + +##### Returns + +| Type | Description | +|-------------|--------------------| +| NetworkTime | The resulting time | + +#### Addition(NetworkTime, NetworkTime) + + +Computes the sum of two times + + + + + + +##### Declaration + + +``` lang-csharp +public static NetworkTime operator +(NetworkTime a, NetworkTime b) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|------|-------------| +| NetworkTime | a | First time | +| NetworkTime | b | Second time | + +##### Returns + +| Type | Description | +|-------------|------------------------------------| +| NetworkTime | The sum of the two times passed in | + +#### Subtraction(NetworkTime, Double) + + +Computes the time a number of seconds before + + + + + + +##### Declaration + + +``` lang-csharp +public static NetworkTime operator -(NetworkTime a, double b) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|------|---------------------------------| +| NetworkTime | a | The start time | +| System.Double | b | The number of seconds to remove | + +##### Returns + +| Type | Description | +|-------------|--------------------| +| NetworkTime | The resulting time | + +#### Subtraction(NetworkTime, NetworkTime) + + +Computes the time difference between two ticks + + + + + + +##### Declaration + + +``` lang-csharp +public static NetworkTime operator -(NetworkTime a, NetworkTime b) +``` + + + +##### Parameters + +| Type | Name | Description | +|-------------|------|-------------| +| NetworkTime | a | End time | +| NetworkTime | b | Start time | + +##### Returns + +| Type | Description | +|-------------|-------------------------------------------| +| NetworkTime | The time difference between start and end | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTimeSystem.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTimeSystem.md new file mode 100644 index 000000000..91d6c1d68 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTimeSystem.md @@ -0,0 +1,398 @@ +--- +id: Unity.Netcode.NetworkTimeSystem +title: Unity.Netcode.NetworkTimeSystem +--- + +# Class NetworkTimeSystem + + +NetworkTimeSystem is a standalone system which can be used to run a +network time simulation. The network time system maintains both a local +and a server time. The local time is based on + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkTimeSystem + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NetworkTimeSystem +``` + + + +### Constructors + +#### NetworkTimeSystem(Double, Double, Double, Double) + + +The constructor class for NetworkTickSystem + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkTimeSystem(double localBufferSec, double serverBufferSec, double hardResetThresholdSec, double adjustmentRatio = 0.01) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|-----------------------|-----------------------------------------------------------------------------------------------| +| System.Double | localBufferSec | The amount of time, in seconds, the server should buffer incoming client messages. | +| System.Double | serverBufferSec | The amount of the time in seconds the client should buffer incoming messages from the server. | +| System.Double | hardResetThresholdSec | The threshold, in seconds, used to force a hard catchup of network time. | +| System.Double | adjustmentRatio | The ratio at which the NetworkTimeSystem speeds up or slows down time. | + +### Properties + +#### AdjustmentRatio + + +Gets or sets the ratio at which the NetworkTimeSystem speeds up or slows +down time. + + + + + + +##### Declaration + + +``` lang-csharp +public double AdjustmentRatio { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.Double | | + +#### HardResetThresholdSec + + +Gets or sets a threshold in seconds used to force a hard catchup of +network time. + + + + + + +##### Declaration + + +``` lang-csharp +public double HardResetThresholdSec { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.Double | | + +#### LocalBufferSec + + +Gets or sets the amount of time in seconds the server should buffer +incoming client messages. This increases the difference between local +and server time so that messages arrive earlier on the server. + + + + + + +##### Declaration + + +``` lang-csharp +public double LocalBufferSec { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.Double | | + +#### LocalTime + + +The current local time with the local time offset applied + + + + + + +##### Declaration + + +``` lang-csharp +public double LocalTime { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.Double | | + +#### ServerBufferSec + + +Gets or sets the amount of the time in seconds the client should buffer +incoming messages from the server. This increases server time. A higher +value increases latency but makes the game look more smooth in bad +networking conditions. This value must be higher than the tick length +client side. + + + + + + +##### Declaration + + +``` lang-csharp +public double ServerBufferSec { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.Double | | + +#### ServerTime + + +The current server time with the server time offset applied + + + + + + +##### Declaration + + +``` lang-csharp +public double ServerTime { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.Double | | + +### Methods + +#### Advance(Double) + + +Advances the time system by a certain amount of time. Should be called +once per frame with Time.deltaTime or similar. + + + + + + +##### Declaration + + +``` lang-csharp +public bool Advance(double deltaTimeSec) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|--------------|-------------------------------------------------------------------------------------------| +| System.Double | deltaTimeSec | The amount of time to advance. The delta time which passed since Advance was last called. | + +##### Returns + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +#### Reset(Double, Double) + + +Resets the time system to a time based on the given network parameters. + + + + + + +##### Declaration + + +``` lang-csharp +public void Reset(double serverTimeSec, double rttSec) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|----------------------------------------------------------------| +| System.Double | serverTimeSec | The most recent server time value received in seconds. | +| System.Double | rttSec | The current RTT in seconds. Can be an averaged or a raw value. | + +#### ServerTimeSystem() + + +Creates a new instance of the NetworkTimeSystem class for a server +instance. The server will not apply any buffer values which ensures that +local time equals server time. + + + + + + +##### Declaration + + +``` lang-csharp +public static NetworkTimeSystem ServerTimeSystem() +``` + + + +##### Returns + +| Type | Description | +|-------------------|---------------| +| NetworkTimeSystem | The instance. | + +#### Sync(Double, Double) + + +Synchronizes the time system with up-to-date network statistics but does +not change any time values or advance the time. + + + + + + +##### Declaration + + +``` lang-csharp +public void Sync(double serverTimeSec, double rttSec) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|----------------------------------------------------------------| +| System.Double | serverTimeSec | The most recent server time value received in seconds. | +| System.Double | rttSec | The current RTT in seconds. Can be an averaged or a raw value. | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTransport.TransportEventDelegate.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTransport.TransportEventDelegate.md new file mode 100644 index 000000000..649e1aac8 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTransport.TransportEventDelegate.md @@ -0,0 +1,39 @@ +--- +id: Unity.Netcode.NetwrokTransport.TransportEventDelegate +title: Unity.Netcode.NetworkTransport.TransportEventDelegate +--- + +# Delegate NetworkTransport.TransportEventDelegate + + +Delegate for transport network events + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void TransportEventDelegate(NetworkEvent eventType, ulong clientId, ArraySegment payload, float receiveTime); +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------------------|-------------|-------------| +| NetworkEvent | eventType | | +| System.UInt64 | clientId | | +| System.ArraySegment\ | payload | | +| System.Single | receiveTime | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTransport.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTransport.md new file mode 100644 index 000000000..99ef4f4cf --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkTransport.md @@ -0,0 +1,397 @@ +--- +id: Unity.Netcode.NetworkTransport +title: Unity.Netcode.NetworkTransport +--- + +# Class NetworkTransport + + +The generic transport class all Netcode for GameObjects network +transport implementations derive from. Use this class to add a custom +transport. for an example of how a transport is integrated + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkTransport + + + + +UnityTransport + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public abstract class NetworkTransport : MonoBehaviour +``` + + + +### Properties + +#### IsSupported + + +Gets a value indicating whether this NetworkTransport is supported in +the current runtime context This is used by multiplex adapters + + + + + + +##### Declaration + + +``` lang-csharp +public virtual bool IsSupported { get; } +``` + + + +##### Property Value + +| Type | Description | +|----------------|---------------------------------------------| +| System.Boolean | `true` if is supported; otherwise, `false`. | + +#### ServerClientId + + +A constant `clientId` that represents the server When this value is +found in methods such as `Send`, it should be treated as a placeholder +that means "the server" + + + + + + +##### Declaration + + +``` lang-csharp +public abstract ulong ServerClientId { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +### Methods + +#### DisconnectLocalClient() + + +Disconnects the local client from the server + + + + + + +##### Declaration + + +``` lang-csharp +public abstract void DisconnectLocalClient() +``` + + + +#### DisconnectRemoteClient(UInt64) + + +Disconnects a client from the server + + + + + + +##### Declaration + + +``` lang-csharp +public abstract void DisconnectRemoteClient(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|----------------------------| +| System.UInt64 | clientId | The clientId to disconnect | + +#### GetCurrentRtt(UInt64) + + +Gets the round trip time for a specific client. This method is optional + + + + + + +##### Declaration + + +``` lang-csharp +public abstract ulong GetCurrentRtt(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|----------------------------------| +| System.UInt64 | clientId | The clientId to get the RTT from | + +##### Returns + +| Type | Description | +|---------------|---------------------------------------------| +| System.UInt64 | Returns the round trip time in milliseconds | + +#### Initialize(NetworkManager) + + +Initializes the transport + + + + + + +##### Declaration + + +``` lang-csharp +public abstract void Initialize(NetworkManager networkManager = null) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|----------------|-----------------------------------| +| NetworkManager | networkManager | optionally pass in NetworkManager | + +#### InvokeOnTransportEvent(NetworkEvent, UInt64, ArraySegment\, Single) + + +Invokes the OnTransportEvent. Invokation has to occur on the Unity +thread in the Update loop. + + + + + + +##### Declaration + + +``` lang-csharp +protected void InvokeOnTransportEvent(NetworkEvent eventType, ulong clientId, ArraySegment payload, float receiveTime) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------------------|-------------|----------------------------------------------------------------------------| +| NetworkEvent | eventType | The event type | +| System.UInt64 | clientId | The clientId this event is for | +| System.ArraySegment\ | payload | The incoming data payload | +| System.Single | receiveTime | The time the event was received, as reported by Time.realtimeSinceStartup. | + +#### PollEvent(out UInt64, out ArraySegment\, out Single) + + +Polls for incoming events, with an extra output parameter to report the +precise time the event was received. + + + + + + +##### Declaration + + +``` lang-csharp +public abstract NetworkEvent PollEvent(out ulong clientId, out ArraySegment payload, out float receiveTime) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------------------|-------------|----------------------------------------------------------------------------| +| System.UInt64 | clientId | The clientId this event is for | +| System.ArraySegment\ | payload | The incoming data payload | +| System.Single | receiveTime | The time the event was received, as reported by Time.realtimeSinceStartup. | + +##### Returns + +| Type | Description | +|--------------|------------------------| +| NetworkEvent | Returns the event type | + +#### Send(UInt64, ArraySegment\, NetworkDelivery) + + +Send a payload to the specified clientId, data and networkDelivery. + + + + + + +##### Declaration + + +``` lang-csharp +public abstract void Send(ulong clientId, ArraySegment payload, NetworkDelivery networkDelivery) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------------------|-----------------|-------------------------------------------| +| System.UInt64 | clientId | The clientId to send to | +| System.ArraySegment\ | payload | The data to send | +| NetworkDelivery | networkDelivery | The delivery type (QoS) to send data with | + +#### Shutdown() + + +Shuts down the transport + + + + + + +##### Declaration + + +``` lang-csharp +public abstract void Shutdown() +``` + + + +#### StartClient() + + +Connects client to the server + + + + + + +##### Declaration + + +``` lang-csharp +public abstract bool StartClient() +``` + + + +##### Returns + +| Type | Description | +|----------------|----------------------------| +| System.Boolean | Returns success or failure | + +#### StartServer() + + +Starts to listening for incoming clients + + + + + + +##### Declaration + + +``` lang-csharp +public abstract bool StartServer() +``` + + + +##### Returns + +| Type | Description | +|----------------|----------------------------| +| System.Boolean | Returns success or failure | + +### Events + +#### OnTransportEvent + + +Occurs when the transport has a new transport network event. Can be used +to make an event based transport instead of a poll based. Invocation has +to occur on the Unity thread in the Update loop. + + + + + + +##### Declaration + + +``` lang-csharp +public event NetworkTransport.TransportEventDelegate OnTransportEvent +``` + + + +##### Event Type + +| Type | Description | +|-----------------------------------------|-------------| +| NetworkTransport.TransportEventDelegate | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkUpdateLoop.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkUpdateLoop.md new file mode 100644 index 000000000..2267346ee --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkUpdateLoop.md @@ -0,0 +1,227 @@ +--- +id: Unity.Netcode.NetworkUpdateLoop +title: Unity.Netcode.NetworkUpdateLoop +--- + +# Class NetworkUpdateLoop + + +Represents the network update loop injected into low-level player loop +in Unity. + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkUpdateLoop + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public static class NetworkUpdateLoop +``` + + + +### Fields + +#### UpdateStage + + +The current network update stage being executed. + + + + + + +##### Declaration + + +``` lang-csharp +public static NetworkUpdateStage UpdateStage +``` + + + +##### Field Value + +| Type | Description | +|--------------------|-------------| +| NetworkUpdateStage | | + +### Methods + +#### RegisterAllNetworkUpdates(INetworkUpdateSystem) + + +Registers a network update system to be executed in all network update +stages. + + + + + + +##### Declaration + + +``` lang-csharp +public static void RegisterAllNetworkUpdates(this INetworkUpdateSystem updateSystem) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------|--------------|-----------------------------------------------------------------------------| +| INetworkUpdateSystem | updateSystem | The INetworkUpdateSystem implementation to register for all network updates | + +#### RegisterNetworkUpdate(INetworkUpdateSystem, NetworkUpdateStage) + + +Registers a network update system to be executed in a specific network +update stage. + + + + + + +##### Declaration + + +``` lang-csharp +public static void RegisterNetworkUpdate(this INetworkUpdateSystem updateSystem, NetworkUpdateStage updateStage = NetworkUpdateStage.Update) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------|--------------|-------------------------------------------------------------------------------------| +| INetworkUpdateSystem | updateSystem | The INetworkUpdateSystem implementation to register for all network updates | +| NetworkUpdateStage | updateStage | The NetworkUpdateStage being registered for the INetworkUpdateSystem implementation | + +#### UnregisterAllNetworkUpdates(INetworkUpdateSystem) + + +Unregisters a network update system from all network update stages. + + + + + + +##### Declaration + + +``` lang-csharp +public static void UnregisterAllNetworkUpdates(this INetworkUpdateSystem updateSystem) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------|--------------|--------------------------------------------------------------------------------| +| INetworkUpdateSystem | updateSystem | The INetworkUpdateSystem implementation to deregister from all network updates | + +#### UnregisterNetworkUpdate(INetworkUpdateSystem, NetworkUpdateStage) + + +Unregisters a network update system from a specific network update +stage. + + + + + + +##### Declaration + + +``` lang-csharp +public static void UnregisterNetworkUpdate(this INetworkUpdateSystem updateSystem, NetworkUpdateStage updateStage = NetworkUpdateStage.Update) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------------|--------------|----------------------------------------------------------------------------------------| +| INetworkUpdateSystem | updateSystem | The INetworkUpdateSystem implementation to deregister from all network updates | +| NetworkUpdateStage | updateStage | The NetworkUpdateStage to be deregistered from the INetworkUpdateSystem implementation | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkUpdateStage.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkUpdateStage.md new file mode 100644 index 000000000..8befa7cc3 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkUpdateStage.md @@ -0,0 +1,77 @@ +--- +id: Unity.Netcode.NetworkUpdateStage +title: Unity.Netcode.NetworkUpdateStage +--- + +# Enum NetworkUpdateStage + + +Defines network update stages being executed by the network update loop. +See for more details on update stages: +https://docs.unity3d.com/ScriptReference/PlayerLoop.Initialization.html + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum NetworkUpdateStage : byte +``` + + + +### Fields + +Name + + + + + + + + + +Description + +EarlyUpdate + +Invoked before Fixed update + +FixedUpdate + +Fixed Update (i.e. state machine, physics, animations, etc) + +Initialization + +Very first initialization update + +PostLateUpdate + +Updated after the Monobehaviour.LateUpdate for all components is invoked + +PreLateUpdate + +Updated before the Monobehaviour.LateUpdate for all components is +invoked + +PreUpdate + +Updated before the Monobehaviour.Update for all components is invoked + +Unset + +Default value + +Update + +Updated when the Monobehaviour.Update for all components is invoked + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariable-1.OnValueChangedDelegate.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariable-1.OnValueChangedDelegate.md new file mode 100644 index 000000000..a3c6f635f --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariable-1.OnValueChangedDelegate.md @@ -0,0 +1,37 @@ +--- +id: Unity.Netcode.NetworkVariable-1.OnValueChangedDelegate +title: Unity.Netcode.NetworkVariable-1.OnValueChangedDelegate +--- + +# Delegate NetworkVariable\.OnValueChangedDelegate + + +Delegate type for value changed event + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void OnValueChangedDelegate(T previousValue, T newValue); +``` + + + +##### Parameters + +| Type | Name | Description | +|------|---------------|-----------------------------| +| T | previousValue | The value before the change | +| T | newValue | The new value | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariable-1.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariable-1.md new file mode 100644 index 000000000..a69c0f46f --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariable-1.md @@ -0,0 +1,413 @@ +--- +id: Unity.Netcode.NetworkVariable-1 +title: Unity.Netcode.NetworkVariable-1 +--- + +# Class NetworkVariable\ + + +A variable that can be synchronized over the network. + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkVariableBase + + + + +NetworkVariable\ + + + + + + +##### Implements + + + +System.IDisposable + + + + + + +##### Inherited Members + + + +NetworkVariableBase.Initialize(NetworkBehaviour) + + + + + +NetworkVariableBase.DefaultReadPerm + + + + + +NetworkVariableBase.DefaultWritePerm + + + + + +NetworkVariableBase.Name + + + + + +NetworkVariableBase.ReadPerm + + + + + +NetworkVariableBase.WritePerm + + + + + +NetworkVariableBase.SetDirty(Boolean) + + + + + +NetworkVariableBase.ResetDirty() + + + + + +NetworkVariableBase.IsDirty() + + + + + +NetworkVariableBase.CanClientRead(UInt64) + + + + + +NetworkVariableBase.CanClientWrite(UInt64) + + + + + +NetworkVariableBase.Dispose() + + + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +[Serializable] +public class NetworkVariable : NetworkVariableBase, IDisposable where T : struct +``` + + + +##### Type Parameters + +| Name | Description | +|------|---------------------------------------------| +| T | the unmanaged type for NetworkVariable\ | + +### Constructors + +#### NetworkVariable(T, NetworkVariableReadPermission, NetworkVariableWritePermission) + + +Constructor for NetworkVariable\ + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkVariable(T value = default(T), NetworkVariableReadPermission readPerm = NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission writePerm = NetworkVariableWritePermission.Server) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|-----------|------------------------------------------------------------------| +| T | value | initial value set that is of type T | +| NetworkVariableReadPermission | readPerm | the NetworkVariableReadPermission for this NetworkVariable\ | +| NetworkVariableWritePermission | writePerm | the NetworkVariableWritePermission for this NetworkVariable\ | + +### Fields + +#### OnValueChanged + + +The callback to be invoked when the value gets changed + + + + + + +##### Declaration + + +``` lang-csharp +public NetworkVariable.OnValueChangedDelegate OnValueChanged +``` + + + +##### Field Value + +| Type | Description | +|--------------------------------------------|-------------| +| NetworkVariable.OnValueChangedDelegate\<\> | | + +### Properties + +#### Value + + +The value of the NetworkVariable container + + + + + + +##### Declaration + + +``` lang-csharp +public virtual T Value { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|------|-------------| +| T | | + +### Methods + +#### ReadDelta(FastBufferReader, Boolean) + + +Reads value from the reader and applies it + + + + + + +##### Declaration + + +``` lang-csharp +public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|----------------|-----------------------------------------------------------------------------------------| +| FastBufferReader | reader | The stream to read the value from | +| System.Boolean | keepDirtyDelta | Whether or not the container should keep the dirty delta, or mark the delta as consumed | + +##### Overrides + + + +NetworkVariableBase.ReadDelta(FastBufferReader, Boolean) + + + +#### ReadField(FastBufferReader) + + +Reads the complete state from the reader and applies it + + + + + + +##### Declaration + + +``` lang-csharp +public override void ReadField(FastBufferReader reader) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-----------------------------------| +| FastBufferReader | reader | The stream to read the state from | + +##### Overrides + + + +NetworkVariableBase.ReadField(FastBufferReader) + + + +#### WriteDelta(FastBufferWriter) + + +Writes the variable to the writer + + + + + + +##### Declaration + + +``` lang-csharp +public override void WriteDelta(FastBufferWriter writer) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|----------------------------------| +| FastBufferWriter | writer | The stream to write the value to | + +##### Overrides + + + +NetworkVariableBase.WriteDelta(FastBufferWriter) + + + +#### WriteField(FastBufferWriter) + + +Writes the complete state of the variable to the writer + + + + + + +##### Declaration + + +``` lang-csharp +public override void WriteField(FastBufferWriter writer) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|----------------------------------| +| FastBufferWriter | writer | The stream to write the state to | + +##### Overrides + + + +NetworkVariableBase.WriteField(FastBufferWriter) + + + +### Implements + + + +System.IDisposable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableBase.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableBase.md new file mode 100644 index 000000000..51d841553 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableBase.md @@ -0,0 +1,559 @@ +--- +id: Unity.Netcode.NetworkVariableBase +title: Unity.Netcode.NetworkVariableBase +--- + +# Class NetworkVariableBase + + +Interface for network value containers + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkVariableBase + + + + +NetworkList\ + + + + +NetworkVariable\ + + + + + + +##### Implements + + + +System.IDisposable + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public abstract class NetworkVariableBase : IDisposable +``` + + + +### Constructors + +#### NetworkVariableBase(NetworkVariableReadPermission, NetworkVariableWritePermission) + + +The default constructor for NetworkVariableBase that can be used to +create a custom NetworkVariable. + + + + + + +##### Declaration + + +``` lang-csharp +protected NetworkVariableBase(NetworkVariableReadPermission readPerm = NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission writePerm = NetworkVariableWritePermission.Server) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------------------------|-----------|----------------------------------------------------| +| NetworkVariableReadPermission | readPerm | the NetworkVariableReadPermission access settings | +| NetworkVariableWritePermission | writePerm | the NetworkVariableWritePermission access settings | + +### Fields + +#### DefaultReadPerm + + +The default read permissions + + + + + + +##### Declaration + + +``` lang-csharp +public const NetworkVariableReadPermission DefaultReadPerm = NetworkVariableReadPermission.Everyone +``` + + + +##### Field Value + +| Type | Description | +|-------------------------------|-------------| +| NetworkVariableReadPermission | | + +#### DefaultWritePerm + + +The default write permissions + + + + + + +##### Declaration + + +``` lang-csharp +public const NetworkVariableWritePermission DefaultWritePerm = NetworkVariableWritePermission.Server +``` + + + +##### Field Value + +| Type | Description | +|--------------------------------|-------------| +| NetworkVariableWritePermission | | + +#### ReadPerm + + +The read permission for this var + + + + + + +##### Declaration + + +``` lang-csharp +public readonly NetworkVariableReadPermission ReadPerm +``` + + + +##### Field Value + +| Type | Description | +|-------------------------------|-------------| +| NetworkVariableReadPermission | | + +#### WritePerm + + +The write permission for this var + + + + + + +##### Declaration + + +``` lang-csharp +public readonly NetworkVariableWritePermission WritePerm +``` + + + +##### Field Value + +| Type | Description | +|--------------------------------|-------------| +| NetworkVariableWritePermission | | + +### Properties + +#### Name + + +Gets or sets the name of the network variable's instance (MemberInfo) +where it was declared. + + + + + + +##### Declaration + + +``` lang-csharp +public string Name { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.String | | + +### Methods + +#### CanClientRead(UInt64) + + +Gets if a specific client has permission to read the var or not + + + + + + +##### Declaration + + +``` lang-csharp +public bool CanClientRead(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|---------------| +| System.UInt64 | clientId | The client id | + +##### Returns + +| Type | Description | +|----------------|--------------------------------------------------| +| System.Boolean | Whether or not the client has permission to read | + +#### CanClientWrite(UInt64) + + +Gets if a specific client has permission to write the var or not + + + + + + +##### Declaration + + +``` lang-csharp +public bool CanClientWrite(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|---------------| +| System.UInt64 | clientId | The client id | + +##### Returns + +| Type | Description | +|----------------|---------------------------------------------------| +| System.Boolean | Whether or not the client has permission to write | + +#### Dispose() + + +Virtual System.IDisposable implementation + + + + + + +##### Declaration + + +``` lang-csharp +public virtual void Dispose() +``` + + + +#### Initialize(NetworkBehaviour) + + +Initializes the NetworkVariable + + + + + + +##### Declaration + + +``` lang-csharp +public void Initialize(NetworkBehaviour networkBehaviour) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|------------------|-----------------------------------------------------| +| NetworkBehaviour | networkBehaviour | The NetworkBehaviour the NetworkVariable belongs to | + +#### IsDirty() + + +Gets Whether or not the container is dirty + + + + + + +##### Declaration + + +``` lang-csharp +public virtual bool IsDirty() +``` + + + +##### Returns + +| Type | Description | +|----------------|---------------------------------------| +| System.Boolean | Whether or not the container is dirty | + +#### ReadDelta(FastBufferReader, Boolean) + + +Reads delta from the reader and applies them to the internal value + + + + + + +##### Declaration + + +``` lang-csharp +public abstract void ReadDelta(FastBufferReader reader, bool keepDirtyDelta) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|----------------|--------------------------------------------------------------| +| FastBufferReader | reader | The stream to read the delta from | +| System.Boolean | keepDirtyDelta | Whether or not the delta should be kept as dirty or consumed | + +#### ReadField(FastBufferReader) + + +Reads the complete state from the reader and applies it + + + + + + +##### Declaration + + +``` lang-csharp +public abstract void ReadField(FastBufferReader reader) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-----------------------------------| +| FastBufferReader | reader | The stream to read the state from | + +#### ResetDirty() + + +Resets the dirty state and marks the variable as synced / clean + + + + + + +##### Declaration + + +``` lang-csharp +public virtual void ResetDirty() +``` + + + +#### SetDirty(Boolean) + + +Sets whether or not the variable needs to be delta synced + + + + + + +##### Declaration + + +``` lang-csharp +public virtual void SetDirty(bool isDirty) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|---------|---------------------------------| +| System.Boolean | isDirty | Whether or not the var is dirty | + +#### WriteDelta(FastBufferWriter) + + +Writes the dirty changes, that is, the changes since the variable was +last dirty, to the writer + + + + + + +##### Declaration + + +``` lang-csharp +public abstract void WriteDelta(FastBufferWriter writer) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|------------------------------------------| +| FastBufferWriter | writer | The stream to write the dirty changes to | + +#### WriteField(FastBufferWriter) + + +Writes the complete state of the variable to the writer + + + + + + +##### Declaration + + +``` lang-csharp +public abstract void WriteField(FastBufferWriter writer) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|----------------------------------| +| FastBufferWriter | writer | The stream to write the state to | + +### Implements + + + +System.IDisposable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableReadPermission.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableReadPermission.md new file mode 100644 index 000000000..c38f183b4 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableReadPermission.md @@ -0,0 +1,50 @@ +--- +id: Unity.Netcode.NetworkVariableReadPermission +title: Unity.Netcode.NetworkVariableReadPermission +--- + +# Enum NetworkVariableReadPermission + + +The permission types for reading a var + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum NetworkVariableReadPermission +``` + + + +### Fields + +Name + + + + + + + + + +Description + +Everyone + +Everyone can read + +Owner + +Only the owner and the server can read + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableSerialization-1.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableSerialization-1.md new file mode 100644 index 000000000..e67816c00 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableSerialization-1.md @@ -0,0 +1,104 @@ +--- +id: Unity.Netcode.NetworkVariableSerialization-1 +title: Unity.Netcode.NetworkVariableSerialization-1 +--- + +# Class NetworkVariableSerialization\ + + +Support methods for reading/writing NetworkVariables Because there are +multiple overloads of WriteValue/ReadValue based on different generic +constraints, but there's no way to achieve the same thing with a class, +this sets up various read/write schemes based on which constraints are +met by `T` using reflection, which is done at module load time. + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkVariableSerialization\ + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +[Serializable] +public static class NetworkVariableSerialization + where T : struct +``` + + + +##### Type Parameters + +| Name | Description | +|------|---------------------------------------------------------| +| T | The type the associated NetworkVariable is templated on | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableWritePermission.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableWritePermission.md new file mode 100644 index 000000000..838445301 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NetworkVariableWritePermission.md @@ -0,0 +1,50 @@ +--- +id: Unity.Netcode.NetworkVariableWritePermission +title: Unity.Netcode.NetworkVariableWritePermission +--- + +# Enum NetworkVariableWritePermission + + +The permission types for writing a var + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum NetworkVariableWritePermission +``` + + + +### Fields + +Name + + + + + + + + + +Description + +Owner + +Only the owner can write + +Server + +Only the server can write + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NotListeningException.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NotListeningException.md new file mode 100644 index 000000000..d6e9e3dac --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NotListeningException.md @@ -0,0 +1,262 @@ +--- +id: Unity.Netcode.NotListeningException +title: Unity.Netcode.NotListeningException +--- + +# Class NotListeningException + + +Exception thrown when the operation require NetworkManager to be +listening. + + + + + + + +##### Inheritance + + +System.Object + + + + +System.Exception + + + + +NotListeningException + + + + + + +##### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + + +##### Inherited Members + + + +System.Exception.GetBaseException() + + + + + +System.Exception.GetObjectData(System.Runtime.Serialization.SerializationInfo, +System.Runtime.Serialization.StreamingContext) + + + + + +System.Exception.GetType() + + + + + +System.Exception.ToString() + + + + + +System.Exception.Data + + + + + +System.Exception.HelpLink + + + + + +System.Exception.HResult + + + + + +System.Exception.InnerException + + + + + +System.Exception.Message + + + + + +System.Exception.Source + + + + + +System.Exception.StackTrace + + + + + +System.Exception.TargetSite + + + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NotListeningException : Exception, _Exception, ISerializable +``` + + + +### Constructors + +#### NotListeningException() + + +Constructs a NotListeningException + + + + + + +##### Declaration + + +``` lang-csharp +public NotListeningException() +``` + + + +#### NotListeningException(String) + + +Constructs a NotListeningException with a message + + + + + + +##### Declaration + + +``` lang-csharp +public NotListeningException(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|-----------------------| +| System.String | message | The exception message | + +#### NotListeningException(String, Exception) + + +Constructs a NotListeningException with a message and a inner exception + + + + + + +##### Declaration + + +``` lang-csharp +public NotListeningException(string message, Exception inner) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|---------|-----------------------| +| System.String | message | The exception message | +| System.Exception | inner | The inner exception | + +### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.NotServerException.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.NotServerException.md new file mode 100644 index 000000000..fe3dece32 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.NotServerException.md @@ -0,0 +1,261 @@ +--- +id: Unity.Netcode.NotServerException +title: Unity.Netcode.NotServerException +--- + +# Class NotServerException + + +Exception thrown when the operation can only be done on the server + + + + + + + +##### Inheritance + + +System.Object + + + + +System.Exception + + + + +NotServerException + + + + + + +##### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + + +##### Inherited Members + + + +System.Exception.GetBaseException() + + + + + +System.Exception.GetObjectData(System.Runtime.Serialization.SerializationInfo, +System.Runtime.Serialization.StreamingContext) + + + + + +System.Exception.GetType() + + + + + +System.Exception.ToString() + + + + + +System.Exception.Data + + + + + +System.Exception.HelpLink + + + + + +System.Exception.HResult + + + + + +System.Exception.InnerException + + + + + +System.Exception.Message + + + + + +System.Exception.Source + + + + + +System.Exception.StackTrace + + + + + +System.Exception.TargetSite + + + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class NotServerException : Exception, _Exception, ISerializable +``` + + + +### Constructors + +#### NotServerException() + + +Constructs a NotServerException + + + + + + +##### Declaration + + +``` lang-csharp +public NotServerException() +``` + + + +#### NotServerException(String) + + +Constructs a NotServerException with a message + + + + + + +##### Declaration + + +``` lang-csharp +public NotServerException(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|-----------------------| +| System.String | message | The exception message | + +#### NotServerException(String, Exception) + + +Constructs a NotServerException with a message and a inner exception + + + + + + +##### Declaration + + +``` lang-csharp +public NotServerException(string message, Exception inner) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|---------|-----------------------| +| System.String | message | The exception message | +| System.Exception | inner | The inner exception | + +### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.PendingClient.State.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.PendingClient.State.md new file mode 100644 index 000000000..aca15b6f6 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.PendingClient.State.md @@ -0,0 +1,50 @@ +--- +id: Unity.Netcode.PendingClient.State +title: Unity.Netcode.PendingClient.State +--- + +# Enum PendingClient.State + + +The states of a connection + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum State +``` + + + +### Fields + +Name + + + + + + + + + +Description + +PendingApproval + +Waiting for client connection request to be approved + +PendingConnection + +Waiting for client to send it's initial connection request + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.PendingClient.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.PendingClient.md new file mode 100644 index 000000000..d839f2878 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.PendingClient.md @@ -0,0 +1,145 @@ +--- +id: Unity.Netcode.PendingClient +title: Unity.Netcode.PendingClient +--- + +# Class PendingClient + + +A class representing a client that is currently in the process of +connecting + + + + + + + +##### Inheritance + + +System.Object + + + + +PendingClient + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class PendingClient +``` + + + +### Properties + +#### ClientId + + +The ClientId of the client + + + + + + +##### Declaration + + +``` lang-csharp +public ulong ClientId { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +#### ConnectionState + + +The state of the connection process for the client + + + + + + +##### Declaration + + +``` lang-csharp +public PendingClient.State ConnectionState { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------------|-------------| +| PendingClient.State | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.RpcAttribute.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.RpcAttribute.md new file mode 100644 index 000000000..0cbcc1227 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.RpcAttribute.md @@ -0,0 +1,415 @@ +--- +id: Unity.Netcode.RpcAttribute +title: Unity.Netcode.RpcAttribute +--- + +# Class RpcAttribute + + +Represents the common base class for Rpc attributes. + + + + + + + +##### Inheritance + + +System.Object + + + + +System.Attribute + + + + +RpcAttribute + + + + +ClientRpcAttribute + + + + +ServerRpcAttribute + + + + + + +##### Implements + + + +System.Runtime.InteropServices.\_Attribute + + + + + + +##### Inherited Members + + + +System.Attribute.Equals(System.Object) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Assembly, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Assembly, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.MemberInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.MemberInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Module, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Module, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.ParameterInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.ParameterInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetHashCode() + + + + + +System.Attribute.IsDefaultAttribute() + + + + + +System.Attribute.IsDefined(System.Reflection.Assembly, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.Assembly, System.Type, +System.Boolean) + + + + + +System.Attribute.IsDefined(System.Reflection.MemberInfo, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.MemberInfo, System.Type, +System.Boolean) + + + + + +System.Attribute.IsDefined(System.Reflection.Module, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.Module, System.Type, +System.Boolean) + + + + + +System.Attribute.IsDefined(System.Reflection.ParameterInfo, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.ParameterInfo, System.Type, +System.Boolean) + + + + + +System.Attribute.Match(System.Object) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.GetIDsOfNames(System.Guid, +System.IntPtr, System.UInt32, System.UInt32, System.IntPtr) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.GetTypeInfo(System.UInt32, +System.UInt32, System.IntPtr) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.GetTypeInfoCount(System.UInt32) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.Invoke(System.UInt32, +System.Guid, System.UInt32, System.Int16, System.IntPtr, System.IntPtr, +System.IntPtr, System.IntPtr) + + + + + +System.Attribute.TypeId + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public abstract class RpcAttribute : Attribute, _Attribute +``` + + + +### Fields + +#### Delivery + + +Type of RPC delivery method + + + + + + +##### Declaration + + +``` lang-csharp +public RpcDelivery Delivery +``` + + + +##### Field Value + +| Type | Description | +|-------------|-------------| +| RpcDelivery | | + +### Implements + + + +System.Runtime.InteropServices.\_Attribute + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.RpcDelivery.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.RpcDelivery.md new file mode 100644 index 000000000..cd975fbb8 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.RpcDelivery.md @@ -0,0 +1,50 @@ +--- +id: Unity.Netcode.RpcDelivery +title: Unity.Netcode.RpcDelivery +--- + +# Enum RpcDelivery + + +RPC delivery types + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum RpcDelivery +``` + + + +### Fields + +Name + + + + + + + + + +Description + +Reliable + +Reliable delivery + +Unreliable + +Unreliable delivery + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.SceneEvent.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.SceneEvent.md new file mode 100644 index 000000000..430b709e6 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.SceneEvent.md @@ -0,0 +1,352 @@ +--- +id: Unity.Netcode.SceneEvent +title: Unity.Netcode.SceneEvent +--- + +# Class SceneEvent + + +Used for local notifications of various scene events. The OnSceneEvent +of delegate type NetworkSceneManager.SceneEventDelegate uses this class +to provide scene event status. +*Note: This is only when EnableSceneManagement is enabled.* +*\*\*\* Do not start new scene events within scene event notification +callbacks.* +See also: +SceneEventType + + + + + + + +##### Inheritance + + +System.Object + + + + +SceneEvent + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class SceneEvent +``` + + + +### Fields + +#### AsyncOperation + + +The returned by +This is set for the following SceneEventTypes: + +- Load +- Unload + + + + + + +##### Declaration + + +``` lang-csharp +public AsyncOperation AsyncOperation +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| AsyncOperation | | + +#### ClientId + + +The client identifier can vary depending upon the following +conditions: + +1. SceneEventTypes that always set the ClientId to the local client + identifier, are initiated (and processed locally) by the + server-host, and sent to all clients to be processed. + - Load + - Unload + - Synchronize + - ReSynchronize +2. Events that always set the ClientId to the local client identifier, + are initiated (and processed locally) by a client or server-host, + and if initiated by a client will always be sent to and processed on + the server-host: + - LoadComplete + - UnloadComplete + - SynchronizeComplete +3. Events that always set the ClientId to the ServerId: + - LoadEventCompleted + - UnloadEventCompleted + + + + + + +##### Declaration + + +``` lang-csharp +public ulong ClientId +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +#### ClientsThatCompleted + + +List of clients that completed a loading or unloading event. +This is set for the following SceneEventTypes: + +- LoadEventCompleted +- UnloadEventCompleted + + + + + + +##### Declaration + + +``` lang-csharp +public List ClientsThatCompleted +``` + + + +##### Field Value + +| Type | Description | +|--------------------------------------------------|-------------| +| System.Collections.Generic.List\ | | + +#### ClientsThatTimedOut + + +List of clients that timed out during a loading or unloading event. +This is set for the following SceneEventTypes: + +- LoadEventCompleted +- UnloadEventCompleted + + + + + + +##### Declaration + + +``` lang-csharp +public List ClientsThatTimedOut +``` + + + +##### Field Value + +| Type | Description | +|--------------------------------------------------|-------------| +| System.Collections.Generic.List\ | | + +#### LoadSceneMode + + +If applicable, this reflects the type of scene loading or unloading that +is occurring. +This is set for the following SceneEventTypes: + +- Load +- Unload +- LoadComplete +- UnloadComplete +- LoadEventCompleted +- UnloadEventCompleted + + + + + + +##### Declaration + + +``` lang-csharp +public LoadSceneMode LoadSceneMode +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| LoadSceneMode | | + +#### Scene + + +When a scene is loaded, the Scene structure is returned. +This is set for the following SceneEventTypes: + +- LoadComplete + + + + + + +##### Declaration + + +``` lang-csharp +public Scene Scene +``` + + + +##### Field Value + +| Type | Description | +|-------|-------------| +| Scene | | + +#### SceneEventType + + +Will always be set to the current SceneEventType + + + + + + +##### Declaration + + +``` lang-csharp +public SceneEventType SceneEventType +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| SceneEventType | | + +#### SceneName + + +This will be set to the scene name that the event pertains to. +This is set for the following SceneEventTypes: + +- Load +- Unload +- LoadComplete +- UnloadComplete +- LoadEventCompleted +- UnloadEventCompleted + + + + + + +##### Declaration + + +``` lang-csharp +public string SceneName +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.String | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.SceneEventProgressStatus.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.SceneEventProgressStatus.md new file mode 100644 index 000000000..907c9576e --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.SceneEventProgressStatus.md @@ -0,0 +1,81 @@ +--- +id: Unity.Netcode.SceneEventProgressStatus +title: Unity.Netcode.SceneEventProgressStatus +--- + +# Enum SceneEventProgressStatus + + +Used by NetworkSceneManager to determine if a server invoked scene event +has started. The returned status is stored in the +Unity.Netcode.SceneEventProgress.Status property. +*Note: This was formally known as SwitchSceneProgress which contained +the . All s are now delivered by the OnSceneEvent event handler via the +SceneEvent parameter.* + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum SceneEventProgressStatus +``` + + + +### Fields + +Name + + + + + + + + + +Description + +InternalNetcodeError + +This is used for internal error notifications. +If you receive this event then it is most likely due to a bug (*please +open a GitHub issue with steps to replicate*). + +InvalidSceneName + +Returned if the scene name used with LoadScene(String, LoadSceneMode) or +UnloadScene(Scene)is invalid. + +None + +No scene event progress status can be used to initialize a variable that +will be checked over time. + +SceneEventInProgress + +Returned if you try to start a new scene event before a previous one is +finished. + +SceneFailedVerification + +Server side: Returned if the VerifySceneBeforeLoading delegate handler +returns false (*i.e. scene is considered not valid/safe to load*). + +SceneNotLoaded + +Returned if you try to unload a scene that was not yet loaded. + +Started + +The scene event was successfully started. + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.SceneEventType.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.SceneEventType.md new file mode 100644 index 000000000..0689b71da --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.SceneEventType.md @@ -0,0 +1,123 @@ +--- +id: Unity.Netcode.SceneEventType +title: Unity.Netcode.SceneEventType +--- + +# Enum SceneEventType + + +The different types of scene events communicated between a server and +client. +Used by NetworkSceneManager for Unity.Netcode.SceneEventMessage +messages. +*Note: This is only when EnableSceneManagement is enabled.* +See also: +SceneEvent + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum SceneEventType : byte +``` + + + +### Fields + +Name + + + + + + + + + +Description + +Load + +Load a scene +**Invocation:** Server Side +**Message Flow:** Server to client +**Event Notification:** Both server and client are notified a load scene +event started + +LoadComplete + +A client has finished loading a scene +**Invocation:** Client Side +**Message Flow:** Client to Server +**Event Notification:** Both server and client receive a local +notification. + +LoadEventCompleted + +All clients have finished loading a scene +**Invocation:** Server Side +**Message Flow:** Server to Client +**Event Notification:** Both server and client receive a local +notification containing the clients that finished as well as the clients +that timed out(*if any*). + +ReSynchronize + +Game session re-synchronization of NetworkObjects that were destroyed +during a Synchronize event +**Invocation:** Server Side +**Message Flow:** Server to client +**Event Notification:** Both server and client receive a local +notification + +Synchronize + +Synchronizes current game session state for newly approved clients +**Invocation:** Server Side +**Message Flow:** Server to client +**Event Notification:** Server and Client receives a local notification +(*server receives the ClientId being synchronized*). + +SynchronizeComplete + +A client has finished synchronizing from a Synchronize event +**Invocation:** Client Side +**Message Flow:** Client to Server +**Event Notification:** Both server and client receive a local +notification. + +Unload + +Unload a scene +**Invocation:** Server Side +**Message Flow:** Server to client +**Event Notification:** Both server and client are notified an unload +scene event started. + +UnloadComplete + +A client has finished unloading a scene +**Invocation:** Client Side +**Message Flow:** Client to Server +**Event Notification:** Both server and client receive a local +notification. + +UnloadEventCompleted + +All clients have unloaded a scene +**Invocation:** Server Side +**Message Flow:** Server to Client +**Event Notification:** Both server and client receive a local +notification containing the clients that finished as well as the clients +that timed out(*if any*). + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcAttribute.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcAttribute.md new file mode 100644 index 000000000..fa3eef8fb --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcAttribute.md @@ -0,0 +1,421 @@ +--- +id: Unity.Netcode.ServerRpcAttribute +title: Unity.Netcode.ServerRpcAttribute +--- + +# Class ServerRpcAttribute + + +Marks a method as ServerRpc. + +A ServerRpc marked method will be fired by a client but executed on the +server. + + + + + + + +##### Inheritance + + +System.Object + + + + +System.Attribute + + + + +RpcAttribute + + + + +ServerRpcAttribute + + + + + + +##### Implements + + + +System.Runtime.InteropServices.\_Attribute + + + + + + +##### Inherited Members + + + +RpcAttribute.Delivery + + + + + +System.Attribute.Equals(System.Object) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Assembly, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Assembly, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.MemberInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.MemberInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Module, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.Module, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.ParameterInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttribute(System.Reflection.ParameterInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Assembly, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.MemberInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.Module, +System.Type, System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, +System.Boolean) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, +System.Type) + + + + + +System.Attribute.GetCustomAttributes(System.Reflection.ParameterInfo, +System.Type, System.Boolean) + + + + + +System.Attribute.GetHashCode() + + + + + +System.Attribute.IsDefaultAttribute() + + + + + +System.Attribute.IsDefined(System.Reflection.Assembly, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.Assembly, System.Type, +System.Boolean) + + + + + +System.Attribute.IsDefined(System.Reflection.MemberInfo, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.MemberInfo, System.Type, +System.Boolean) + + + + + +System.Attribute.IsDefined(System.Reflection.Module, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.Module, System.Type, +System.Boolean) + + + + + +System.Attribute.IsDefined(System.Reflection.ParameterInfo, System.Type) + + + + + +System.Attribute.IsDefined(System.Reflection.ParameterInfo, System.Type, +System.Boolean) + + + + + +System.Attribute.Match(System.Object) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.GetIDsOfNames(System.Guid, +System.IntPtr, System.UInt32, System.UInt32, System.IntPtr) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.GetTypeInfo(System.UInt32, +System.UInt32, System.IntPtr) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.GetTypeInfoCount(System.UInt32) + + + + + +System.Attribute.System.Runtime.InteropServices.\_Attribute.Invoke(System.UInt32, +System.Guid, System.UInt32, System.Int16, System.IntPtr, System.IntPtr, +System.IntPtr, System.IntPtr) + + + + + +System.Attribute.TypeId + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +[AttributeUsage(AttributeTargets.Method)] +public class ServerRpcAttribute : RpcAttribute, _Attribute +``` + + + +### Fields + +#### RequireOwnership + + +Whether or not the ServerRpc should only be run if executed by the owner +of the object + + + + + + +##### Declaration + + +``` lang-csharp +public bool RequireOwnership +``` + + + +##### Field Value + +| Type | Description | +|----------------|-------------| +| System.Boolean | | + +### Implements + + + +System.Runtime.InteropServices.\_Attribute + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcParams.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcParams.md new file mode 100644 index 000000000..6977734f8 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcParams.md @@ -0,0 +1,125 @@ +--- +id: Unity.Netcode.ServerRpcParams +title: Unity.Netcode.ServerRpcParams +--- + +# Struct ServerRpcParams + + +Server-Side RPC Can be used with any sever-side remote procedure call +Note: typically this is use primarily for the ServerRpcReceiveParams + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ServerRpcParams +``` + + + +### Fields + +#### Receive + + +The client RPC receive parameters provides you with the sender's +identifier + + + + + + +##### Declaration + + +``` lang-csharp +public ServerRpcReceiveParams Receive +``` + + + +##### Field Value + +| Type | Description | +|------------------------|-------------| +| ServerRpcReceiveParams | | + +#### Send + + +The server RPC send parameters (currently a place holder) + + + + + + +##### Declaration + + +``` lang-csharp +public ServerRpcSendParams Send +``` + + + +##### Field Value + +| Type | Description | +|---------------------|-------------| +| ServerRpcSendParams | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcReceiveParams.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcReceiveParams.md new file mode 100644 index 000000000..da2f07c9d --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcReceiveParams.md @@ -0,0 +1,98 @@ +--- +id: Unity.Netcode.ServerRpcReceiveParams +title: Unity.Netcode.ServerRpcReceiveParams +--- + +# Struct ServerRpcReceiveParams + + +The receive parameters for server-side remote procedure calls + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ServerRpcReceiveParams +``` + + + +### Fields + +#### SenderClientId + + +Server-Side RPC The client identifier of the sender + + + + + + +##### Declaration + + +``` lang-csharp +public ulong SenderClientId +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcSendParams.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcSendParams.md new file mode 100644 index 000000000..7c7fbd497 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.ServerRpcSendParams.md @@ -0,0 +1,73 @@ +--- +id: Unity.Netcode.ServerRpcSendParams +title: Unity.Netcode.ServerRpcSendParams +--- + +# Struct ServerRpcSendParams + + +Server-Side RPC Place holder. ServerRpcParams Note: Clients always send +to one destination when sending RPCs to the server so this structure is +a place holder + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct ServerRpcSendParams +``` + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.SpawnStateException.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.SpawnStateException.md new file mode 100644 index 000000000..b29fb39b7 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.SpawnStateException.md @@ -0,0 +1,261 @@ +--- +id: Unity.Netcode.SpawnStateException +title: Unity.Netcode.SpawnStateException +--- + +# Class SpawnStateException + + +Exception thrown when an object is not yet spawned + + + + + + + +##### Inheritance + + +System.Object + + + + +System.Exception + + + + +SpawnStateException + + + + + + +##### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + + +##### Inherited Members + + + +System.Exception.GetBaseException() + + + + + +System.Exception.GetObjectData(System.Runtime.Serialization.SerializationInfo, +System.Runtime.Serialization.StreamingContext) + + + + + +System.Exception.GetType() + + + + + +System.Exception.ToString() + + + + + +System.Exception.Data + + + + + +System.Exception.HelpLink + + + + + +System.Exception.HResult + + + + + +System.Exception.InnerException + + + + + +System.Exception.Message + + + + + +System.Exception.Source + + + + + +System.Exception.StackTrace + + + + + +System.Exception.TargetSite + + + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class SpawnStateException : Exception, _Exception, ISerializable +``` + + + +### Constructors + +#### SpawnStateException() + + +Constructs a SpawnStateException + + + + + + +##### Declaration + + +``` lang-csharp +public SpawnStateException() +``` + + + +#### SpawnStateException(String) + + +Constructs a SpawnStateException with a message + + + + + + +##### Declaration + + +``` lang-csharp +public SpawnStateException(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|-----------------------| +| System.String | message | The exception message | + +#### SpawnStateException(String, Exception) + + +Constructs a SpawnStateException with a message and a inner exception + + + + + + +##### Declaration + + +``` lang-csharp +public SpawnStateException(string message, Exception inner) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|---------|-----------------------| +| System.String | message | The exception message | +| System.Exception | inner | The inner exception | + +### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.ErrorUtilities.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.ErrorUtilities.md new file mode 100644 index 000000000..952c055ee --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.ErrorUtilities.md @@ -0,0 +1,127 @@ +--- +id: Unity.Netcode.Transports.UTP.ErrorUtilities +title: Unity.Netcode.Transports.UTP.ErrorUtilities +--- + +# Class ErrorUtilities + + +Helper utility class to convert error codes to human readable error +messages. + + + + + + + +##### Inheritance + + +System.Object + + + + +ErrorUtilities + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode.Transports.UTP + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public static class ErrorUtilities +``` + + + +### Methods + +#### ErrorToString(Networking.Transport.Error.StatusCode, UInt64) + + +Convert error code to human readable error message. + + + + + + +##### Declaration + + +``` lang-csharp +public static string ErrorToString(Networking.Transport.Error.StatusCode error, ulong connectionId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------------------------------|--------------|------------------------------------| +| Networking.Transport.Error.StatusCode | error | Status code of the error | +| System.UInt64 | connectionId | Subject connection ID of the error | + +##### Returns + +| Type | Description | +|---------------|-------------------------------| +| System.String | Human readable error message. | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.INetworkStreamDriverConstructor.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.INetworkStreamDriverConstructor.md new file mode 100644 index 000000000..e0a150ed8 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.INetworkStreamDriverConstructor.md @@ -0,0 +1,62 @@ +--- +id: Unity.Netcode.Transports.UTP.INetworkStreamDriverConstructor +title: Unity.Netcode.Transports.UTP.INetworkStreamDriverConstructor +--- + +# Interface INetworkStreamDriverConstructor + + +Provides an interface that overrides the ability to create your own +drivers and pipelines + + + + + + +###### **Namespace**: Unity.Netcode.Transports.UTP + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public interface INetworkStreamDriverConstructor +``` + + + +### Methods + +#### CreateDriver(UnityTransport, out NetworkDriver, out NetworkPipeline, out NetworkPipeline, out NetworkPipeline) + + +Creates the internal NetworkDriver + + + + + + +##### Declaration + + +``` lang-csharp +void CreateDriver(UnityTransport transport, out NetworkDriver driver, out NetworkPipeline unreliableFragmentedPipeline, out NetworkPipeline unreliableSequencedFragmentedPipeline, out NetworkPipeline reliableSequencedPipeline) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------|---------------------------------------|---------------------------------------------------| +| UnityTransport | transport | The owner transport | +| NetworkDriver | driver | The driver | +| NetworkPipeline | unreliableFragmentedPipeline | The UnreliableFragmented NetworkPipeline | +| NetworkPipeline | unreliableSequencedFragmentedPipeline | The UnreliableSequencedFragmented NetworkPipeline | +| NetworkPipeline | reliableSequencedPipeline | The ReliableSequenced NetworkPipeline | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.NetworkMetricsContext.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.NetworkMetricsContext.md new file mode 100644 index 000000000..91b28284a --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.NetworkMetricsContext.md @@ -0,0 +1,123 @@ +--- +id: Unity.Netcode.Transports.UTP.NetworkMetricsContext +title: Unity.Netcode.Transports.UTP.NetworkMetricsContext +--- + +# Struct NetworkMetricsContext + + +Caching structure to track network metrics related information. + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode.Transports.UTP + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public struct NetworkMetricsContext +``` + + + +### Fields + +#### PacketReceivedCount + + +The number of packet received. + + + + + + +##### Declaration + + +``` lang-csharp +public uint PacketReceivedCount +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt32 | | + +#### PacketSentCount + + +The number of packet sent. + + + + + + +##### Declaration + + +``` lang-csharp +public uint PacketSentCount +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt32 | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.ConnectionAddressData.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.ConnectionAddressData.md new file mode 100644 index 000000000..0d9a08086 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.ConnectionAddressData.md @@ -0,0 +1,202 @@ +--- +id: Unity.Netcode.Transports.UTP.UnityTransport.ConnectionAddressData +title: Unity.Netcode.Transports.UTP.UnityTransport.ConnectionAddressData +--- + +# Struct UnityTransport.ConnectionAddressData + + +Structure to store the address to connect to + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode.Transports.UTP + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +[Serializable] +public struct ConnectionAddressData +``` + + + +### Fields + +#### Address + + +IP address of the server (address to which clients will connect to). + + + + + + +##### Declaration + + +``` lang-csharp +public string Address +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.String | | + +#### Port + + +UDP port of the server. + + + + + + +##### Declaration + + +``` lang-csharp +public ushort Port +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.UInt16 | | + +#### ServerListenAddress + + +IP address the server will listen on. If not provided, will use +'Address'. + + + + + + +##### Declaration + + +``` lang-csharp +public string ServerListenAddress +``` + + + +##### Field Value + +| Type | Description | +|---------------|-------------| +| System.String | | + +### Properties + +#### ListenEndPoint + + +Endpoint (IP address and port) server will listen/bind on. + + + + + + +##### Declaration + + +``` lang-csharp +public readonly NetworkEndPoint ListenEndPoint { get; } +``` + + + +##### Property Value + +| Type | Description | +|-----------------|-------------| +| NetworkEndPoint | | + +#### ServerEndPoint + + +Endpoint (IP address and port) clients will connect to. + + + + + + +##### Declaration + + +``` lang-csharp +public readonly NetworkEndPoint ServerEndPoint { get; } +``` + + + +##### Property Value + +| Type | Description | +|-----------------|-------------| +| NetworkEndPoint | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.ProtocolType.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.ProtocolType.md new file mode 100644 index 000000000..50fce6765 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.ProtocolType.md @@ -0,0 +1,50 @@ +--- +id: Unity.Netcode.Transports.UTP.UnityTransport.ProtocolType +title: Unity.Netcode.Transports.UTP.UnityTransport.ProtocolType +--- + +# Enum UnityTransport.ProtocolType + + +Enum type stating the type of protocol + + + + + + +###### **Namespace**: Unity.Netcode.Transports.UTP + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public enum ProtocolType +``` + + + +### Fields + +Name + + + + + + + + + +Description + +RelayUnityTransport + +Unity Transport Protocol over Relay + +UnityTransport + +Unity Transport Protocol + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.SimulatorParameters.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.SimulatorParameters.md new file mode 100644 index 000000000..7704ae3e4 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.SimulatorParameters.md @@ -0,0 +1,154 @@ +--- +id: Unity.Netcode.Transports.UTP.UnityTransport.SimulatorParameters +title: Unity.Netcode.Transports.UTP.UnityTransport.SimulatorParameters +--- + +# Struct UnityTransport.SimulatorParameters + + +Parameters for the Network Simulator + + + + + + + +##### Inherited Members + + + +System.ValueType.Equals(System.Object) + + + + + +System.ValueType.GetHashCode() + + + + + +System.ValueType.ToString() + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetType() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode.Transports.UTP + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +[Serializable] +public struct SimulatorParameters +``` + + + +### Fields + +#### PacketDelayMS + + +Delay to add to every send and received packet (in milliseconds). Only +applies in the editor and in development builds. The value is ignored in +production builds. + + + + + + +##### Declaration + + +``` lang-csharp +public int PacketDelayMS +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### PacketDropRate + + +Percentage of sent and received packets to drop. Only applies in the +editor and in the editor and in developments builds. + + + + + + +##### Declaration + + +``` lang-csharp +public int PacketDropRate +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### PacketJitterMS + + +Jitter (random variation) to add/substract to the packet delay (in +milliseconds). Only applies in the editor and in development builds. The +value is ignored in production builds. + + + + + + +##### Declaration + + +``` lang-csharp +public int PacketJitterMS +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.md new file mode 100644 index 000000000..64b19a37c --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.md @@ -0,0 +1,1065 @@ +--- +id: Unity.Netcode.Transports.UTP.UnityTransport +title: Unity.Netcode.Transports.UTP.UnityTransport +--- + +# Class UnityTransport + + +The Netcode for GameObjects NetworkTransport for UnityTransport. Note: +This is highly recommended to use over UNet. + + + + + + + +##### Inheritance + + +System.Object + + + + +NetworkTransport + + + + +UnityTransport + + + + + + +##### Implements + + + +INetworkStreamDriverConstructor + + + + + + +##### Inherited Members + + + +NetworkTransport.IsSupported + + + + + +NetworkTransport.OnTransportEvent + + + + + +NetworkTransport.InvokeOnTransportEvent(NetworkEvent, UInt64, +ArraySegment\, Single) + + + + + +###### **Namespace**: Unity.Netcode.Transports.UTP + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class UnityTransport : NetworkTransport, INetworkStreamDriverConstructor +``` + + + +### Fields + +#### ConnectionData + + +The connection (address) data for this UnityTransport instance. This is +where you can change IP Address, Port, or server's listen address. +UnityTransport.ConnectionAddressData + + + + + + +##### Declaration + + +``` lang-csharp +public UnityTransport.ConnectionAddressData ConnectionData +``` + + + +##### Field Value + +| Type | Description | +|--------------------------------------|-------------| +| UnityTransport.ConnectionAddressData | | + +#### DebugSimulator + + +Can be used to simulate poor network conditions such as: + +- packet delay/latency +- packet jitter (variances in latency, see: + https://en.wikipedia.org/wiki/Jitter) +- packet drop rate (packet loss) + + + + + + +##### Declaration + + +``` lang-csharp +public UnityTransport.SimulatorParameters DebugSimulator +``` + + + +##### Field Value + +| Type | Description | +|------------------------------------|-------------| +| UnityTransport.SimulatorParameters | | + +#### InitialMaxPacketQueueSize + + +The default maximum (receive) packet queue size + + + + + + +##### Declaration + + +``` lang-csharp +public const int InitialMaxPacketQueueSize = 128 +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### InitialMaxPayloadSize + + +The default maximum payload size + + + + + + +##### Declaration + + +``` lang-csharp +public const int InitialMaxPayloadSize = 6144 +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### InitialMaxSendQueueSize + + +The default maximum send queue size + + + + + + +##### Declaration + + +``` lang-csharp +public const int InitialMaxSendQueueSize = 98304 +``` + + + +##### Field Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### s_DriverConstructor + + +The global INetworkStreamDriverConstructor implementation + + + + + + +##### Declaration + + +``` lang-csharp +public static INetworkStreamDriverConstructor s_DriverConstructor +``` + + + +##### Field Value + +| Type | Description | +|---------------------------------|-------------| +| INetworkStreamDriverConstructor | | + +### Properties + +#### ConnectTimeoutMS + + +Timeout in milliseconds indicating how long we will wait until we send a +new connection attempt. + + + + + + +##### Declaration + + +``` lang-csharp +public int ConnectTimeoutMS { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### DisconnectTimeoutMS + + +Inactivity timeout after which a connection will be disconnected. + + + + + + +##### Declaration + + +``` lang-csharp +public int DisconnectTimeoutMS { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +##### Remarks + + +The connection needs to receive data from the connected endpoint within +this timeout. Note that with heartbeats enabled, simply not sending any +data will not be enough to trigger this timeout (since heartbeats count +as connection events). + + + +#### DriverConstructor + + +Returns either the global INetworkStreamDriverConstructor implementation +or the current UnityTransport instance + + + + + + +##### Declaration + + +``` lang-csharp +public INetworkStreamDriverConstructor DriverConstructor { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------------------------|-------------| +| INetworkStreamDriverConstructor | | + +#### HeartbeatTimeoutMS + + +Timeout in milliseconds after which a heartbeat is sent if there is no +activity. + + + + + + +##### Declaration + + +``` lang-csharp +public int HeartbeatTimeoutMS { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### MaxConnectAttempts + + +The maximum amount of connection attempts we will try before +disconnecting. + + + + + + +##### Declaration + + +``` lang-csharp +public int MaxConnectAttempts { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### MaxPacketQueueSize + + +The maximum amount of packets that can be in the internal send/receive +queues. + + + + + + +##### Declaration + + +``` lang-csharp +public int MaxPacketQueueSize { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +##### Remarks + + +Basically this is how many packets can be sent/received in a single +update/frame. + + + +#### MaxPayloadSize + + +The maximum size of a payload that can be handled by the transport. + + + + + + +##### Declaration + + +``` lang-csharp +public int MaxPayloadSize { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +#### MaxSendQueueSize + + +The maximum size in bytes of the transport send queue. + + + + + + +##### Declaration + + +``` lang-csharp +public int MaxSendQueueSize { get; set; } +``` + + + +##### Property Value + +| Type | Description | +|--------------|-------------| +| System.Int32 | | + +##### Remarks + + +The send queue accumulates messages for batching and stores messages +when other internal send queues are full. If you routinely observe an +error about too many in-flight packets, try increasing this. + + + +#### Protocol + + +The current ProtocolType used by the transport + + + + + + +##### Declaration + + +``` lang-csharp +public UnityTransport.ProtocolType Protocol { get; } +``` + + + +##### Property Value + +| Type | Description | +|-----------------------------|-------------| +| UnityTransport.ProtocolType | | + +#### ServerClientId + + +The client id used to represent the server. + + + + + + +##### Declaration + + +``` lang-csharp +public override ulong ServerClientId { get; } +``` + + + +##### Property Value + +| Type | Description | +|---------------|-------------| +| System.UInt64 | | + +##### Overrides + + + +NetworkTransport.ServerClientId + + + +### Methods + +#### CreateDriver(UnityTransport, out NetworkDriver, out NetworkPipeline, out NetworkPipeline, out NetworkPipeline) + + +Creates the internal NetworkDriver + + + + + + +##### Declaration + + +``` lang-csharp +public void CreateDriver(UnityTransport transport, out NetworkDriver driver, out NetworkPipeline unreliableFragmentedPipeline, out NetworkPipeline unreliableSequencedFragmentedPipeline, out NetworkPipeline reliableSequencedPipeline) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------|---------------------------------------|---------------------------------------------------| +| UnityTransport | transport | The owner transport | +| NetworkDriver | driver | The driver | +| NetworkPipeline | unreliableFragmentedPipeline | The UnreliableFragmented NetworkPipeline | +| NetworkPipeline | unreliableSequencedFragmentedPipeline | The UnreliableSequencedFragmented NetworkPipeline | +| NetworkPipeline | reliableSequencedPipeline | The ReliableSequenced NetworkPipeline | + +#### DisconnectLocalClient() + + +Disconnects the local client from the remote + + + + + + +##### Declaration + + +``` lang-csharp +public override void DisconnectLocalClient() +``` + + + +##### Overrides + + + +NetworkTransport.DisconnectLocalClient() + + + +#### DisconnectRemoteClient(UInt64) + + +Disconnects a remote client from the server + + + + + + +##### Declaration + + +``` lang-csharp +public override void DisconnectRemoteClient(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|--------------------------| +| System.UInt64 | clientId | The client to disconnect | + +##### Overrides + + + +NetworkTransport.DisconnectRemoteClient(UInt64) + + + +#### GetCurrentRtt(UInt64) + + +Gets the current RTT for a specific client + + + + + + +##### Declaration + + +``` lang-csharp +public override ulong GetCurrentRtt(ulong clientId) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|----------|-----------------------| +| System.UInt64 | clientId | The client RTT to get | + +##### Returns + +| Type | Description | +|---------------|-------------| +| System.UInt64 | The RTT | + +##### Overrides + + + +NetworkTransport.GetCurrentRtt(UInt64) + + + +#### Initialize(NetworkManager) + + +Initializes the transport + + + + + + +##### Declaration + + +``` lang-csharp +public override void Initialize(NetworkManager networkManager = null) +``` + + + +##### Parameters + +| Type | Name | Description | +|----------------|----------------|------------------------------------------------------------| +| NetworkManager | networkManager | The NetworkManager that initialized and owns the transport | + +##### Overrides + + + +NetworkTransport.Initialize(NetworkManager) + + + +#### PollEvent(out UInt64, out ArraySegment\, out Single) + + +Polls for incoming events, with an extra output parameter to report the +precise time the event was received. + + + + + + +##### Declaration + + +``` lang-csharp +public override NetworkEvent PollEvent(out ulong clientId, out ArraySegment payload, out float receiveTime) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------------------|-------------|----------------------------------------------------------------------------| +| System.UInt64 | clientId | The clientId this event is for | +| System.ArraySegment\ | payload | The incoming data payload | +| System.Single | receiveTime | The time the event was received, as reported by Time.realtimeSinceStartup. | + +##### Returns + +| Type | Description | +|--------------|------------------------| +| NetworkEvent | Returns the event type | + +##### Overrides + + + +NetworkTransport.PollEvent(out UInt64, out ArraySegment\, out +Single) + + + +#### Send(UInt64, ArraySegment\, NetworkDelivery) + + +Send a payload to the specified clientId, data and networkDelivery. + + + + + + +##### Declaration + + +``` lang-csharp +public override void Send(ulong clientId, ArraySegment payload, NetworkDelivery networkDelivery) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------------------------|-----------------|-------------------------------------------| +| System.UInt64 | clientId | The clientId to send to | +| System.ArraySegment\ | payload | The data to send | +| NetworkDelivery | networkDelivery | The delivery type (QoS) to send data with | + +##### Overrides + + + +NetworkTransport.Send(UInt64, ArraySegment\, NetworkDelivery) + + + +#### SetClientRelayData(String, UInt16, Byte\[\], Byte\[\], Byte\[\], Byte\[\], Boolean) + + +Set the relay server data for the host. + + + + + + +##### Declaration + + +``` lang-csharp +public void SetClientRelayData(string ipAddress, ushort port, byte[] allocationId, byte[] key, byte[] connectionData, byte[] hostConnectionData, bool isSecure = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------|--------------------|-----------------------------------------------| +| System.String | ipAddress | IP address of the relay server. | +| System.UInt16 | port | UDP port of the relay server. | +| System.Byte\[\] | allocationId | Allocation ID as a byte array. | +| System.Byte\[\] | key | Allocation key as a byte array. | +| System.Byte\[\] | connectionData | Connection data as a byte array. | +| System.Byte\[\] | hostConnectionData | Host's connection data as a byte array. | +| System.Boolean | isSecure | Whether the connection is secure (uses DTLS). | + +#### SetConnectionData(NetworkEndPoint, NetworkEndPoint) + + +Sets IP and Port information. This will be ignored if using the Unity +Relay and you should call SetRelayServerData(String, UInt16, Byte\[\], +Byte\[\], Byte\[\], Byte\[\], Boolean) + + + + + + +##### Declaration + + +``` lang-csharp +public void SetConnectionData(NetworkEndPoint endPoint, NetworkEndPoint listenEndPoint = null) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------|----------------|---------------------------| +| NetworkEndPoint | endPoint | The remote end point | +| NetworkEndPoint | listenEndPoint | The local listen endpoint | + +#### SetConnectionData(String, UInt16, String) + + +Sets IP and Port information. This will be ignored if using the Unity +Relay and you should call SetRelayServerData(String, UInt16, Byte\[\], +Byte\[\], Byte\[\], Byte\[\], Boolean) + + + + + + +##### Declaration + + +``` lang-csharp +public void SetConnectionData(string ipv4Address, ushort port, string listenAddress = null) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------------|--------------------------| +| System.String | ipv4Address | The remote IP address | +| System.UInt16 | port | The remote port | +| System.String | listenAddress | The local listen address | + +#### SetDebugSimulatorParameters(Int32, Int32, Int32) + + +Set the parameters for the debug simulator. + + + + + + +##### Declaration + + +``` lang-csharp +public void SetDebugSimulatorParameters(int packetDelay, int packetJitter, int dropRate) +``` + + + +##### Parameters + +| Type | Name | Description | +|--------------|--------------|--------------------------------| +| System.Int32 | packetDelay | Packet delay in milliseconds. | +| System.Int32 | packetJitter | Packet jitter in milliseconds. | +| System.Int32 | dropRate | Packet drop percentage. | + +#### SetHostRelayData(String, UInt16, Byte\[\], Byte\[\], Byte\[\], Boolean) + + +Set the relay server data for the host. + + + + + + +##### Declaration + + +``` lang-csharp +public void SetHostRelayData(string ipAddress, ushort port, byte[] allocationId, byte[] key, byte[] connectionData, bool isSecure = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------|----------------|-----------------------------------------------| +| System.String | ipAddress | IP address of the relay server. | +| System.UInt16 | port | UDP port of the relay server. | +| System.Byte\[\] | allocationId | Allocation ID as a byte array. | +| System.Byte\[\] | key | Allocation key as a byte array. | +| System.Byte\[\] | connectionData | Connection data as a byte array. | +| System.Boolean | isSecure | Whether the connection is secure (uses DTLS). | + +#### SetRelayServerData(String, UInt16, Byte\[\], Byte\[\], Byte\[\], Byte\[\], Boolean) + + +Set the relay server data for the server. + + + + + + +##### Declaration + + +``` lang-csharp +public void SetRelayServerData(string ipv4Address, ushort port, byte[] allocationIdBytes, byte[] keyBytes, byte[] connectionDataBytes, byte[] hostConnectionDataBytes = null, bool isSecure = false) +``` + + + +##### Parameters + +| Type | Name | Description | +|-----------------|-------------------------|-----------------------------------------------| +| System.String | ipv4Address | IP address of the relay server. | +| System.UInt16 | port | UDP port of the relay server. | +| System.Byte\[\] | allocationIdBytes | Allocation ID as a byte array. | +| System.Byte\[\] | keyBytes | Allocation key as a byte array. | +| System.Byte\[\] | connectionDataBytes | Connection data as a byte array. | +| System.Byte\[\] | hostConnectionDataBytes | The HostConnectionData as a byte array. | +| System.Boolean | isSecure | Whether the connection is secure (uses DTLS). | + +#### Shutdown() + + +Shuts down the transport + + + + + + +##### Declaration + + +``` lang-csharp +public override void Shutdown() +``` + + + +##### Overrides + + + +NetworkTransport.Shutdown() + + + +#### StartClient() + + +Connects client to the server Note: When this method returns false it +could mean: + +- You are trying to start a client that is already started +- It failed during the initial port binding when attempting to begin + to connect + + + + + + +##### Declaration + + +``` lang-csharp +public override bool StartClient() +``` + + + +##### Returns + +| Type | Description | +|----------------|---------------------------------------------------------------------------| +| System.Boolean | true if the client was started and false if it failed to start the client | + +##### Overrides + + + +NetworkTransport.StartClient() + + + +#### StartServer() + + +Starts to listening for incoming clients Note: When this method returns +false it could mean: + +- You are trying to start a client that is already started +- It failed during the initial port binding when attempting to begin + to connect + + + + + + +##### Declaration + + +``` lang-csharp +public override bool StartServer() +``` + + + +##### Returns + +| Type | Description | +|----------------|---------------------------------------------------------------------------| +| System.Boolean | true if the server was started and false if it failed to start the server | + +##### Overrides + + + +NetworkTransport.StartServer() + + + +### Implements + + + +INetworkStreamDriverConstructor + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.md new file mode 100644 index 000000000..1542a6e78 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.Transports.UTP.md @@ -0,0 +1,78 @@ +--- +id: Unity.Netcode.Transports.UTP +title: Unity.Netcode.Transports.UTP +--- + +# Namespace Unity.Netcode.Transports.UTP + + + + + + + + + + +### Classes + +#### ErrorUtilities + + +Helper utility class to convert error codes to human readable error +messages. + + + +#### UnityTransport + + +The Netcode for GameObjects NetworkTransport for UnityTransport. Note: +This is highly recommended to use over UNet. + + + +### Structs + +#### NetworkMetricsContext + + +Caching structure to track network metrics related information. + + + +#### UnityTransport.ConnectionAddressData + + +Structure to store the address to connect to + + + +#### UnityTransport.SimulatorParameters + + +Parameters for the Network Simulator + + + +### Interfaces + +#### INetworkStreamDriverConstructor + + +Provides an interface that overrides the ability to create your own +drivers and pipelines + + + +### Enums + +#### UnityTransport.ProtocolType + + +Enum type stating the type of protocol + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.UserNetworkVariableSerialization-1.ReadValueDelegate.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.UserNetworkVariableSerialization-1.ReadValueDelegate.md new file mode 100644 index 000000000..cfe81630d --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.UserNetworkVariableSerialization-1.ReadValueDelegate.md @@ -0,0 +1,37 @@ +--- +id: Unity.Netcode.UserNetworkVariableSerialization-1.ReadValueDelegate +title: Unity.Netcode.UserNetworkVariableSerialization-1.ReadValueDelegate +--- + +# Delegate UserNetworkVariableSerialization\.ReadValueDelegate + + +The read value delegate handler definition + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void ReadValueDelegate(FastBufferReader reader, out T value); +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|----------------------------------------------------| +| FastBufferReader | reader | The FastBufferReader to read the value of type `T` | +| T | value | The value of type `T` to be read | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.UserNetworkVariableSerialization-1.WriteValueDelegate.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.UserNetworkVariableSerialization-1.WriteValueDelegate.md new file mode 100644 index 000000000..1661b8789 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.UserNetworkVariableSerialization-1.WriteValueDelegate.md @@ -0,0 +1,37 @@ +--- +id: Unity.Netcode.UserNetworkVariableSerialization-1.WriteValueDelegate +title: Unity.Netcode.UserNetworkVariableSerialization-1.WriteValueDelegate +--- + +# Delegate UserNetworkVariableSerialization\.WriteValueDelegate + + +The write value delegate handler definition + + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public delegate void WriteValueDelegate(FastBufferWriter writer, in T value); +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|--------|-----------------------------------------------------| +| FastBufferWriter | writer | The FastBufferWriter to write the value of type `T` | +| T | value | The value of type `T` to be written | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.UserNetworkVariableSerialization-1.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.UserNetworkVariableSerialization-1.md new file mode 100644 index 000000000..1bf4fc342 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.UserNetworkVariableSerialization-1.md @@ -0,0 +1,157 @@ +--- +id: Unity.Netcode.UserNetworkVariableSerialization-1 +title: Unity.Netcode.UserNetworkVariableSerialization-1 +--- + +# Class UserNetworkVariableSerialization\ + + +This class is used to register user serialization with NetworkVariables +for types that are serialized via user serialization, such as with +FastBufferReader and FastBufferWriter extension methods. Finding those +methods isn't achievable efficiently at runtime, so this allows users to +tell NetworkVariable about those extension methods (or simply pass in a +lambda) + + + + + + + +##### Inheritance + + +System.Object + + + + +UserNetworkVariableSerialization\ + + + + + + +##### Inherited Members + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.GetType() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +System.Object.ToString() + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class UserNetworkVariableSerialization +``` + + + +##### Type Parameters + +| Name | Description | +|------|-------------| +| T | | + +### Fields + +#### ReadValue + + +The UserNetworkVariableSerialization\.ReadValueDelegate delegate +handler declaration + + + + + + +##### Declaration + + +``` lang-csharp +public static UserNetworkVariableSerialization.ReadValueDelegate ReadValue +``` + + + +##### Field Value + +| Type | Description | +|--------------------------------------------------------|-------------| +| UserNetworkVariableSerialization.ReadValueDelegate\<\> | | + +#### WriteValue + + +The UserNetworkVariableSerialization\.WriteValueDelegate delegate +handler declaration + + + + + + +##### Declaration + + +``` lang-csharp +public static UserNetworkVariableSerialization.WriteValueDelegate WriteValue +``` + + + +##### Field Value + +| Type | Description | +|---------------------------------------------------------|-------------| +| UserNetworkVariableSerialization.WriteValueDelegate\<\> | | + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.VisibilityChangeException.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.VisibilityChangeException.md new file mode 100644 index 000000000..0bc1035c8 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.VisibilityChangeException.md @@ -0,0 +1,262 @@ +--- +id: Unity.Netcode.VisibilityChangeException +title: Unity.Netcode.VisibilityChangeException +--- + +# Class VisibilityChangeException + + +Exception thrown when a visibility change fails + + + + + + + +##### Inheritance + + +System.Object + + + + +System.Exception + + + + +VisibilityChangeException + + + + + + +##### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + + +##### Inherited Members + + + +System.Exception.GetBaseException() + + + + + +System.Exception.GetObjectData(System.Runtime.Serialization.SerializationInfo, +System.Runtime.Serialization.StreamingContext) + + + + + +System.Exception.GetType() + + + + + +System.Exception.ToString() + + + + + +System.Exception.Data + + + + + +System.Exception.HelpLink + + + + + +System.Exception.HResult + + + + + +System.Exception.InnerException + + + + + +System.Exception.Message + + + + + +System.Exception.Source + + + + + +System.Exception.StackTrace + + + + + +System.Exception.TargetSite + + + + + +System.Object.Equals(System.Object) + + + + + +System.Object.Equals(System.Object, System.Object) + + + + + +System.Object.GetHashCode() + + + + + +System.Object.MemberwiseClone() + + + + + +System.Object.ReferenceEquals(System.Object, System.Object) + + + + + +###### **Namespace**: Unity.Netcode + +###### **Assembly**: MLAPI.dll + +##### Syntax + + +``` lang-csharp +public class VisibilityChangeException : Exception, _Exception, ISerializable +``` + + + +### Constructors + +#### VisibilityChangeException() + + +Constructs a VisibilityChangeException + + + + + + +##### Declaration + + +``` lang-csharp +public VisibilityChangeException() +``` + + + +#### VisibilityChangeException(String) + + +Constructs a VisibilityChangeException with a message + + + + + + +##### Declaration + + +``` lang-csharp +public VisibilityChangeException(string message) +``` + + + +##### Parameters + +| Type | Name | Description | +|---------------|---------|-----------------------| +| System.String | message | The exception message | + +#### VisibilityChangeException(String, Exception) + + +Constructs a VisibilityChangeException with a message and a inner +exception + + + + + + +##### Declaration + + +``` lang-csharp +public VisibilityChangeException(string message, Exception inner) +``` + + + +##### Parameters + +| Type | Name | Description | +|------------------|---------|-----------------------| +| System.String | message | The exception message | +| System.Exception | inner | The inner exception | + +### Implements + + + +System.Runtime.InteropServices.\_Exception + + + + + +System.Runtime.Serialization.ISerializable + + + + + diff --git a/versioned_docs/version-1.0.0/api/Unity.Netcode.md b/versioned_docs/version-1.0.0/api/Unity.Netcode.md new file mode 100644 index 000000000..3e976e441 --- /dev/null +++ b/versioned_docs/version-1.0.0/api/Unity.Netcode.md @@ -0,0 +1,860 @@ +--- +id: Unity.Netcode +title: Unity.Netcode +--- + +# Namespace Unity.Netcode + + + + + + + + + + +### Classes + +#### Arithmetic + + +Arithmetic helper class + + + +#### BitCounter + + +Utility class to count the number of bytes or bits needed to serialize a +value. + + + +#### BytePacker + + +Utility class for packing values in serialization. ByteUnpacker to +unpack packed values. + + + +#### ByteUnpacker + + +Byte Unpacking Helper Class Use this class to unpack values during +deserialization for values that were packed. BytePacker to pack unpacked +values + + + +#### ClientRpcAttribute + + +Marks a method as ClientRpc. + +A ClientRpc marked method will be fired by the server but executed on +clients. + + + +#### CustomMessagingManager + + +The manager class to manage custom messages, note that this is different +from the NetworkManager custom messages. These are named and are much +easier to use. + + + +#### InvalidChannelException + + +Exception thrown when a specified network channel is invalid + + + +#### InvalidParentException + + +Exception thrown when the new parent candidate of the NetworkObject is +not valid + + + +#### NetworkBehaviour + + +The base class to override to write network code. Inherits MonoBehaviour + + + +#### NetworkBehaviourUpdater + + +An helper class that helps NetworkManager update NetworkBehaviours and +replicate them down to connected clients. + + + +#### NetworkClient + + +A NetworkClient + + + +#### NetworkConfig + + +The configuration object used to start server, client and hosts + + + +#### NetworkConfigurationException + + +Exception thrown when a change to a configuration is wrong + + + +#### NetworkList\ + + +Event based NetworkVariable container for syncing Lists + + + +#### NetworkLog + + +Helper class for logging + + + +#### NetworkManager + + +The main component of the library + + + +#### NetworkManager.ConnectionApprovalResponse + + +Connection Approval Response + + + +#### NetworkObject + + +A component used to identify that a GameObject in the network + + + +#### NetworkPrefabHandler + + +Primary handler to add or remove customized spawn and destroy handlers +for a network prefab (i.e. a prefab with a NetworkObject component) +Register custom prefab handlers by implementing the +INetworkPrefabInstanceHandler interface. + + + +#### NetworkSceneManager + + +Main class for managing network scenes when EnableSceneManagement is +enabled. Uses the Unity.Netcode.SceneEventMessage message to communicate +Unity.Netcode.SceneEventData between the server and client(s) + + + +#### NetworkSpawnManager + + +Class that handles object spawning + + + +#### NetworkTickSystem + + +Provides discretized time. This is useful for games that require ticks +happening at regular interval on the server and clients. + + + +#### NetworkTimeSystem + + +NetworkTimeSystem is a standalone system which can be used to run a +network time simulation. The network time system maintains both a local +and a server time. The local time is based on + + + +#### NetworkTransport + + +The generic transport class all Netcode for GameObjects network +transport implementations derive from. Use this class to add a custom +transport. for an example of how a transport is integrated + + + +#### NetworkUpdateLoop + + +Represents the network update loop injected into low-level player loop +in Unity. + + + +#### NetworkVariable\ + + +A variable that can be synchronized over the network. + + + +#### NetworkVariableBase + + +Interface for network value containers + + + +#### NetworkVariableSerialization\ + + +Support methods for reading/writing NetworkVariables Because there are +multiple overloads of WriteValue/ReadValue based on different generic +constraints, but there's no way to achieve the same thing with a class, +this sets up various read/write schemes based on which constraints are +met by `T` using reflection, which is done at module load time. + + + +#### NotListeningException + + +Exception thrown when the operation require NetworkManager to be +listening. + + + +#### NotServerException + + +Exception thrown when the operation can only be done on the server + + + +#### PendingClient + + +A class representing a client that is currently in the process of +connecting + + + +#### RpcAttribute + + +Represents the common base class for Rpc attributes. + + + +#### SceneEvent + + +Used for local notifications of various scene events. The OnSceneEvent +of delegate type NetworkSceneManager.SceneEventDelegate uses this class +to provide scene event status. +*Note: This is only when EnableSceneManagement is enabled.* +*\*\*\* Do not start new scene events within scene event notification +callbacks.* +See also: +SceneEventType + + + +#### ServerRpcAttribute + + +Marks a method as ServerRpc. + +A ServerRpc marked method will be fired by a client but executed on the +server. + + + +#### SpawnStateException + + +Exception thrown when an object is not yet spawned + + + +#### UserNetworkVariableSerialization\ + + +This class is used to register user serialization with NetworkVariables +for types that are serialized via user serialization, such as with +FastBufferReader and FastBufferWriter extension methods. Finding those +methods isn't achievable efficiently at runtime, so this allows users to +tell NetworkVariable about those extension methods (or simply pass in a +lambda) + + + +#### VisibilityChangeException + + +Exception thrown when a visibility change fails + + + +### Structs + +#### BitReader + + +Helper class for doing bitwise reads for a FastBufferReader. Ensures all +bitwise reads end on proper byte alignment so FastBufferReader doesn't +have to be concerned with misaligned reads. + + + +#### BitWriter + + +Helper class for doing bitwise writes for a FastBufferWriter. Ensures +all bitwise writes end on proper byte alignment so FastBufferWriter +doesn't have to be concerned with misaligned writes. + + + +#### BufferSerializer\ + + +Two-way serializer wrapping FastBufferReader or FastBufferWriter. + +Implemented as a ref struct for two reasons: + +1. The BufferSerializer cannot outlive the FBR/FBW it wraps or using it + will cause a crash +2. The BufferSerializer must always be passed by reference and can't be + copied + +Ref structs help enforce both of those rules: they can't ref live the +stack context in which they were created, and they're always passed by +reference no matter what. + +BufferSerializer doesn't wrapp FastBufferReader or FastBufferWriter +directly because it can't. ref structs can't implement interfaces, and +in order to be able to have two different implementations with the same +interface (which allows us to avoid an "if(IsReader)" on every call), +the thing directly wrapping the struct has to implement an interface. So +IReaderWriter exists as the interface, which is implemented by a normal +struct, while the ref struct wraps the normal one to enforce the two +above requirements. (Allowing direct access to the IReaderWriter struct +would allow dangerous things to happen because the struct's lifetime +could outlive the Reader/Writer's.) + + + +#### ClientRpcParams + + +Client-Side RPC Can be used with any client-side remote procedure call +Note: Typically this is used primarily for sending to a specific list of +clients as opposed to the default (all). ClientRpcSendParams + + + +#### ClientRpcReceiveParams + + +Client-Side RPC Place holder. ServerRpcParams Note: Server will always +be the sender, so this structure is a place holder + + + +#### ClientRpcSendParams + + +Client-Side RPC The send parameters, when sending client RPCs, provides +you wil the ability to target specific clients as a managed or unmanaged +list: TargetClientIds and TargetClientIdsNativeArray + + + +#### FastBufferReader + + +Optimized class used for reading values from a byte stream +FastBufferWriter BytePacker ByteUnpacker + + + +#### FastBufferWriter + + +Optimized class used for writing values into a byte stream +FastBufferReader BytePacker ByteUnpacker + + + +#### FastBufferWriter.ForEnums + + +This empty struct exists to allow overloading WriteValue based on +generic constraints. At the bytecode level, constraints aren't included +in the method signature, so if multiple methods exist with the same +signature, it causes a compile error because they would end up being +emitted as the same method, even if the constraints are different. +Adding an empty struct with a default value gives them different +signatures in the bytecode, which then allows the compiler to do +overload resolution based on the generic constraints without the user +having to pass the struct in themselves. + + + +#### FastBufferWriter.ForFixedStrings + + +This empty struct exists to allow overloading WriteValue based on +generic constraints. At the bytecode level, constraints aren't included +in the method signature, so if multiple methods exist with the same +signature, it causes a compile error because they would end up being +emitted as the same method, even if the constraints are different. +Adding an empty struct with a default value gives them different +signatures in the bytecode, which then allows the compiler to do +overload resolution based on the generic constraints without the user +having to pass the struct in themselves. + + + +#### FastBufferWriter.ForNetworkSerializable + + +This empty struct exists to allow overloading WriteValue based on +generic constraints. At the bytecode level, constraints aren't included +in the method signature, so if multiple methods exist with the same +signature, it causes a compile error because they would end up being +emitted as the same method, even if the constraints are different. +Adding an empty struct with a default value gives them different +signatures in the bytecode, which then allows the compiler to do +overload resolution based on the generic constraints without the user +having to pass the struct in themselves. + + + +#### FastBufferWriter.ForPrimitives + + +This empty struct exists to allow overloading WriteValue based on +generic constraints. At the bytecode level, constraints aren't included +in the method signature, so if multiple methods exist with the same +signature, it causes a compile error because they would end up being +emitted as the same method, even if the constraints are different. +Adding an empty struct with a default value gives them different +signatures in the bytecode, which then allows the compiler to do +overload resolution based on the generic constraints without the user +having to pass the struct in themselves. + + + +#### FastBufferWriter.ForStructs + + +This empty struct exists to allow overloading WriteValue based on +generic constraints. At the bytecode level, constraints aren't included +in the method signature, so if multiple methods exist with the same +signature, it causes a compile error because they would end up being +emitted as the same method, even if the constraints are different. +Adding an empty struct with a default value gives them different +signatures in the bytecode, which then allows the compiler to do +overload resolution based on the generic constraints without the user +having to pass the struct in themselves. + + + +#### ForceNetworkSerializeByMemcpy\ + + +This is a wrapper that adds `INetworkSerializeByMemcpy` support to +existing structs that the developer doesn't have the ability to modify +(for example, external structs like `Guid`). + + + +#### NetworkBehaviourReference + + +A helper struct for serializing NetworkBehaviours over the network. Can +be used in RPCs and NetworkVariable\. Note: network ids get recycled +by the NetworkManager after a while. So a reference pointing to + + + +#### NetworkListEvent\ + + +Struct containing event information about changes to a NetworkList. + + + +#### NetworkManager.ConnectionApprovalRequest + + +Connection Approval Request + + + +#### NetworkObjectReference + + +A helper struct for serializing NetworkObjects over the network. Can be +used in RPCs and NetworkVariable\. + + + +#### NetworkTime + + +A struct to represent a point of time in a networked game. Time is +stored as a combination of amount of passed ticks + a duration offset. +This struct is meant to replace the Unity Time API for multiplayer +gameplay. + + + +#### ServerRpcParams + + +Server-Side RPC Can be used with any sever-side remote procedure call +Note: typically this is use primarily for the ServerRpcReceiveParams + + + +#### ServerRpcReceiveParams + + +The receive parameters for server-side remote procedure calls + + + +#### ServerRpcSendParams + + +Server-Side RPC Place holder. ServerRpcParams Note: Clients always send +to one destination when sending RPCs to the server so this structure is +a place holder + + + +### Interfaces + +#### INetworkPrefabInstanceHandler + + +Interface for customizing, overriding, spawning, and destroying Network +Prefabs Used by NetworkPrefabHandler + + + +#### INetworkSerializable + + +Interface for implementing custom serializable types. + + + +#### INetworkSerializeByMemcpy + + +This interface is a "tag" that can be applied to a struct to mark that +struct as being serializable by memcpy. It's up to the developer of the +struct to analyze the struct's contents and ensure it is actually +serializable by memcpy. This requires all of the members of the struct +to be `unmanaged` Plain-Old-Data values - if your struct contains a +pointer (or a type that contains a pointer, like `NativeList<T>`), it +should be serialized via `INetworkSerializable` or via +`FastBufferReader`/`FastBufferWriter` extension methods. + + + +#### INetworkUpdateSystem + + +Defines the required interface of a network update system being executed +by the NetworkUpdateLoop. + + + +#### IReaderWriter + + +Interface for an implementation of one side of a two-way serializer + + + +### Enums + +#### HashSize + + +Represents the length of a var int encoded hash Note that the HashSize +does not say anything about the actual final output due to the var int +encoding It just says how many bytes the maximum will be + + + +#### LogLevel + + +Log level + + + +#### NetworkDelivery + + +Delivery methods + + + +#### NetworkEvent + + +Represents a netEvent when polling + + + +#### NetworkListEvent\.EventType + + +Enum representing the different operations available for triggering an +event. + + + +#### NetworkUpdateStage + + +Defines network update stages being executed by the network update loop. +See for more details on update stages: +https://docs.unity3d.com/ScriptReference/PlayerLoop.Initialization.html + + + +#### NetworkVariableReadPermission + + +The permission types for reading a var + + + +#### NetworkVariableWritePermission + + +The permission types for writing a var + + + +#### PendingClient.State + + +The states of a connection + + + +#### RpcDelivery + + +RPC delivery types + + + +#### SceneEventProgressStatus + + +Used by NetworkSceneManager to determine if a server invoked scene event +has started. The returned status is stored in the +Unity.Netcode.SceneEventProgress.Status property. +*Note: This was formally known as SwitchSceneProgress which contained +the . All s are now delivered by the OnSceneEvent event handler via the +SceneEvent parameter.* + + + +#### SceneEventType + + +The different types of scene events communicated between a server and +client. +Used by NetworkSceneManager for Unity.Netcode.SceneEventMessage +messages. +*Note: This is only when EnableSceneManagement is enabled.* +See also: +SceneEvent + + + +### Delegates + +#### CustomMessagingManager.HandleNamedMessageDelegate + + +Delegate used to handle named messages + + + +#### CustomMessagingManager.UnnamedMessageDelegate + + +Delegate used for incoming unnamed messages + + + +#### NetworkList\.OnListChangedDelegate + + +Delegate type for list changed event + + + +#### NetworkObject.SpawnDelegate + + +Delegate type for checking spawn options + + + +#### NetworkObject.VisibilityDelegate + + +Delegate type for checking visibility + + + +#### NetworkSceneManager.OnEventCompletedDelegateHandler + + +Delegate declaration for the OnLoadEventCompleted and +OnUnloadEventCompleted events. +See also: +LoadEventCompleted +UnloadEventCompleted + + + +#### NetworkSceneManager.OnLoadCompleteDelegateHandler + + +Delegate declaration for the OnLoadComplete event. +See also: +LoadComplete for more information + + + +#### NetworkSceneManager.OnLoadDelegateHandler + + +Delegate declaration for the OnLoad event. +See also: +Loadfor more information + + + +#### NetworkSceneManager.OnSynchronizeCompleteDelegateHandler + + +Delegate declaration for the OnSynchronizeComplete event. +See also: +SynchronizeComplete for more information + + + +#### NetworkSceneManager.OnSynchronizeDelegateHandler + + +Delegate declaration for the OnSynchronize event. +See also: +Synchronize for more information + + + +#### NetworkSceneManager.OnUnloadCompleteDelegateHandler + + +Delegate declaration for the OnUnloadComplete event. +See also: +UnloadComplete for more information + + + +#### NetworkSceneManager.OnUnloadDelegateHandler + + +Delegate declaration for the OnUnload event. +See also: +Unload for more information + + + +#### NetworkSceneManager.SceneEventDelegate + + +The delegate callback definition for scene event notifications. +See also: +SceneEvent +Unity.Netcode.SceneEventData + + + +#### NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler + + +Delegate declaration for the VerifySceneBeforeLoading handler that +provides an additional level of scene loading security and/or validation +to assure the scene being loaded is valid scene to be loaded in the +LoadSceneMode specified. + + + +#### NetworkTransport.TransportEventDelegate + + +Delegate for transport network events + + + +#### NetworkVariable\.OnValueChangedDelegate + + +Delegate type for value changed event + + + +#### UserNetworkVariableSerialization\.ReadValueDelegate + + +The read value delegate handler definition + + + +#### UserNetworkVariableSerialization\.WriteValueDelegate + + +The write value delegate handler definition + + + + + diff --git a/versioned_docs/version-1.0.0/api/introduction.md b/versioned_docs/version-1.0.0/api/introduction.md new file mode 100644 index 000000000..e20ef891c --- /dev/null +++ b/versioned_docs/version-1.0.0/api/introduction.md @@ -0,0 +1,44 @@ +--- +id: introduction +title: API Overview +--- + +The Netcode for GameObjects (Netcode) API reference provides information for availble classes, methods, delegates, and more for the `com.unity.netcode.gameobjects`package. + +:::unity Content Licenses +All Netcode code and documentation is covered by MIT license. See [Licenses](/reference/license) for more information. +::: + +:::note +All content is generated from [source code](https://github.com/Unity-Technologies/com.unity.netcode.gameobjects) using tools including [DocFX](https://dotnet.github.io/docfx/) and custom filters with [Pandoc](https://pandoc.org/) to convert to Markdown. See [Document your code with XML comments](https://docs.microsoft.com/en-us/dotnet/csharp/codedoc) for guidance and examples. DocFX generates documentation using these comments. +::: + +To document APIs, developers should add comments in code. For example: + +```csharp +namespace Unity.Netcode.Collections +{ + /// + /// Queue with a fixed size + /// + /// The type of the queue + public sealed class FixedQueue + { + private readonly T[] queue; + private int queueCount = 0; + private int queueStart; + + /// + /// The amount of enqueued objects + /// + public int Count { get => queueCount; } + + /// + /// Gets the element at a given virtual index + /// + /// The virtual index to get the item from + /// The element at the virtual index + public T this[int index] + + ... +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/basics/connection-approval.md b/versioned_docs/version-1.0.0/basics/connection-approval.md new file mode 100644 index 000000000..f94c95dea --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/connection-approval.md @@ -0,0 +1,100 @@ +--- +id: connection-approval +title: Connection Approval +--- + +With every new connection, Netcode for GameObjects (Netcode) performs a handshake in addition to handshakes done by the transport. This ensures the `NetworkConfig` on the Client matches the Server's `NetworkConfig`. You can enable `ConnectionApproval` in the `NetworkManager` or via code by setting `NetworkManager.NetworkConfig.ConnectionApproval` to `true`. + +Connection approval allows you to decide, on a per connection basis, if the connection should be allowed. Connection approval also enables you to specify the player prefab to be created, allowing you to override the default `NetworkManager` defined player prefab on a per player basis. By setting `ConnectionApproval` property of the `NetworkManager` to `true` Netcode will then check to make sure the `NetworkManager.ConnectionApprovalCallback` has been assigned. If it has been assigned, then Netcode will use the connection approval process for connecting clients. + +:::note +If it is not assigned even with the `NetworkManager.ConnectionApprovalCallback` set to `true`, then the basic authentication will be used for the user! (i.e. automatically authorizes and assigns the default player prefab) +::: + +### NetworkManager.ConnectionApprovalRequest + +This class represents the client-to-server request which contains: +- **ClientNetworkId**: the connecting client identifier +- **Payload**: any additional user defined connection data + +### NetworkManager.ConnectionApprovalResponse + +This is how the connection approval response is formed by server-side specific user code in the handler assigned to 'NetworkManager.ConnectionApprovalCallback'. On the server side, this class contains all of the connection approval response information required to either authorize or reject a player attempting to connect. It also contains the following properties: +- **Approved**: When `true` the player is approved and `false` the player is denied. +- **CreatePlayerObject**: When `true` the server will spawn a player prefab for the connecting player. The default player prefab is defined in NetworkManager. In order to specify a player prefab other than the default use the `PlayerPrefabHash` property. +- **PlayerPrefabHash**: The type of player prefab to use for the authorized player (_if this is null it uses the default `NetworkManager` defined player prefab_) +- **Position** and **Rotation**: The position and rotation of the player when spawned +- **Pending**: Provides the ability to mark the approval "pending" to delay the authorization until other user-specific code finishes the approval process. + +:::note +Unlike previous versions of Netcode for GameObjects where users were provided a callback to be invoked within the connection approval handler method, users now only need to set the appropriate properties of the `NetworkManager.ConnectionApprovalResponse` class. Part of this update allows users to set their `ConnectionApprovalResponse` to `Pending` which provides users additional time to process any other tasks involved with the player approval process. +::: + +## Server Side Connection Approval Example + +```csharp +using Unity.Netcode; + +private void Setup() +{ + NetworkManager.Singleton.ConnectionApprovalCallback = ApprovalCheck; + NetworkManager.Singleton.StartHost(); +} + +private void ApprovalCheck(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response) +{ + // The client identifier to be authenticated + var clientId = request.ClientNetworkId; + + // Additional connection data defined by user code + var connectionData = request.Payload; + + // Your approval logic determines the following values + response.Approved = true; + response.CreatePlayerObject = true; + + // The prefab hash value of the NetworkPrefab, if null the default NetworkManager player prefab is used + response.PlayerPrefabHash = null; + + // Position to spawn the player object (if null it uses default of Vector3.zero) + response.Position = Vector3.zero; + + // Rotation to spawn the player object (if null it uses the default of Quaternion.identity) + response.Rotation = Quaternion.identity; + + // If additional approval steps are needed, set this to true until the additional steps are complete + // once it transitions from true to false the connection approval response will be processed. + response.Pending = false; +} +``` + +## Connection data (_`NetworkManager.ConnectionApprovalRequest.Payload`_) + +The `ConnectionApprovalRequest.Payload` parameter takes any custom data of your choice that the client should send to the server. Usually, this data should be some sort of ticket, room password, or similar that will decide if a connection should be approved or not. The `connectionData` is specified on the Client-side in the `NetworkingConfig` supplied when connecting. + +Example: + +```csharp +using Unity.Netcode; + +NetworkManager.Singleton.NetworkConfig.ConnectionData = System.Text.Encoding.ASCII.GetBytes("room password"); +NetworkManager.Singleton.StartClient(); +``` + +The `Payload`, defined by the client-side `NetworkConfig.ConnectionData`, will be sent to the server as part of the `Payload` of the connection request message that will be used on the server-side to determine if the client is approved or not. The connetion data is completely optional and the connection approval process can be used to simply assign player's unique prefabs, other than the default, as well as facilitates the ability to spawn players at various locations (without requiring the client to send any form of connection data). + +## Timeout + +Netcode uses a callback system in order to allow for external validation. For example, you might have a steam authentication ticket sent as the `ConnectionData` that you want to validate against steam servers. This can take some time, so you will want to set the `NetworkManager.ConnectionApprovalResponse.Pending` to true while the steam server(or other third party authentication service) occurs. However, if the third party authentication process (i.e. steam servers, etc) takes longer than the time specified by the `NetworkConfig.ClientConnectionBufferTimeout`, then the connection will be dropped. The timer for this starts when the server is notified of the new inbound client connection. The "Client Connection Buffer Timeout" value can be set via the `NetworkManager` in the inspector view or accessed via the `NetworkManager.NetworkConfig.ClientConnectionBufferTimeout` property. + +## Security + +If connection approval is enabled. Any messages sent before a connection is setup are silently ignored. + +### Connection data security + +The connection data is not encrypted or authenticated. + +:::important +A man in the middle attack can be done. It is strongly suggested to not send authentication tokens such as steam tickets or user passwords over connection approval. +::: diff --git a/versioned_docs/version-1.0.0/basics/images/DontDestroyWithOwner.png b/versioned_docs/version-1.0.0/basics/images/DontDestroyWithOwner.png new file mode 100644 index 000000000..9b9cc8912 Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/images/DontDestroyWithOwner.png differ diff --git a/versioned_docs/version-1.0.0/basics/images/MyCustomNetworkVariableInspectorView.png b/versioned_docs/version-1.0.0/basics/images/MyCustomNetworkVariableInspectorView.png new file mode 100644 index 000000000..af257dcf4 Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/images/MyCustomNetworkVariableInspectorView.png differ diff --git a/versioned_docs/version-1.0.0/basics/images/non-pooled-friendly-prefab.png b/versioned_docs/version-1.0.0/basics/images/non-pooled-friendly-prefab.png new file mode 100644 index 000000000..5d79334d4 Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/images/non-pooled-friendly-prefab.png differ diff --git a/versioned_docs/version-1.0.0/basics/images/pooled-friendly-prefab-child.png b/versioned_docs/version-1.0.0/basics/images/pooled-friendly-prefab-child.png new file mode 100644 index 000000000..fdb7647e3 Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/images/pooled-friendly-prefab-child.png differ diff --git a/versioned_docs/version-1.0.0/basics/images/pooled-friendly-prefab.png b/versioned_docs/version-1.0.0/basics/images/pooled-friendly-prefab.png new file mode 100644 index 000000000..26eb38cda Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/images/pooled-friendly-prefab.png differ diff --git a/versioned_docs/version-1.0.0/basics/logging.md b/versioned_docs/version-1.0.0/basics/logging.md new file mode 100644 index 000000000..980fe196a --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/logging.md @@ -0,0 +1,25 @@ +--- +id: logging +title: Logging +sidebar_label: Logging +--- + + Netcode for GameObjects (Netcode) has built in support for logging which can be great for working with development builds, playtesting and more. If used in production, it should be noted that logs can be forged and do take up some bandwidth depending on the log sizes. + +The logging functionality can be accessed with the NetworkLog API. If a `NetworkLog` is called on the server, the log will not be sent across the network but will instead just be logged locally with the `ServerClientId` as the sender. An example log would be `[MLAPI_SERVER Sender=0] Hello World!`. If the NetworkLog API is instead accessed from a client, it will first log locally on the sending client but will also be logged on the server. + +## Examples + +```csharp +if (IsServer) +{ + // This will not send any network packets but will log it locally on the server + NetworkLog.LogInfoServer("Hello World!"); +} + +if (IsClient) +{ + // This will log locally and send the log to the server to be logged there aswell + NetworkLog.LogInfoServer("Hello World!"); +} +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/basics/maxnumberplayers.md b/versioned_docs/version-1.0.0/basics/maxnumberplayers.md new file mode 100644 index 000000000..1bb1b47bd --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/maxnumberplayers.md @@ -0,0 +1,33 @@ +--- +id: max-players +title: Limiting the maximum number of players +--- + +Netcode for Gameobjects (Netcode) provides a way to customize the [connection approval process](connection-approval.md) that can reject incoming connections based on any number of user-specific reasons. +​ + +Boss Room provides one example of how to handle limiting the number of players through the connection approval process: + +Boss Room provides an example of such delegate + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/Gameplay/ConnectionManagement/ServerGameNetPortal.cs#L176 +``` +​ +The code below shows an example of an over-capacity check that would prevent more than a certain pre-defined number of players from connecting. +​ +```csharp +if( m_Portal.NetManager.ConnectedClientsIds.Count >= CharSelectData.k_MaxLobbyPlayers ) +{ + return ConnectStatus.ServerFull; +} +``` +​ +:::tip**SUBJECT TO CHANGE:** +​ +In connection approval delegate Netcode does not support an ability to send anything more than a boolean back. +Boss Room demonstrates a way to provide meaningful error code to the client by invoking a client RPC in the same channel that Netcode uses for its connection callback. + +::: + +When using Relay, ensure the maximum number of peer connections allowed by the host satisfies the logic implemented in the connection approval delegate. diff --git a/versioned_docs/version-1.0.0/basics/networkbehaviour.md b/versioned_docs/version-1.0.0/basics/networkbehaviour.md new file mode 100644 index 000000000..2f77036b1 --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/networkbehaviour.md @@ -0,0 +1,110 @@ +--- +id: networkbehavior +title: NetworkBehaviour +--- + +:::note +Both the `NetworkObject` and `NetworkBehaviour` components require the use of specialized structures in order to be serialized and used with `RPC`s and `NetworkVariables`: + +For `NetworkObject`s use the [NetworkObjectReference](../api/Unity.Netcode.NetworkObjectReference). + +For `NetworkBehaviour`s use the NetworkBehaviourReference. +::: + +## NetworkBehaviour + +`NetworkBehaviour`s can use `NetworkVariable`s and `RPC`s to synchronize state and send messages over the network. In order to replicate any netcode aware properties or send/receive RPCs a `GameObject` must have a [NetworkObject component](/basics/networkobject.md) and at least one `NetworkBehaviour` component. A `NetworkBehaviour` requires a `NetworkObject` component on the same relative `GameObject` or on a parent of the `GameObject` with the `NetworkBehaviour` component assigned to it. If you add a `NetworkBehaviour` to a GameObject that does not have a `NetworkObject` (or any parent), then Netcode for GameObjects will automatically add a `NetworkObject` component to the `GameObject` in which the `NetworkBehaviour` was added. + +[`NetworkBehaviour`](../api/Unity.Netcode.NetworkBehaviour.md) is an abstract class that derives from [`MonoBehaviour`](https://docs.unity3d.com/ScriptReference/MonoBehaviour.html) and is primarily used to create unique netcode/game logic. + +`NetworkBehaviours` can contain RPC methods and `NetworkVariables`. When you call an RPC function, the function is not called locally. Instead a message is sent containing your parameters, the `networkId` of the `NetworkObject` associated with the same GameObject (or child) that the `NetworkBehaviour` is assigned to, and the "index" of the `NetworkObject` relative `NetworkBehaviour` (i.e. a `NetworkObject` could have several NetworkBehaviours, the index communicates "which one"). + +:::note +It is important that the `NetworkBehaviour`s on each `NetworkObject` remains the same for the server and any client connected. When using multiple projects, this becomes especially important so the server doesn't try to call a client RPC on a `NetworkBehaviour` that might not exist on a specific client type (or set a NetworkVariable, etc). +::: + +### Pre-Spawn and Monobehaviour Updates + +Since `NetworkBehaviour`s derive from MonoBehaviour, the `FixedUpdate`, `Update`, and `LateUpdate` methods, if defined, will still be invoked on `NetworkBehaviour`s even when they are not yet spawned. In order to "exit early" to avoid executing netcode specific code within the update methods, you can check the local `NetworkBehaviour.IsSpawned` flag and return if it is not yet set like the below example: + +```csharp +private void Update() +{ + if (!IsSpawned) + { + return; + } + // Netcode specific logic below here +} +``` + +### Spawning + +`OnNetworkSpawn` is invoked on each `NetworkBehaviour` associatd with a `NetworkObject` spawned. This is where all netcode related initialization should occur. +You can still use `Awake` and `Start` to do things like finding components and assigning them to local properties, but if `NetworkBehaviour.IsSpawned` is false do not expect netcode distinguishing properties (like IsClient, IsServer, IsHost, etc) to be accurate while within the those two methods (Awake and Start). +For reference purposes, below is a table of when `NetworkBehaviour.OnNetworkSpawn` is invoked relative to the `NetworkObject` type: + +Dynamically Spawned | In-Scene Placed +------------------- | --------------- +Awake | Awake +OnNetworkSpawn | Start +Start | OnNetworkSpawn + +#### Dynamically Spawned NetworkObjects + +For dynamically spawned `NetworkObjects` (instantiating a network prefab during runtime) the `OnNetworkSpawn` method is invoked **before** the `Start` method is invoked. So, it is important to be aware of this because finding and assigning components to a local property within the `Start` method exclusively will result in that property not being set in a `NetworkBehaviour` component's `OnNetworkSpawn` method when the `NetworkObject` is dynamically spawned. To circumvent this issue, you could have a common method that initializes the components and is invoked both during the `Start` method and the `OnNetworkSpawned` method like the code example below: + +```csharp +public class MyNetworkBehaviour : NetworkBehaviour +{ + private MeshRenderer m_MeshRenderer; + private void Start() + { + Initialize(); + } + + private void Initialize() + { + if (m_MeshRenderer == null) + { + m_MeshRenderer = FindObjectOfType(); + } + } + + public override void OnNetworkSpawn() + { + Initialize(); + // Do things with m_MeshRenderer + + base.OnNetworkSpawn(); + } +} +``` + +#### In-Scene Placed NetworkObjects + +For in-scene placed `NetworkObjects`, the `OnNetworkSpawn` method is invoked **after** the `Start` method since the SceneManager scene loading process controls when the `NetworkObject`s are instantiated. The previous code example demonstrates how one can design a `NetworkBehaviour` that assures both in-scene placed and dynamically spawned `NetworkObject`s will have assigned the required properties before attempting to access them. Of course, you can always make the decision to have in-scene placed `NetworkObjects` contain unique components to that of dynamically spawned `NetworkObjects`. It all depends upon what usage pattern works best for your project. + +### De-Spawning + +`OnNetworkDespawn` is invoked on each `NetworkBehaviour` associated with a `NetworkObject` when it is de-spawned. This is where all netcode "despawn cleanup code" should occur, but is not to be confused with destroying. Despawning occurs before anything is destroyed. + +### Destroying + +Each 'NetworkBehaviour' has a virtual 'OnDestroy' method that can be overridden to handle clean up that needs to occur when you know the `NetworkBehaviour` is being destroyed. + +:::important +If you override the virtual 'OnDestroy' method it is important to alway invoke the base like such: + +```csharp + public override void OnDestroy() + { + // Clean up your NetworkBehaviour + + // Always invoked the base + base.OnDestroy(); + } +``` + +`NetworkBehaviour` handles other destroy clean up tasks and requires that you invoke the base `OnDestroy` method to operate properly. +::: diff --git a/versioned_docs/version-1.0.0/basics/networkobject.md b/versioned_docs/version-1.0.0/basics/networkobject.md new file mode 100644 index 000000000..5d0b62e4a --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/networkobject.md @@ -0,0 +1,109 @@ +--- +id: networkobject +title: NetworkObject +--- + +Netcode for Gameobjects' high level components, [the RPC system](../advanced-topics/messaging-system.md), [object spawning](../basics/object-spawning), and [NetworkVariable](../basics/networkvariable)s all rely on there being at least two netcode components added to a `GameObject`: + 1. `NetworkObject` + 2. [`NetworkBehaviour`](networkbehaviour.md) + +:::note +Both the `NetworkObject` and `NetworkBehaviour` components require the use of specialized structures in order to be serialized and used with `RPC`s and `NetworkVariables`: + +- For `NetworkObject`s use the [`NetworkObjectReference`](../api/Unity.Netcode.NetworkObjectReference). +- For `NetworkBehaviour`s use the [`NetworkBehaviourReference`](../api/Unity.Netcode.NetworkBehaviourReference.md). +::: + +## NetworkObject + +In order to replicate any netcode aware properties or send/receive RPCs a `GameObject` must have a `NetworkObject` component and at least one `NetworkBehaviour` component. Any netcode related component, like `NetworkTransform` or a `NetworkBehaviour` with one or more `NetworkVariable`s or `RPC`s, requires a `NetworkObject` component on the same relative `GameObject` or on a parent of the `GameObject` in question. + +When spawning a `NetworkObject`, the NetworkObject.GlobalObjectIdHash value is used to initially identify the associatd network prefab asset clients will instantiate to create a client-local clone/copy. Once instantiated locally, each `NetworkObject` is assigned a `NetworkObjectId` that is used to associate `NetworkObject`s across the network. For example, one peer can say "Send this RPC to the object with the NetworkObjectId 103", and everyone knows what object that is. A `NetworkObject` is considered "Spawned" on a client is when it has been instatiated and assigned a unique `NetworkObjectId`. + +[NetworkBehaviours](networkbehaviour.md) provide users with the ability to add their own custom netcode logic to the associated `NetworkObject`. + +## Ownership + +Each `NetworkObject` is owned by either the server (default) or any connected and approved client. Netcode for GameObjects is server authoritative, which means the server controls (i.e. is the only system authorized) to spawn or despawn `NetworkObject`s. + +:::note +All code snippets below should be invoked on the server-side. +::: + +The default 'NetworkObject.Spawn' method assumes server-side ownership: +```csharp +GetComponent().Spawn(); +``` + +To spawn `NetworkObject`s with ownership use the following: +```csharp +GetComponent().SpawnWithOwnership(clientId); +``` + +To change ownership, use the `ChangeOwnership` method: + +```csharp +GetComponent().ChangeOwnership(clientId); +``` + +To give ownership back to the server use the `RemoveOwnership` method: + +```csharp +GetComponent().RemoveOwnership(); +``` + +To determine if the local client is the owner of a NetworkObject you can check the [`NetworkBehaviour.IsOwner`](../api/Unity.Netcode.NetworkBehaviour#isowner) property. + +To determine if the NetworkObject is owned by the server you can check the [`NetworkBehaviour.IsOwnedByServer`](../api/Unity.Netcode.NetworkBehaviour#isownedbyserver) property. + +:::note +When you want to despawn and destroy the owner but you don't want a specific `NetworkObject` to be destroyed along with the owner, then you can set the `NetworkObject.DontDestroyWithOwner` property to `true` which will assure that when the owner is destroyed the owned `NetworkObject`is not destroyed. +::: + +## Player Objects + +Player objects are an optional feature in Netcode which can be used to assign a networked object to a specific client. A client can always only have at most one player object. + +:::note +If you want a client to control multiple objects, then use the ownership methods described above under the ownership section. + +If you want to be able to assign a unique player prefab on a per client connection basis, use client [Connection Approval](connection-approval). +::: + +### Creating a Player Object + +Netcode can spawn a default player object for you. If `Create Player Prefab` is checked (`true`) in the `NetworkManager` and the `Player Prefab` is assigned a valid prefab, then Netcode will spawn a unique instance of the designated player prefab for each connected and approved client. + +To manually spawn an object as player object, use the following method: + +```csharp +GetComponent().SpawnAsPlayerObject(clientId); +``` +:::note +If the player already had a prefab instance assigned, then the NetworkObject of that prefab instance will still be owned by the client unless there is additional server-side specific user code that removes or changes the ownership. +::: + +### Finding Player Objects + +To find a player object for a specific client id you can use the following methods: + +Within a NetworkBehaviour, you can check the local `NetworkManager`'s `LocalClient` to get the local player object: + +```csharp +NetworkManager.LocalClient.PlayerObject +``` + +Conversely, on the server-side if you need to get the player object instance for a specific client you can use the following: + +```csharp +NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject; +``` + +To find your own player object just pass `NetworkManager.Singleton.LocalClientId` as the clientId in the sample above. + +### Network Prefabs +Network prefabs (NetworkPrefabs) are prefabs that contain a GameObject with a `NetworkObject` component. As an example, if you wanted to create a prefab to be the default player prefab, then you would create a prefab that at the root GameObject included a `NetworkObject` component and any additional player specific `NetworkBehabiour` components. You can then assign that prefab to the `NetworkManager` Player Prefab property to be used when a player is connected and approved. Each connected player will have a unique instance spawned on all connected clients (including the server). + +:::note +You can only have one `NetworkObject` at the root of a prefab. This means do not create prefabs with nested `NetworkObjects`! +::: diff --git a/versioned_docs/version-1.0.0/basics/networkvariable.md b/versioned_docs/version-1.0.0/basics/networkvariable.md new file mode 100644 index 000000000..62532f40e --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/networkvariable.md @@ -0,0 +1,749 @@ +--- +id: networkvariable +title: NetworkVariable +sidebar_label: NetworkVariable +--- + +## Introduction + +At a high level, a `NetworkVariable` is a way to synchronize a property ("variable") between a server and client(s) without having to use custom messages or RPCs. Since `NetworkVariable` is really a wrapper ("container") of the stored value of type `T`, you must use the `NetworkVariable.Value` property to access the actual value being synchronized. A `NetworkVariable.Value` is synchronized with: +- Newly joining clients (i.e. "Late Joining Clients") + - When the associated `NetworkObject` of a `NetworkBehaviour`, with `NetworkVariable` properties, is spawned, any `NetworkVariable`'s current state (`Value`) is automatically synchronized on the client side. +- Connected clients + - When a `NetworkVariable` value changes, any connected clients that subscribed to `NetworkVariable.OnValueChanged` event (prior to the value being changed) will be notified of the change. + - Two parameters are passed to any `NetworkVariable.OnValueChanged` subscribed callback method: + - First parameter (Previous): The previous value before the value was changed + - Second parameter (Current): The newly changed `NetworkVariable.Value`. + +### NetworkVariable General Requirements + +A `NetworkVariable`: +- Property *must* be defined within a `NetworkBehaviour` derived class attached to a `GameObject` + - The `GameObject` or a parent `GameObject` **must** also have a `NetworkObject` component attached to it. +- A `NetworkVariable`'s assigned type (`T`) must be [constrained to an unmanaged `Type`](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#unmanaged-constraint). +- A `NetworkVariable`'s value can only be set when: + - Initializing the property (either when it is declared or within the Awake method) + - While the associated `NetworkObject` is spawned (upon being spawned or any time while it is still spawned). + +:::important +When a client first connects, it will be synchronized with the current value of the `NetworkVariable`. Typically, clients should register for `NetworkVariable.OnValueChanged` within the OnNetworkSpawn method. +*But why?*
+A `NetworkBehaviour`'s `Start` and `OnNetworkSpawn` methods are invoked based on the type of `NetworkObject` the `NetworkBehaviour` is associated with: +- In-Scene Placed: Since the instantiation occurs via the scene loading mechanism(s), the `Start` method is invoked before `OnNetworkSpawn`. +- Dynamically Spawned: Since `OnNetworkSpawn` is invoked immediately (i.e. within the same relative call-stack) after instantiation, the `Start` method is invoked after `OnNetworkSpawn`. + +_Typically, these are invoked at least 1 frame after the `NetworkObject` and associated `NetworkBehaviour` components are instantiated._ + +Dynamically Spawned | In-Scene Placed +------------------- | --------------- +Awake | Awake +OnNetworkSpawn | Start +Start | OnNetworkSpawn + +Also, you should only set the value of a `NetworkVariable` when first initializing it or if it is spawned. It is not recommended setting a `NetworkVariable` when the associated `NetworkObject` is not spawned. +::: + + +:::tip +If you need to initialize other components or objects based on a `NetworkVariable`'s initial synchronized state, then you might contemplate having a common method that is invoked on the client side within the `NetworkVariable.OnValueChanged` callback (if assigned) and `NetworkBehaviour.OnNetworkSpawn` method. +::: + +### Synchronization and Notification Example + +The following example demonstrates how the initial `NetworkVariable` synchronization has already occurred by the time `OnNetworkSpawn` is invoked. It also demonstrates how subscribing to `NetworkVariable.OnValueChanged` within `OnNetworkSpawn` will provide notifications for any changes to `m_SomeValue.Value` that occur. + + ```csharp +public class TestNetworkVariableSynchronization : NetworkBehaviour +{ + private NetworkVariable m_SomeValue = new NetworkVariable(); + private const int k_InitialValue = 1111; + + public override void OnNetworkSpawn() + { + if (IsServer) + { + m_SomeValue.Value = k_InitialValue; + NetworkManager.OnClientConnectedCallback += NetworkManager_OnClientConnectedCallback; + } + else + { + if (m_SomeValue.Value != k_InitialValue) + { + Debug.LogWarning($"NetworkVariable was {m_SomeValue.Value} upon being spawned" + + $" when it really should have been {k_InitialValue}"); + } + else + { + Debug.Log($"NetworkVariable is {m_SomeValue.Value} when spawned."); + } + m_SomeValue.OnValueChanged += OnSomeValueChanged; + } + } + + private void NetworkManager_OnClientConnectedCallback(ulong obj) + { + StartCoroutine(StartChangingNetworkVariable()); + } + + private void OnSomeValueChanged(int previous, int current) + { + Debug.Log($"Detected NetworkVariable Change: Previous: {previous} | Current: {current}"); + } + + private IEnumerator StartChangingNetworkVariable() + { + var count = 0; + var updateFrequency = new WaitForSeconds(0.5f); + while (count < 4) + { + m_SomeValue.Value += m_SomeValue.Value; + yield return updateFrequency; + } + NetworkManager.OnClientConnectedCallback -= NetworkManager_OnClientConnectedCallback; + } +} +``` + +In the above example: + - The server initializes the `NetworkVariable` upon the associated `NetworkObject` being spawned. + - The client confirms that the `NetworkVariable` is synchronized to the initial value set by the server and assigns a callback method to `NetworkVariable.OnValueChanged`. + - Once spawned, the client will be notified of any changes made to the `NetworkVariable`. + +:::tip +If you were to attach the above script to an in-scene placed `NetworkObject`, make a stand alone build, run the stand alone build as a host, and then connect to that host by entering play mode in the editor, you would see (in the console output): +- The client side `NetworkVariable` value is the same as the server when `NetworkBehaviour.OnNetworkSpawn` is invoked. +- The client detects any changes made to the `NetworkVariable` after the in-scene placed `NetworkObject` is spawned. +_This works the same way with dynamically spawned `NetworkObject`s._ +::: + +:::important +The above example is only to test both the initial client synchronization of the value and when the value changes. It was intentionally written to only be an example, and if you "late join" a 2nd client it will throw the warning about the `NetworkVariable.Value` not being the initial value. This example was really intended to be used with a single server or host and a single client. +::: + +### OnValueChanged Example + +While the first example highlighted the differences between synchronizing a `NetworkVariable` with newly joining clients and notifying connected clients when a `NetworkVariable` changes, it didn't really provide any concrete example usage. The next example demonstrates a simple server authoritative `NetworkVariable` being used to track the state of a door (i.e. open or closed): + +```csharp +public class Door : NetworkBehaviour +{ + public NetworkVariable State = new NetworkVariable(); + + public override void OnNetworkSpawn() + { + State.OnValueChanged += OnStateChanged; + } + + public override void OnNetworkDespawn() + { + State.OnValueChanged -= OnStateChanged; + } + + public void OnStateChanged(bool previous, bool current) + { + // note: `State.Value` will be equal to `current` here + if (State.Value) + { + // door is open: + // - rotate door transform + // - play animations, sound etc. + } + else + { + // door is closed: + // - rotate door transform + // - play animations, sound etc. + } + } + + [ServerRpc(RequireOwnership = false)] + public void ToggleServerRpc() + { + // this will cause a replication over the network + // and ultimately invoke `OnValueChanged` on receivers + State.Value = !State.Value; + } +} +``` +In the above example, we demonstrate how you can maintain a server authoritative `NetworkVariable` by using a non-ownership based server RPC (i.e. `RequireOwnership = false` means non-owners can invoke it) so any client can notify the server that it is performing an "action" on the door. For this example, each time the door is used by a client the `Door.ToggleServerRpc` is invoked and the server-side toggles the state of the door. Upon the `Door.State.Value` changing, all connected clients are synchronized to the (new) current `Value` and the `OnStateChanged` method is invoked locally on each client. + +However, what if you wanted to adjust who could write to or read from the `NetworkVariable`? +_The answer: `NetworkVariable` permissions._ + +## Permissions + +The `NetworkVariable` constructor can take up to 3 parameters: + +```csharp +public NetworkVariable(T value = default, +NetworkVariableReadPermission readPerm = NetworkVariableReadPermission.Everyone, +NetworkVariableWritePermission writePerm = NetworkVariableWritePermission.Server); +``` + +As you can see by the above constructor declaration, the default permissions are: +- *Server:* Has read and write permissions +- *Clients:* Have read only permissions. + +Let's look at the two types of permissions defined within [NetworkVariablePermissions.cs](https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/blob/release/1.0.0/com.unity.netcode.gameobjects/Runtime/NetworkVariable/NetworkVariablePermission.cs): + +```csharp + /// + /// The permission types for reading a var + /// + public enum NetworkVariableReadPermission + { + /// + /// Everyone can read + /// + Everyone, + /// + /// Only the owner and the server can read + /// + Owner, + } + + /// + /// The permission types for writing a var + /// + public enum NetworkVariableWritePermission + { + /// + /// Only the server can write + /// + Server, + /// + /// Only the owner can write + /// + Owner + } +``` +:::important +Since Netcode for GameObjects uses a server authoritative model, the server will always have read or write permissions to any `NetworkVariable`. As an example, if you set both the read and write permissions to `Owner` the server can still read and write to the `NetworkVariable`. +::: + +### Read Permissions + +There are two options for reading a `NetworkVariable.Value`: +- *Everyone(_default_):* this means the owner and non-owners of the `NetworkObject` can read the value. + - This is useful for "global states" that everyone should be aware of. + - We provided an example of maintaining a door's open or closed state using the everyone permission. + - You might also use this for player scores, health, or any other state that "everyone" should know about. +- *Owner:* This means only the owner of the `NetworkObject` and the server can read the value. + - This is useful if your `NetworkVariable` represents something specific to the client's player that only the server and client should know about + - This might be a player's inventory or gun's ammo count (etc.) + +### Write Permissions + +There are two options for writing a `NetworkVariable.Value`: +- *Server(_default_):* the server is the only one that can write the value. + - This is useful for server side specific states that all clients should should be aware of but cannot change. + - Some examples would be an NPC's status (health, alive, dead, etc) or some global world environment state (i.e. is it night or day time?). +- *Owner:* This means only the owner of the `NetworkObject` can write to the value. + - This is useful if your `NetworkVariable` represents something specific to the client's player that only the owning client should be able to set + - This might be a player's skin or other cosmetics + +### Permissions Example + +The below example provides you with a few different permissions configurations that you might use in a game while keeping track of a player's state. + +```csharp +public class PlayerState : NetworkBehaviour +{ + private const float k_DefaultHealth = 100.0f; + /// + /// Default Permissions: Everyone can read, server can only write + /// Player health is typically something determined (updated/written to) on the server + /// side, but a value everyone should be synchronized with (i.e. read permissions). + /// + public NetworkVariable Health = new NetworkVariable(k_DefaultHealth); + + /// + /// Owner Read Permissions: Owner or server can read + /// Owner Write Permissions: Only the Owner can write + /// A player's ammo count is something that you might want, for convenience sake, the + /// client-side to update locally. This might be because you are trying to reduce + /// bandwidth consumption for the server and all non-owners/ players or you might be + /// trying to incorporate a more client-side "hack resistant" design where non-owners + /// are never synchronized with this value. + /// + public NetworkVariable AmmoCount = new NetworkVariable(default, + NetworkVariableReadPermission.Owner, NetworkVariableWritePermission.Owner); + + /// + /// Owner Write & Everyone Read Permissions: + /// A player's model's skin selection index. You might have the option to allow players + /// to select different skin materials as a way to further encourage a player's personal + /// association with their player character. It would make sense to make the permissions + /// setting of the NetworkVariable such that the client can change the value, but everyone + /// will be notified when it changes to visually reflect the new skin selection. + /// + public NetworkVariable SkinSelectionIndex = new NetworkVariable(default, + NetworkVariableReadPermission.Everyone, NetworkVariableWritePermission.Owner); + + /// + /// Owner Read & Server Write Permissions: + /// You might incorporate some form of reconnection logic that stores a player's state on + /// the server side and can be used by the client to reconnect a player if disconnected + /// unexpectedly. In order for the client to let the server know it is the "same client" + /// you might have implemented a keyed array (i.e. Hashtable, Dictionary, etc, ) to track + /// each connected client. The key value for each connected client would only be written to + /// the each client's PlayerState.ReconnectionKey. Under this scenario, you only want the + /// server to have write permissions and the owner (client) to be synchronized with this + /// value (via owner only read permissions). + /// + public NetworkVariable ReconnectionKey = new NetworkVariable(default, + NetworkVariableReadPermission.Owner, NetworkVariableWritePermission.Server); +} +``` + +The above example provides you with details on: +- The `NetworkVariable`'s purpose. +- The "logical" reasoning behind each `NetworkVariable`'s read and write permission settings. + +:::important +You might be wondering about our earlier door example and why we chose to use a server RPC for clients to notify the server that the door's open/closed state has changed. Under that scenario, the owner of the door will most likely be owned by the server just like non-player characters will almost always be owned by the server. Under a server owned scenario, using an RPC to handle updating a `NetworkVariable` is the proper choice above permissions for most cases. +::: + +## Complex Value Types + +Almost all of our examples have been focused around numeric [Value Types](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types). Value types are any `Type` that cannot be assigned a null value. Structures are considered non-nullable complex value types. From a Netcode for GameObject perspective, as long as the structure (or any nested sub-property) does not contain any properties that are considered nullable value types. + +:::warning +`NetworkVariable` does not support any [nullable value types](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types). This includes any `INetworkSerializable` implementation that contains any properties (private, protected, internal, and public) that are of a nullable value type. +::: + +### Synchronizing Complex Types Example + +For this example, we are extending the previous `PlayerState` class to include some complex value types to handle a weapon boosting game play mechanic. We will explore two complex values types: +- *WeaponBooster:* A power-up weapon booster that can only be assigned/applied by the client. + - This is a simple example of a "complex" value type. +- *AreaWeaponBooster:* A second kind of "weapon booster" power-up that players can deploy at a specific location, and any team members within the radius of the `AreaWeaponBooster` will have the weapon booster applied. + - This is an example of a nested complex value type. + +For the `WeaponBooster`, we only need one NetworkVariable to handle synchronizing everyone with any currently active player-local `WeaponBooster`. However, with the `AreaWeaponBooster` we must consider what happens if you have 8 team members that could, at any given moment, deploy one a `AreaWeaponBooster`? It would require, at a minimum, a list of all deployed and currently active `AreaWeaponBooster`s. For this task, we will use a `NetworkList` as opposed to a `NetworkVariable`. + +First, let's review over the below `PlayerState` additions along with the `WeaponBooster` structure (complex value type): + +```csharp +public class PlayerState : NetworkBehaviour +{ + // ^^^^^^^ including all code from previous example ^^^^^^^ + + // The weapon booster currently applied to a player + private NetworkVariable PlayerWeaponBooster = new NetworkVariable(); + + // A list of team members active "area weapon boosters" that could be applied if the local player + // is within their range. + private NetworkList TeamAreaWeaponBoosters = new NetworkList(); +} + +/// +/// Example: Complex Value Type +/// This is an example of how one might handle tracking any weapon booster currently applied +/// to a player. +/// +public struct WeaponBooster : INetworkSerializable, System.IEquatable +{ + public float PowerAmplifier; + public float Duration; + + public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + if (serializer.IsReader) + { + var reader = serializer.GetFastBufferReader(); + reader.ReadValueSafe(out PowerAmplifier); + reader.ReadValueSafe(out Duration); + } + else + { + var writer = serializer.GetFastBufferWriter(); + writer.WriteValueSafe(PowerAmplifier); + writer.WriteValueSafe(Duration); + } + } + + public bool Equals(WeaponBooster other) + { + return PowerAmplifier == other.PowerAmplifier && Duration == other.Duration; + } +} +``` + +The above first half of the example code shows how a complex value type that implements `INetworkSerializable` is pretty straight forward. Looking at the below second portion of our example, we can see that the `AreaWeaponBooster` includes a `WeaponBooster` property that would (for example) be applied to team members that are within the `AreaWeaponBoosters` radius: + +```csharp +/// +/// Example: Nesting Complex Value Types +/// This example uses the previous WeaponBooster complex value type to be a "container" for +/// the "weapon booster" information of an AreaWeaponBooster. It then provides additional +/// information that would allow clients to easily determine, based on location and radius, +/// if it should add (for example) a special power up HUD symbol or special-FX to the local +/// player. +/// +public struct AreaWeaponBooster : INetworkSerializable, System.IEquatable +{ + public WeaponBooster ApplyWeaponBooster; // the nested complex value type + public float Radius; + public Vector3 Location; + public void NetworkSerialize(BufferSerializer serializer) where T : IReaderWriter + { + if (serializer.IsReader) + { + // The complex value type handles its own de-serialization + serializer.SerializeValue(ref ApplyWeaponBooster); + // Now de-serialize the non-complex value type properties + var reader = serializer.GetFastBufferReader(); + reader.ReadValueSafe(out Radius); + reader.ReadValueSafe(out Location); + } + else + { + // The complex value type handles its own serialization + serializer.SerializeValue(ref ApplyWeaponBooster); + // Now serialize the non-complex value type properties + var writer = serializer.GetFastBufferWriter(); + writer.WriteValueSafe(Radius); + writer.WriteValueSafe(Location); + } + } + + public bool Equals(AreaWeaponBooster other) + { + return other.Equals(this) && Radius == other.Radius && Location == other.Location; + } +} +``` + Looking closely at the read and write segments of code within `AreaWeaponBooster.NetworkSerialize`, the nested complex value type property `ApplyWeaponBooster` handles its own serialization and de-serialization. Any `AreaWeaponBooster` value type property is serialized and de-serialized by the `ApplyWeaponBooster`'s implemented `NetworkSerialize` method. Using this type of design approach can help reduce code replication while providing a more modular foundation to build even more complex, nested, value types. + +## Custom NetworkVariable Implementations + +:::warning Disclaimer +The `NetworkVariable` and `NetworkList` classes were created as `NetworkVariableBase` class implementation examples. While the `NetworkVariable` class is considered production ready for basic `unmanaged` value types, you might run into scenarios where you have a more advanced implementation in mind. Under this scenario, we would encourage you to create your own custom implementation. +::: +In order to create your own `NetworkVariableBase` derived container, you should: +- Create a class deriving from `NetworkVariableBase`. +- Assure the the following methods are overridden: + - `void WriteField(FastBufferWriter writer)` + - `void ReadField(FastBufferReader reader)` + - `void WriteDelta(FastBufferWriter writer)` + - `void ReadDelta(FastBufferReader reader, bool keepDirtyDelta)` +- Depdending upon your custom `NetworkVariableBase` container, you might look at `NetworkVariable` or `NetworkList` to see how those two examples were implemented. + + ### Custom NetworkVariable Example + + With all of the previous discussion revolving around (unmanaged) value types, this example will explore a custom `NetworkVariableBase` derived class that does contain managed properties and one way (for example purposes) that you can have a mixture of managed and unmanaged value types: + + ```csharp + /// Using MyCustomNetworkVariable within a NetworkBehaviour + public class TestMyCustomNetworkVariable : NetworkBehaviour + { + public MyCustomNetworkVariable CustomNetworkVariable = new MyCustomNetworkVariable(); + public override void OnNetworkSpawn() + { + if (IsServer) + { + for (int i = 0; i < 4; i++) + { + var someData = new SomeData(); + someData.SomeFloatData = (float)i; + someData.SomeIntData = i; + someData.SomeListOfValues.Add((ulong)i + 1000000); + someData.SomeListOfValues.Add((ulong)i + 2000000); + someData.SomeListOfValues.Add((ulong)i + 3000000); + CustomNetworkVariable.SomeDataToSynchronize.Add(someData); + CustomNetworkVariable.SetDirty(true); + } + } + } + } + + /// Bare minimum example of NetworkVariableBase derived class + [Serializable] + public class MyCustomNetworkVariable : NetworkVariableBase + { + /// Managed list of class instances + public List SomeDataToSynchronize = new List(); + + /// + /// Writes the complete state of the variable to the writer + /// + /// The stream to write the state to + public override void WriteField(FastBufferWriter writer) + { + // Serialize the data we need to synchronize + writer.WriteValueSafe(SomeDataToSynchronize.Count); + foreach (var dataEntry in SomeDataToSynchronize) + { + writer.WriteValueSafe(dataEntry.SomeIntData); + writer.WriteValueSafe(dataEntry.SomeFloatData); + writer.WriteValueSafe(dataEntry.SomeListOfValues.Count); + foreach (var valueItem in dataEntry.SomeListOfValues) + { + writer.WriteValueSafe(valueItem); + } + } + } + + /// + /// Reads the complete state from the reader and applies it + /// + /// The stream to read the state from + public override void ReadField(FastBufferReader reader) + { + // De-Serialize the data being synchronized + var itemsToUpdate = (int)0; + reader.ReadValueSafe(out itemsToUpdate); + SomeDataToSynchronize.Clear(); + for (int i = 0; i < itemsToUpdate; i++) + { + var newEntry = new SomeData(); + reader.ReadValueSafe(out newEntry.SomeIntData); + reader.ReadValueSafe(out newEntry.SomeFloatData); + var itemsCount = (int)0; + var tempValue = (ulong)0; + reader.ReadValueSafe(out itemsCount); + newEntry.SomeListOfValues.Clear(); + for (int j = 0; j < itemsCount; j++) + { + reader.ReadValueSafe(out tempValue); + newEntry.SomeListOfValues.Add(tempValue); + } + SomeDataToSynchronize.Add(newEntry); + } + } + + public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta) + { + // Do nothing for this example + } + + public override void WriteDelta(FastBufferWriter writer) + { + // Do nothing for this example + } + } + + /// Example managed class used as the item type in the + /// MyCustomNetworkVariable.SomeDataToSynchronize list + [Serializable] + public class SomeData + { + public int SomeIntData = default; + public float SomeFloatData = default; + public List SomeListOfValues = new List(); + } + ``` + +While the above example is not the "recommended" way to synchronize a list that frequently changes (i.e. one or more elements position/order or add/remove), it is just an example of how you can "define your own rules" through using `NetworkVariableBase`. Whether you handle managed or unmanaged value types is up to you. + +The above code could be tested by: +- Using the above code with a project that includes Netcode for GameObjects v1.0 (or higher). +- Adding the `TestMyCustomNetworkVariable` component to an in-scene placed `NetworkObject`. +- Creating a stand alone build and running that as a host or server +- Running the same scene within the editor and connecting as a client + - Once connected, you can then select the `GameObject` with the attached `NetworkObject` and `TestMyCustomNetworkVariable` components so it appears in the inspector view. There you can verify the `TestMyCustomNetworkVariable.CustomNetworkVariable` property was synchronized with the client (like in the screenshot below): + ![ScreenShot](images/MyCustomNetworkVariableInspectorView.png) + +:::caution +If you are not adhering to the (unmanaged) value types in your own custom `NetworkVariableBase` implementation then it is advised to not try and use `NetworkList` or `NetworkVariable` as properties within that implementation. Instead, declare `NetworkVariable` or `NetworkList` properties within the same `NetworkBehaviour` that you have declared your custom `NetworkVariableBase` implementation within. +::: + + +## Strings: NetworkVariable or Custom NetworkVariable? + +Since a string can be considered "null" we already know that it isn't considered an unmanaged value type. So we **can't** use `NetworkVariable` like this: +```csharp +public NetworkVariable MyStringNetworkVariable = new NetworkVariable(); +``` +However, we just finished covering custom `NetworkVariable` implementations through the derivation of the abstract `NetworkVariableBase` class and how you can use managed types if you handle the serialization of the managed type(s). With Netcode for GameObjects there are many different ways you can handle sending text: +- Custom Messages +- Remote Procedure Calls (RPCs) +- NetworkVariable +- Custom NetworkVariable + +Depending upon how often (frequency) you will be changing the contents of the string and how much text you plan on sending (size) should be taken into consideration. For the purposes of this section, we will cover the NetworkVariable and Custom NetworkVariable approaches. + +### Strings: Custom NetworkVariable Basic Example + +If you need to synchronize text that doesn't change frequently (i.e. message of the day, text message from another player, etc.), then you might look at implementing a custom `NetworkVariable`. The below (very basic) example will synchronize any newly connecting client with the message set by the server: +```csharp + +public class TestStringContainer : NetworkBehaviour +{ + + private StringContainer m_StringContainer = new StringContainer(); + public override void OnNetworkSpawn() + { + if (IsServer) + { + m_StringContainer.Text = "This is my test to see if the string is replicated on clients."; + } + else + { + Debug.Log($"Client-Side StringContainer = {m_StringContainer.Text}"); + } + } +} + +public class StringContainer : NetworkVariableBase +{ + /// Managed list of class instances + public string Text = default; + + /// + /// Writes the complete state of the variable to the writer + /// + /// The stream to write the state to + public override void WriteField(FastBufferWriter writer) + { + // If there is nothing, then return 0 as the string size + if (string.IsNullOrEmpty(Text)) + { + writer.WriteValueSafe(0); + return; + } + + var textByteArray = System.Text.Encoding.ASCII.GetBytes(Text); + + // Write the total size of the string + writer.WriteValueSafe(textByteArray.Length); + var toalBytesWritten = 0; + var bytesRemaining = textByteArray.Length; + // Write the string values + while (bytesRemaining > 0) + { + writer.WriteValueSafe(textByteArray[toalBytesWritten]); + toalBytesWritten++; + bytesRemaining = textByteArray.Length - toalBytesWritten; + } + } + + /// + /// Reads the complete state from the reader and applies it + /// + /// The stream to read the state from + public override void ReadField(FastBufferReader reader) + { + // Reset our string to empty + Text = string.Empty; + var stringSize = (int)0; + // Get the string size in bytes + reader.ReadValueSafe(out stringSize); + + // If there is nothing, then we are done + if (stringSize == 0) + { + return; + } + + // allocate an byte array to + var byteArray = new byte[stringSize]; + var tempByte = (byte)0; + for(int i = 0; i < stringSize; i++) + { + reader.ReadValueSafe(out tempByte); + byteArray[i] = tempByte; + } + + // Convert it back to a string + Text = System.Text.Encoding.ASCII.GetString(byteArray); + } + + public override void ReadDelta(FastBufferReader reader, bool keepDirtyDelta) + { + // Do nothing for this example + } + + public override void WriteDelta(FastBufferWriter writer) + { + // Do nothing for this example + } +} +``` + +For simplicity purposes, the above example doesn't handle updating connected clients with any changes to the `Text` string property. It is just one possible approach you might take if you are not concerned about the memory allocation of the temporary `byte` array. It is a "bare minimum and non-optimized" example in order to demonstrate that as long as your serialization process knows what to write and what to read you can serialize any form of managed type. + +:::important +If you already had a maximum string size in mind, you could pre-allocate the byte array to avoid the cost of memory allocation. The downside to this is that you would lose the "managed" flexibility of being able to handle varying message sizes, but the upside (as you will find out in the next example) is that you would always only send the exact number of bytes the string consumes and not send the entire pre-allocated buffer (i.e. you save on bandwidth). +::: + +However, if you already know the maximum size of the `string` that you want to synchronize then there is another way to handle synchronizing "fixed" strings. + +### Strings: NetworkVariable FixedString Example + +Perhaps you want to leverage from the already existing `NetworkVariable` class to handle synchronizing connected clients with any changes that might occur to a string or you might want to keep a very strict "no memory allocations during runtime" design pattern. Under either of these scenarios, you would want to use one of the `Unity.Collections.FixedString` value types. In the below example, we used a `FixedString128Bytes` as the `NetworkVariable` value type and then, on the server side, it will change the string value each time you press the space bar on the server or host instance. Joining clients will be synchronized with the current value applied on the server side, and then each time you hit the space bar on the server side the client will be synchronized with the changed string. + +:::caution +`NetworkVariable` will serialize the entire 128 bytes each time the `Value` is changed even if you only consume a few bytes. In order to only update what has changed you would need to create a custom `NetworkVariable` that handles only synchronizing the deltas between the previous and current versions of the `NetworkVariable`. +::: + +```csharp +public class TestFixedString : NetworkBehaviour +{ + /// Create your 128 byte fixed string NetworkVariable + private NetworkVariable m_TextString = new NetworkVariable(); + + private string[] m_Messages ={ "This is the first message.", + "This is the second message (not like the first)", + "This is the third message (but not the last)", + "This is the fourth and last message (next will roll over to the first)" + }; + + private int m_MessageIndex = 0; + + public override void OnNetworkSpawn() + { + if (IsServer) + { + // Assin the current value based on the current message index value + m_TextString.Value = m_Messages[m_MessageIndex]; + } + else + { + // Subscribe to the OnValueChanged event + m_TextString.OnValueChanged += OnTextStringChanged; + // Log the current value of the text string when the client connected + Debug.Log($"Client-{NetworkManager.LocalClientId}'s TextString = {m_TextString.Value}"); + } + } + + public override void OnNetworkDespawn() + { + m_TextString.OnValueChanged -= OnTextStringChanged; + } + + private void OnTextStringChanged(FixedString128Bytes previous, FixedString128Bytes current) + { + // Just log a notification when m_TextString changes + Debug.Log($"Client-{NetworkManager.LocalClientId}'s TextString = {m_TextString.Value}"); + } + + private void LateUpdate() + { + if (!IsServer) + { + return; + } + + if (Input.GetKeyDown(KeyCode.Space)) + { + m_MessageIndex++; + m_MessageIndex %= m_Messages.Length; + m_TextString.Value = m_Messages[m_MessageIndex]; + Debug.Log($"Server-{NetworkManager.LocalClientId}'s TextString = {m_TextString.Value}"); + } + } +} +``` + +In the above example we have one initial memory allocation when the component is instantiated (128 bytes for the fixed string), but from that point forward that allocated buffer is used to store the string (saving the cost of memory allocations at the expense of bandwidth usage when synchronizing clients to the change). + +:::note +The above example uses a pre-set list of strings to cycle through for example purposes only. If you have a predefined set of text strings as part of your actual design then you would not want to use a FixedString to handle synchronizing the changes to `m_TextString`. Instead, you would want to use a `uint` for the type `T` where the `uint` was the index of the string message to apply to `m_TextString`. +::: + + + + + diff --git a/versioned_docs/version-1.0.0/basics/object-spawning.md b/versioned_docs/version-1.0.0/basics/object-spawning.md new file mode 100644 index 000000000..1ff83fc8b --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/object-spawning.md @@ -0,0 +1,309 @@ +--- +id: object-spawning +title: Object Spawning +sidebar_label: Object Spawning +--- +In Unity, you typically create a new game object using the `Instantiate` function. Creating a game object with `Instantiate` will only create that object on the local machine. `Spawning` in Netcode for GameObjects (Netcode) means to instantiate and/or spawn the object that is synchronized between all clients by the server. + +## Network Prefabs + +A network prefab is any unity prefab asset that has one `NetworkObject` component attached to a `GameObject` within the prefab. More commonly, the `NetworkObject` component is attached to the root `GameObject` of the prefab asset because this allows any child `GameObject` to have `NetworkBehaviour` components automatically assigned to the `NetworkObject`. The reason for this is that a `NetworkObject` component attached to a `GameObject` will be assigned (associated with) any `NetworkBehaviour` components on: +- the same `GameObject` that the `NetworkObject` component is attached to +- any child or children of the `GameObject` that the `NetworkObject` is attached to. + +:::note +A caveat of the above two rules is when one of the children `GameObject`s also has a `NetworkObject` component assigned to it (a.k.a. "Nested NetworkObjects"). Because nested `NetworkObject` components are not permited in network prefabs, Netcode for GameObjects will notify you in the editor if you are trying to add more than one `NetworkObject` to a prefab and will not allow you to do this. +::: + +When a `NetworkBehaviour` is assigned to a `NetworkObject`, the `NetworkObject.NetworkObjectId` is used to help determine which `NetworkBehaviour` component instance will receive an update to a `NetworkVariable` or where to invoke an RPC. A `NetworkObject` component can have one or more `NetworkBehaviour` components assigned to it. + +### Registering a Network Prefab + +One of the requirements to be able to spawn a network prefab instance is that it must be registered with the `NetworkManager` via the "Network Prefabs" property list. +The two steps to registering a network prefab with `NetworkManager`: + +1. Create a network prefab by creating a prefab with a `NetworkObject` component attached to the root `GameObject` +1. Add your network prefab to the Network Prefabs list poperty of the `NetworkManager`. + +### Spawning a Network Prefab (Overview) + +Netcode uses a server authorative networking model so spawning netcode objects can only be done on a server or host. To spawn a network prefab, you must first create an instance of the network prefab and then invoke the spawn method on the `NetworkObject` component of the instance you created. +_In most cases, you will want to keep the `NetworkObject` component attached to the root `GameObject` of the network prefab._ + +By default a newly spawned network prefab instance is owned by the server unless otherwise specified. + +See [Ownership](networkobject.md#ownership) for more information. + +The following is a basic example of how to spawn a network prefab instance (with the default server ownership): + +```csharp +GameObject go = Instantiate(myPrefab, Vector3.zero, Quaternion.identity); +go.GetComponent().Spawn(); +``` + +The `NetworkObject.Spawn` method takes 1 optional parameter that defaults to `true`: + +```csharp +public void Spawn(bool destroyWithScene = true); +``` + +When you set the destroyWithScene property to `false` it will be treated the same as when you set [Object.DontDestroyOnLoad](https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html). Typically, you use this if you are loading a scene using [LoadSceneMode.Single](https://docs.unity3d.com/ScriptReference/SceneManagement.LoadSceneMode.html) parameter. + +[Learn more about Netcode Scene Management here](scenemanagement/scene-management-overview.md) + +## Destroying / Despawning + +By default, a spawned network prefab instance that is destroyed on the server/host will be automatically destroyed on all clients. + +When a client disconnects, all network prefab instances created during the network session will be destroyed on the client-side by default. If you do not want that to happen, set the `DontDestroyWithOwner` field on `NetworkObject` to true before despawning. + +To do this at runtime: +```csharp +m_SpawnedNetworkObject.DontDestroyWithOwner = true; +m_SpawnedNetworkObject.Despawn(); +``` + +To make this the default from the editor insepctor view: + +![image](images/DontDestroyWithOwner.png) + +As an alternative way, you can make the `NetworkObject.DontDestroyWithOwner` property default to `true` by setting it on the `NetworkObject` itself like in the above screenshot. + +### Despawning +Only a server can despawn a `NetworkObject`, and the default despawn behavior is to destroy the associated GameObject. In order to despawn but not destroy a `NetworkObject`, you should call `NetworkObject.Despawn` and pass false as the parameter. Clients will always be notified and will mirror the despawn behavior. If you despawn and destroy on the server then all clients will despawn and then destroy the `GameObject` that the `NetworkObjet` component is attached to. + +On the client side, you should never call `Object.Destroy` on any `GameObject` with a `NetworkObject` component attached to it (this is not supported and will cause an exception to be thrown). If you want to use a more client authority model, have the client with ownership invoke a ServerRpc to defer the despawning on server side. + +The only way to despawn `NetworkObject` for a specific client is to use `NetworkObject.NetworkHide`. +See: [Object Visibility](object-visibility.md) for more information on this. + +:::warning +If you have `GameObject` children, with `NetworkBehaviour` components attached, of a parent `GameObject`, with a `NetworkObject` component attached, you cannot disable the `GameObject` children prior to spawning or despawning. Doing so, in v1.0.0, could cause unexpected results and it is recommended to make sure all children are enabled in the hierarchy prior to spawning or despawning. +::: + +## Dynamically Spawned Network Prefabs + +Netcode for GameObjects uses the term "dynamically spawned" to convey that the `NetworkObject` is being spawned via user specific code. Whereas a player or in-scene placed `NetworkObject` (with scene management enabled) is typically spawned by Netcode for GameObjects. There are several ways to spawn a network prefab via code: + +### Dynamic Spawning (non-pooled): + +This type of dynamically spawned `NetworkObject` typically is a simple wrapper class that holds a reference to the prefab asset. In the example below, the `NonPooledDynamicSpawner.PrefabToSpawn` property holds a reference to the network prefab: + +```csharp + public class NonPooledDynamicSpawner : NetworkBehaviour + { + public GameObject PrefabToSpawn; + public bool DestroyWithSpawner; + private GameObject m_PrefabInstance; + private NetworkObject m_SpawnedNetworkObject; + + public override void OnNetworkSpawn() + { + // Only the server spawns, clients will disable this component on their side + enabled = IsServer; + if (!enabled || PrefabToSpawn == null) + { + return; + } + // Instantiate the GameObject Instance + m_PrefabInstance = Instantiate(PrefabToSpawn); + + // Optional, this example applies the spawner's position and rotation to the new instance + m_PrefabInstance.transform.position = transform.position; + m_PrefabInstance.transform.rotation = transform.rotation; + + // Get the instance's NetworkObject and Spawn + m_SpawnedNetworkObject = m_PrefabInstance.GetComponent(); + m_SpawnedNetworkObject.Spawn(); + } + + public override void OnNetworkDespawn() + { + if (IsServer && DestroyWithSpawner && m_SpawnedNetworkObject != null && m_SpawnedNetworkObject.IsSpawned) + { + m_SpawnedNetworkObject.Despawn(); + } + base.OnNetworkDespawn(); + } + } +``` + +Consumable and/or items that can be picked up by a player or NPC(i.e. a weapon, health, potion, etc.) would be some examples of when you might want to use non-pooled dynamically spawned `NetworkObjects`. + +:::caution +While the NonPooledDynamicSpawner example is one of the simplest ways to spawn a NetworkObject, there is a memory allocation cost associated with instantiating and destroying the GameObject and all attached components. This design pattern can sometimes be all you really need for the netcode game asset you are working with, and other times you might want to respawn/re-use the object instance. When performance is a concern and you want to spawn more than just one `NetworkObject` during the lifetime of the spawner or want to repeatedly respawn a single `NetworkObject`, the less proccessor and memory allocation intensive technique is to use [pooled dynamic spawning](#pooled-dynamic-spawning). +::: + +:::note +Really, the when we use the term "non-pooled" more often than not we are referring to the concept that a `GameObject` will be instantiated on both the server and the clients each time an instance is spawned. +::: + +### Pooled Dynamic Spawning + +Pooled dynamic spawning is when netcode objects (`GameObject` with one `NetworkObject` component) are not destroyed on the server or the client when despawned. Instead, specific components are just disabled (or the `GameObject` itself) when a netcode object is despawned. A pooled dynamically spawned netcode object is typically instantiated during an already memory allocation heavy period of time (like when a scene is loaded or even at the very start of your application prior to even establishing a network connection). Pooled dynamically spawned netcode objects are more commonly thought of as more than one netcode object that can be re-used without incurring the memory allocation and initialization costs. However, you might also run into scenarios where you need just one dynamically spawned netcode object to be treated like a pooled dynmically spawned netcode object. + +Fortunately, Netcode for GameObjects provides you with a way to be in control over the instatiation and destruction process for one or many netcode objects by via the `INetworkPrefabInstanceHandler` interface. Any `INetworkPrefabInstanceHandler`implementation should be registered with the `NetworkPrefabHandler`(for multiple netcode objects see [Object Pooling](../advanced-topics/object-pooling)) to accomplish this. + +The easiest way to not destroy a network prefab instance is to have something, other than the instance itself, keeping a reference to the instance. This way you can simply set the root `GameObject` to be inactive when it is despawned while still being able to set it active when the same network prefab type needs to be respawned. Below is one example of how you can accomplish this for a single netcode object instance: + +```csharp +public class SinglePooledDynamicSpawner : NetworkBehaviour, INetworkPrefabInstanceHandler +{ + public GameObject PrefabToSpawn; + public bool SpawnPrefabAutomatically; + + private GameObject m_PrefabInstance; + private NetworkObject m_SpawnedNetworkObject; + + + private void Start() + { + // Instantiate our instance when we start (for both clients and server) + m_PrefabInstance = Instantiate(PrefabToSpawn); + + // Get the NetworkObject component assigned to the prefab instance + m_SpawnedNetworkObject = m_PrefabInstance.GetComponent(); + + // Set it to be inactive + m_PrefabInstance.SetActive(false); + } + + private IEnumerator DespawnTimer() + { + yield return new WaitForSeconds(2); + m_SpawnedNetworkObject.Despawn(); + StartCoroutine(SpawnTimer()); + yield break; + } + + private IEnumerator SpawnTimer() + { + yield return new WaitForSeconds(2); + SpawnInstance(); + yield break; + } + + /// + /// Invoked only on clients and not server or host + /// INetworkPrefabInstanceHandler.Instantiate implementation + /// Called when Netcode for GameObjects need an instance to be spawned + /// + public NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaternion rotation) + { + m_PrefabInstance.SetActive(true); + m_PrefabInstance.transform.position = transform.position; + m_PrefabInstance.transform.rotation = transform.rotation; + return m_SpawnedNetworkObject; + } + + /// + /// Client and Server side + /// INetworkPrefabInstanceHandler.Destroy implementation + /// + public void Destroy(NetworkObject networkObject) + { + m_PrefabInstance.SetActive(false); + } + + public void SpawnInstance() + { + if (!IsServer) + { + return; + } + + if (m_PrefabInstance != null && m_SpawnedNetworkObject != null && !m_SpawnedNetworkObject.IsSpawned) + { + m_PrefabInstance.SetActive(true); + m_SpawnedNetworkObject.Spawn(); + StartCoroutine(DespawnTimer()); + } + } + + public override void OnNetworkSpawn() + { + // We register our network prefab and this NetworkBehaviour that implements the + // INetworkPrefabInstanceHandler interface with the prefab handler + NetworkManager.PrefabHandler.AddHandler(PrefabToSpawn, this); + + if (!IsServer || !SpawnPrefabAutomatically) + { + return; + } + + if (SpawnPrefabAutomatically) + { + SpawnInstance(); + } + } + + public override void OnNetworkDespawn() + { + if (m_SpawnedNetworkObject != null && m_SpawnedNetworkObject.IsSpawned) + { + m_SpawnedNetworkObject.Despawn(); + } + base.OnNetworkDespawn(); + } + + public override void OnDestroy() + { + // This example destroys the + if (m_PrefabInstance != null) + { + // Always deregister the prefab + NetworkManager.Singleton.PrefabHandler.RemoveHandler(PrefabToSpawn); + Destroy(m_PrefabInstance); + } + base.OnDestroy(); + } +} +``` + +You might run across a situation where you still want other components on the root `GameObject` of your network prefab instance to remain active. Primarily, you want to be able to easily disable the components that would normally be active when the netcode object is considered spawned. + +Below is an example of what a non-pooled friendly prefab might look like: + +![image](images/non-pooled-friendly-prefab.png) + +The issues you might run into with the above prefab hierarchy is that everything is on a single `GameObject`, and as such if you wanted to disable the `MeshRenderer` and the `NetworkObjectLabel`, [one of our classes in the Netcode for GameObjects test project](https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/blob/f0631414e5a5358a5ac7811d43273b1a82a60ca9/testproject/Assets/Scripts/NetworkObjectLabel.cs#L4), you would need to get those component types prior to disabling them (i.e. during `Start` or `OnNetworkSpawn` or get them when `OnNetworkDespawn` is invoked). + +To reduce this level of complexity, a more "pooled dynamic spawning" friendly prefab heirarchy might look like this: + +![image](images/pooled-friendly-prefab.png) + +The `NetworkObject` sits at the root `GameObject` of the network prefab. The child `GameObject`, SpawnedComponents, then contains everything that you might want to have disabled when the network prefab instance is not spawned: + +![image](images/pooled-friendly-prefab-child.png) + +This reduces the complexity down to setting the SpawnedComponents `GameObject` to inactive, which will also disable all of the components attached to it. + +:::tip +Using this type of a hierarchical separation is useful in many ways (especially when you have a much more complex prefab). For more complex prefabs, you could further expand this pattern into specific categories (i.e. visuals, physics, sound, etc) which will provide you with a more macrocosmic way to control enabling or disabling many different components without having to have references to all of them. +::: + +## In-Scene Placed `NetworkObject` + +Any objects in the scene with active and spawned `NetworkObject` components will get automatically replicated by Netcode. There is no need to manually spawn them when scene management is enabled in the `NetworkManager`. In-scene placed `NetworkObjects` should typically be used like a "static" netcode object, where the netcode object is typically spawned upon the scene being loaded on the server-side and synchronized with clients once they finish loading the same scene. + +[Learn more about In-Scene Placed `NetworkObjects`](scenemanagement/inscene-placed-networkobjects) + +Generally, there are **two** modes that define how an in-scene placed `NetworkObject` is synchronized. +- Soft Synchronization (Scene Management enabled) +- Prefab Synchronization (Scene Management disabled) + +### Soft Synchronization + +`SoftSync` or "Soft Synchronization" is a term you might run across if you run into any issue with in-scene placed `NetworkObjects`. Soft synchronization only occurs if scene management is enabled in the `NetworkManager` properties. If you receive a "soft synchronization error", then this typically means that a client could not locate the same in-scene placed `NetworkObject` after loading a scene. + +:::note +The benefit of using scene management is that you don't have to register every in-scene placed `NetworkObject` with the `NetworkManager` as a network prefab, and it handles synchronizing clients to your current game state. +::: + +### Prefab Synchronization + +`PrefabSync` or "Prefab Synchronization" is used if scene management is disabled in the `NetworkManager`. With prefab synchronization, every in-scene placed `NetworkObject` has to be a network prefab and must be registered with `NetworkPrefabs` list. When a client starts, Netcode will destroy all existing in-scene placed `NetworkObject`s and spawn its corresponding prefab from the `NetworkPrefabs` list instead. This also means that you will have to implement your own scene manager and handle how you synchronize clients when they join a network session. + +**PrefabSync is ONLY recommended for advanced development and/or multi project setups**. + + diff --git a/versioned_docs/version-1.0.0/basics/object-visibility.md b/versioned_docs/version-1.0.0/basics/object-visibility.md new file mode 100644 index 000000000..7d1e17413 --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/object-visibility.md @@ -0,0 +1,62 @@ +--- +id: object-visibility +title: Object Visibility +sidebar_label: Object Visibility +--- + +## What Is NetworkObject Visibility? +Object (NetworkObject) visibility is a Netcode for GameObjects term used to describe whether a `NetworkObject` is visible to one or more clients as it pertains to a netcode/network perspective. When a `NetworkObject` is visible to a client, the server will assure the client has a spawned version (a clone) of the `NetworkObject`. This also means that all network traffic generated by the server for the visible `NetworkObject` will be sent to all clients that are aware (i.e. it is "visible to the clients") of it. Likewise, when a `NetworkObject` is "hidden" (i.e. not visible) from a client, then the client will despawn and destroy the `NetworkObject` if it was previously visible and no network traffic generated by the hidden `NetworkObject` will be received by the client(s) it is hidden from. + + +## Using Visibility + +One way to determine visibility is to assign a callback to `NetworkObject.CheckObjectVisibility`. This callback is invoked when new clients connect or just before the associated `NetworkObject` is spawned. Looking at the example below, we can see the callback includes a client identifier (clientId) value as a parameter which is used to determine whether the `NetworkObject` is visible to the client. If `NetworkObject.CheckObjectVisibility` is not assigned, then Netcode for GameObjects assumes it is visible to all clients. + +### CheckObjectVisibility Callback Example +```csharp +NetworkObject netObject = GetComponent(); +netObject.CheckObjectVisibility = ((clientId) => { + // return true to show the object, return false to hide it + + + if (Vector3.Distance(NetworkManager.Singleton.ConnectedClients[clientId].PlayerObject.transform.position, transform.position) < 5) + { + // Only show the object to players that are within 5 meters. Note that this has to be rechecked by your own code + // If you want it to update as the client and objects distance change. + // This callback is usually only called once per client + return true; + } + else + { + // Hide this NetworkObject + return false; + } +}); +``` + +### Additional Visibility Methods: +The `CheckObjectVisibility` callback helps you determine if a `NetworkObject` is visible to a specific client when the `NetworkObject` is spawned. However, you might have the need to change a `NetworkObject`'s visibility after it is spawned. To change the visibility of a `NetworkObject` that is already spawned, you can use the following methods: + +Make a `NetworkObject` visible to a single client: +```csharp +NetworkObject netObject = GetComponent(); +netObject.NetworkShow(clientIdToShowTo); +``` + +Make a `NetworkObject` invisible/hidden from a single client: +```csharp +NetworkObject netObject = GetComponent(); +netObject.NetworkHide(clientIdToHideFrom); +``` + +Make several `NetworkObject`s visible to a single client (static method): +```csharp +/// networkObjects is of type List +NetworkObject.NetworkShow(networkObjects, clientId); +``` + +Make several `NetworkObject`s invisible/hidden to a single client (static method): +```csharp +/// networkObjects is of type List +NetworkObject.NetworkHide(networkObjects, clientId); +``` diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/custom-management.md b/versioned_docs/version-1.0.0/basics/scenemanagement/custom-management.md new file mode 100644 index 000000000..142e659ea --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/scenemanagement/custom-management.md @@ -0,0 +1,63 @@ +--- +id: custom-management +title: Custom Scene Management +sidebar_label: Custom Management +--- + +:::caution +If you have not already read the [Using NetworkSceneManager](using-networkscenemanager.md) section, it is highly recommended to do so before proceeding. +Custom Scene Management currently has some drawbacks that we hope to improve upon over time. +::: + +## Building Your Own Scene Management Solution +Netcode for GameObjects has primarily focused on providing a scene management solution that should meet most projects' needs. However, there might be a special case scenario where you require building your own scene management solution. The very first step is to disable the "Enable Scene Management" property in your `NetworkManager`'s properties. All of your scene loading and unloading will be handled via the UnityEngine.SceneManagement.SceneManager class. + +### Registering In-Scene Placed NetworkObjects +While integrated scene management solution handles the synchronization of in-scene placed `NetworkObject`s, custom scene management treats everything like a dynamically spawned `NetworkObject`. As such, you are **required to register a Network Prefab hash override for each in-scene placed `NetworkObject` instance**. + +**In-Scene Placed `NetworkObject` Registration Steps:** +- [See "Creating In-Scene Placed Network Prefab Instances"](inscene-placed-networkobjects#creating-in-scene-placed-network-prefab-instances) as a reference for creating in-scene placed Network Prefabs. +- Create an instance of a Network Prefab in your scene. +- Select the instance and in the inspector view navigate to the `NetworkObject` component + - Copy the GlobalObjectIdHash value of the `NetworkObject` + ![image](images/CustomManagementGlobalObjectIdHash.png) +- Within your `NetworkManager`, create a new Network Prefab entry in the Network Prefabs list. + - Check the "Override" property of the new Network Prefab entry. + - Select "Hash" and paste the GlobalObjectIdHash value into the "Hash" field. + - Drag an drop your recently created in-scene placed Network Prefab to link the two together (GlobalObjectIdHash and Network Prefab) + ![image](images/CustomManagementRegister.png) +:::tip +If your `NetworkManager` is in another scene, then the easiest way to accomplish this is to (within the editor) load the scene containing the `NetworkManager` instance and the scene you are creating an instance of your in-scene placed Network Prefab. Having quick access to your `NetworkManager`'s properties helps expedite the in-scene placed Network Prefab override registration process. +::: + +Once you have registered your in-scene placed Network Prefab instances with the `NetworkManager`, you can then start a server/host and have a client connect and synchronize with the in-scene placed Network Prefab instances (as long as both client and server have pre-loaded the scene or scenes required). Due to the complexity of in-scene placed Network Prefab registration, we highly recommend using in-scene placed `NetworkObject`s sparingly and [use the Hybrid approach](inscene-placed-networkobjects#a-hybrid-approach-example) as much as possible. + +:::important +When a client first connects, it will delete any in-scene placed `NetworkObjects` in any of the scenes it has currently loaded. When using a custom scene management solution, In-scene placed `NetworkObject`s are actually dynamically spawned. While registering in-scene placed Network Prefabs does require more initial setup, it also removes many of the integrated scene management restraints. As your custom scene management solution starts to take shape, you can devise your own rules for in-scene placed Network Prefab instances (if any). +::: + +## Starting a Netcode Enabled Game Session +The recommended way of starting session using your own scene management solution is to assure that when a client attempts to join a netcode game session it should already have (as best as possible) any scenes that the server might have loaded. While this does not assure that your newly connecting client will load any additional scenes that might have been loaded, using this approach initially will get you started so you can then come up with a strategy to handling: +- Scene Synchronization +- Scene Loading and Unloading + +### Scene synchronization + While you might have an initial set of scenes loaded, you are bound to want to load more scenes as your netcode enabled game session progresses. Once a client has fully connected (you can use `NetworkManager.OnClientConnected` for this), you will want to send the client a list of additional scenes to be loaded. + - You will want to come up with your own "client state" as it progresses through this synchronization process to determine when a client has loaded all scenes. + - As an example: A client might be connected and has synchronized with the default scenes required to connect, but then you have one or more additional scenes you might have loaded (additively) that the client needs to load and synchronize (spawn) any in-scene placed Network Prefab instances + +### Scene Loading and Unloading +You can accomplish this using either RPCs or custom messages. You might even use your own `INetworkSerializable` implementation that contains a list of scenes and whether they should be loaded or unloaded. You should always have some form of "complete" response factored into your design so you know when a client has finished loading/unloading a scene. You will also want to devise a strategy for loading a scene in `LoadSceneMode.Additive` and `LoadSceneMode.Single` modes. + +:::tip +Creating a global scene management script and attaching it to the same GameObject as the `NetworkManager` is one way to assure your custom netcode scene management solution persists while a game session is in progress. +::: + + + + + + + + + diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/ClientSyncUpdates.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/ClientSyncUpdates.png new file mode 100644 index 000000000..9bbbe812a Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/ClientSyncUpdates.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/CustomManagementGlobalObjectIdHash.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/CustomManagementGlobalObjectIdHash.png new file mode 100644 index 000000000..45cca9294 Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/CustomManagementGlobalObjectIdHash.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/CustomManagementRegister.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/CustomManagementRegister.png new file mode 100644 index 000000000..8e7687d7e Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/CustomManagementRegister.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/LoadNewSceneTimeline.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/LoadNewSceneTimeline.png new file mode 100644 index 000000000..9bb21b44c Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/LoadNewSceneTimeline.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/LoadingAdditiveScene.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/LoadingAdditiveScene.png new file mode 100644 index 000000000..5f99a4b87 Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/LoadingAdditiveScene.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/SceneEventProperties-1.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/SceneEventProperties-1.png new file mode 100644 index 000000000..6c6d81ceb Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/SceneEventProperties-1.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/SceneEventProperties-2.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/SceneEventProperties-2.png new file mode 100644 index 000000000..66cda8139 Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/SceneEventProperties-2.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/SceneEventSynchronizationTimeline.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/SceneEventSynchronizationTimeline.png new file mode 100644 index 000000000..153b4fe42 Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/SceneEventSynchronizationTimeline.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/SwitchingToNewSceneLight.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/SwitchingToNewSceneLight.png new file mode 100644 index 000000000..fad635c44 Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/SwitchingToNewSceneLight.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/UnloadingAdditiveScene.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/UnloadingAdditiveScene.png new file mode 100644 index 000000000..577ee2f3c Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/UnloadingAdditiveScene.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/UnloadingSceneTimeline.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/UnloadingSceneTimeline.png new file mode 100644 index 000000000..8e4be2c81 Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/UnloadingSceneTimeline.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/images/scenemanagement_synchronization_overview.png b/versioned_docs/version-1.0.0/basics/scenemanagement/images/scenemanagement_synchronization_overview.png new file mode 100644 index 000000000..d0d8f3121 Binary files /dev/null and b/versioned_docs/version-1.0.0/basics/scenemanagement/images/scenemanagement_synchronization_overview.png differ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/inscene-placed-networkobjects.md b/versioned_docs/version-1.0.0/basics/scenemanagement/inscene-placed-networkobjects.md new file mode 100644 index 000000000..e3e758380 --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/scenemanagement/inscene-placed-networkobjects.md @@ -0,0 +1,236 @@ +--- +id: inscene-placed-networkobjects +title: In-Scene (Placed) NetworkObjects +sidebar_label: In-Scene NetworkObjects +--- +:::caution +If you have not already read the [Using NetworkSceneManager](using-networkscenemanager.md) section, it is highly recommended to do so before proceeding. +::: + +## Introduction +At this point, you have most likely run across the term "in-scene placed NetworkObject" or "in-scene NetworkObject" several times. An in-scene placed `NetworkObject` means a `GameObject` with a `NetworkObject` component was added to a scene from within the editor. There are many uses for in-scene placed `NetworkObjects`, which includes but is not limited to: +- Management systems + - An example would be a `NetworkObject` pool managent system that dynamically spawns Network Prefabs. +- Interactive "world objects" that are typically easier to place in-scene than spawn + - An example of this would be a door that can only be unlocked by a key (or the like), if a player unlocks it you want other players to know about it being unlocked and making it an in-scene placed `NetworkObject` simplifies the positioning of the door relative to the other surrounding world geometry. + - "Scene Static" visual elements + - An example of this might be a heads up display (HUD) that includes information about other items or players (i.e. radar or the like) + - Another example might be some form of platform or teleporter that moves a player from one location to the next when a player enters a trigger or uses an object. + +:::tip +Items that can be picked up are typically better to implement as a "hybrid" approach where you use both an in-scene placed and a dynamically spawned `NetworkObject`. The in-scene placed `NetworkObject` is commonly used to configure additional information about the item (what kind, does another one respawn after the other one is picked up and if so how much time should it wait before spawning a new item, etc.) while the dynamically spawned object is the item itself. The hybrid approach is explained in more detail below in this section. +::: + +### In-Scene Placed vs. Dynamically Spawned `NetworkObjects` (Order of Operations) +Because in-scene placed `NetworkObject`s are instantiated when a scene loads, they have a different order of operations to that of dynamically spawned `NetworkObject`s when it comes to spawning: + +Dynamically Spawned | In-Scene Placed +------------------- | --------------- +Awake | Awake +OnNetworkSpawn | Start +Start | OnNetworkSpawn + +Looking at the above table, we can quickly see that "spawning" occurs after `Awake` but before `Start` for dynamically spawned `NetworkObject`s, but for in-scene placed `NetworkObject`s it occurs afterboth Awake and Start are invoked. As mentioned before, in-scene placed `NetworkObject`s are instantiated when the scene is loaded which means both the `Awake` and the `Start` methods are invoked prior to an in-scene placed `NetworkObject` being spawned. This distinct difference is important to keep in mind when doing any form of dependency related initializations that might require an active network session. This is especially important to consider when you are using the same `NetworkBehaviour` component with both dynamically and in-scene placed `NetworkObjects`. + +### In-Scene Placed Network Prefab Instances +A common "usage" design pattern for frequently used in-scene placed `NetworkObject`s is to make it a Network Prefab in order to simplify the replication process in order to achieve the functionality. With network prefabs, you can easily use the "drag & drop" approach when editing a scene. Another benefit of in-scene placed `NetworkObject`s is that they do not required you to register them with the NetworkManager. In-scene placed `NetworkObjects` are registered internally, when scene management is enabled, for tracking and identification purposes. + +### Creating In-Scene Placed Network Prefab Instances +In order to create a Network Prefab that can be used as an in-scene placed `NetworkObject` you must do the following: +1. In the scene you wish to create the instance (or any open scene) create an empty GameObject and add a `NetworkObject` component to it. +2. Add any other `NetworkBehaviour`s required by your in-scene placed `NetworkObject`. +3. Drag and drop the newly created GameObject into your Prefab (or associated) folder. +4. Delete the GameObject instance in your scene (this is *required* to get a proper GlobalObjectIdHash value assigned) +5. Finally, drag and drop an instance of your newly created Network Prefab into the scene you wish to have an instance of your in-scene placed `NetworkObject`. + +## Using In-Scene Placed NetworkObjects +Since there are additional complexities involved with in-scene placed `NetworkObject`s, some use cases are more easily achieved through dynamically spawned `NetworkObjects` or through a combination of both types. While Netcode for GameObjects has made many improvements with in-scene placed `NetworkObjects`, there are still special edge case scenarios that you have to take into consideration. + +### Static Objects +There are many scenarios where you might just need to use the in-scene placed `NetworkObject` to keep track of when a door is opened, a button pushed, a lever pulled, and any other "toggle oriented" type of state. This is what we consider "static objects": + - They are "statically" spawned while its originating scene is loaded and only de-spawned when its originating scene is unloaded. + - The originating scene is the scene that the in-scene `NetworkObject` was placed. + - They are typically associated with some world object that is visible to the players (i.e. door, switch, etc.) + - They aren't migrated into other scenes or parented under another `NetworkObject` + - _Think of a draw bridge that comes down when a certain game state is reached, the draw bridge is most likely connected to some castle or perhaps a section of the castle and would never need to be migrated to another scene._ + This usage pattern is possibly the least complex ways to use an in-scene placed `NetworkObject`. + +### Netcode Managers +An in-scene placed `NetworkObject` used as a netcode manager could range from handling game states (i.e. player scores) to a `NetworkObject` spawn manager (pooled or not). Typically, a manager will stay instantiated and spawned as long as the scene it was placed in remains loaded. For scenarios where you want to keep a global game state, the recommended solution is to place the in-scene `NetworkObject` in an additively loaded scene that remains loaded for the duration of your network game session. + +If you are using "Scene Switching" (i.e. loading a scene in LoadSceneMode.Single), then you can migrate the in-scene placed `NetworkObject` (used for management purposes) into the DDoL by sending its `GameObject` to the DDoL: + +```csharp +private void Start() +{ + // Do not use this for Dynamically spawned NetworkObjects + DontDestroyOnLoad(gameObject); +} +``` + +:::warning +Once migrated into the DDoL, migrating the in-scene placed `NetworkObject` back into a different scene after it has already been spawned will cause soft synchronization errors with late joining clients. Once in the DDoL it should stay in the DDoL. This is only for scene switching, if you are not using scene switching then it is recommended to use an additively loaded scene and keep that scene loaded for as long as you wish to persist the in-scene placed `NetworkObject`(s) being used for state management purposes. +::: + +### Complex In-Scene NetworkObjects: +The most common mistake when using an in-scene placed `NetworkObject` is to try and use it like a dynamically spawned `NetworkObject`. When trying to decide if you should use an in-scene placed or dynamically spawned `NetworkObject`, you should ask yourself the following questions: +- Do you plan on de-spawning and destroying the `NetworkObject`? _(highly recommended to use dynamically spawned)_ +- Could it be parented, at runtime, under another `NetworkObject`? +- Excluding any special case DDoL scenarios, will it be moved into another scene other than the originating scene? +- Do you plan on having full scene-migrations (i.e. LoadSceneMode.Single or "scene switching") during a network session? + +If you answered yes to any of the above questions, then using only an in-scene placed `NetworkObject` to implement your feature might not be the right choice. However, just because you did answer yes to one or more of the above questions doesn't mean you shouldn't use an in-scene placed `NetworkObject` either. While the previous two sentences might seem puzzling, there are scenarios where the "best choice" (regarding simplicity and modularity) is to use a hybrid approach by using a combination of both in-scene placed and dynamically spawned `NetworkObject`s! + +#### A Hybrid Approach Example +Perhaps your project's design includes making some world items that can either be consumed (i.e. health) or picked up (weapons, items, etc) by players. Initially, using a single in-scene placed `NetworkObject` might seem like the best approach for this world item feature. + +However, there is another way to accomplish the very same thing while keeping a clear defining line between dynamically spawned and in-scene placed `NetworkObject`s. As opposed to lumping everything into a single NetworkPrefab and handling the additional complexities involved with in-scene placed `NetworkObject`s, you could create two Network Prefabs: + +1. World item Network Prefab: since this will be dynamically spawned, you can re-use this Network Prefab with any spawn manager (pooled or single). +2. A "single spawn manger" (non-pooled): this will spawn the world item Network Prefab. The single-spawn manager could spawn the dynamically spawned `NetworkObject` at its exact location with an option to use the same rotation and scale. +:::tip + Your "single spawn manager" could also have a list of GameObjects used as spawn points in the event you wish to spawn world items in various locations randomly and/or based on game state. +::: + +Using this approach allows you to: +1. Re-use the same single spawn manager with any other Network Prefab registered with the `NetworkManager` +2. Not worry about the complexities involved with treating an in-scene placed `NetworkObject` like a dynamically spawned one. + +[See a Dynamic Spawning (non-pooled) "Hybrid Approach" Example Here](../object-spawning#dynamic-spawning-non-pooled) + +### Spawning and De-spawning +By default, an in-scene placed `NetworkObject` will always get spawned when the scene it was placed within is loaded and a network session is in progress. However, in-scene placed `NetworkObject`s are unique from dynamically spawned `NetworkObject`s when it comes to spawning and de-spawning. Functionally speaking, when de-spawning a dynamically spawned NetworkObject you can always spawn a new instance of the `NetworkObject`'s associated network prefab. So, whether you decide to destroy a dynamically spawned `NetworkObject` or not, you can always make another clone of the same network prefab unless you want to preserve the current state of the instance being de-spawned.
+With in-scene placed NetworkObjects, the scene it is placed within is similar to the network prefab used to dynamically spawn a `NetworkObject` in that both are used to uniquely identify the spawned `NetworkObject`. The primary difference is that you use a network prefab to create a new dynamically spawned instance where you a required to additively load the same scene to create another in-scene placed `NetworkObject` instance.
+ +**How the two types of spawned `NetworkObject`s are uniquely identified** + +Dynamically Spawned | In-Scene Placed +------------------- | --------------- +NetworkPrefab | Scene +GlobalObjectIdHash | Scene Handle (_When Loaded_) & GlobalObjectIdHash + +Once the `NetworkObject` is spawned, Netcode for GameObjects uses the `NetworkObjectId` to uniquely identify it for both types. An in-scene placed `NetworkObject` will still continue to be uniquely identified by the scene handle that it originated from and the GlobalObjectIdHash even if the in-scene placed `NetworkObject` is migrated to another additively loaded scene and originating scene is unloaded. + +
+ +**_What if you wanted to de-spawn and re-spawn the same in-scene placed NetworkObject?_** + +When invoking the `Despawn` method of a `NetworkObject` with no parameters, it will always default to destroying the `NetworkObject`: + +```csharp +NetworkObject.Despawn(); // Will de-spawn and destroy (!!! not recommended !!!) +``` + +If you want an in-scene placed NetworkObject to persist after it has been de-spawned, it is recommended to always set the first parameter of the `Despawn` method to `false`: + +```csharp +NetworkObject.Despawn(false); // Will only de-spawn (recommended usage for in-scene placed NetworkObjects) +``` + +Now that you have a de-spawned `NetworkObject`, you might notice that the associated `GameObject` and all of its components are still active and possibly visible to all players (i.e. like a `MeshRenderer` component). Unless you have a specific reason to keep the associated `GameObject` active in the hierarchy, you can override the virtual `OnNetworkDespawn` method in a `NetworkBehaviour` derived component and set the `GameObject` to in-active: + +```csharp +using UnityEngine; +using Unity.Netcode; + +public class MyInSceneNetworkObjectBehaviour : NetworkBehaviour +{ + public override void OnNetworkDespawn() + { + gameObject.SetActive(false); + base.OnNetworkDespawn(); + } +} +``` + +This will assure that when your in-scene placed `NetworkObject` is de-spawned it won't consume precious processing or rendering cycles and it will become "invisible" to all players (connected or that join the session later). Once the `NetworkObject` has been de-spawned and disabled, you might want to re-spawn it at some later time. To do this, you would want to set the server-side instance's `GameObject` back to being active and spawn it: + +```csharp +using UnityEngine; +using Unity.Netcode; + +public class MyInSceneNetworkObjectBehaviour : NetworkBehaviour +{ + public override void OnNetworkDespawn() + { + gameObject.SetActive(false); + base.OnNetworkDespawn(); + } + + public void Spawn(bool destroyWithScene) + { + if (IsServer && !IsSpawned) + { + gameObject.SetActive(true); + NetworkObject.Spawn(destroyWithScene); + } + } +} +``` + +:::info +You only need to enable the `NetworkObject` on the server-side to be able to re-spawn it. Netcode for GameObjects will only enable a disabled in-scene placed `NetworkObject` on the client-side if the server-side spawns it.
+_This **does not** apply to dynamically spawned `NetworkObjects`.
(see [Object Pooling](../../advanced-topics/object-pooling.md) for an example of recycling dynamically spawned `NetworkObject`s_) +::: + + +**_How can you start an in-scene placed `NetworkObject` as de-spawned when the scene is first loaded (i.e. its first spawn)?_** + +Since in-scene placed `NetworkObject`s are automatically spawned when their respective scene has finished loading during a network session, you might run into the scenario where you want it to start disabled until a certain condition has been met specific to your project. To do this, it only requires adding some additional code in the `OnNetworkSpawn` portion of your `NetworkBehaviour` component: + +```csharp +using UnityEngine; +using Unity.Netcode; + + public class MyInSceneNetworkObjectBehaviour : NetworkBehaviour + { + public bool StartDespawned; + + private bool m_HasStartedDespawned; + public override void OnNetworkSpawn() + { + if (IsServer && StartDespawned && !m_HasStartedDespawned) + { + m_HasStartedDespawned = true; + NetworkObject.Despawn(false); + } + base.OnNetworkSpawn(); + } + + public override void OnNetworkDespawn() + { + gameObject.SetActive(false); + base.OnNetworkDespawn(); + } + + public void Spawn(bool destroyWithScene) + { + if (IsServer && !IsSpawned) + { + gameObject.SetActive(true); + NetworkObject.Spawn(destroyWithScene); + } + } + } +``` + +You will notice the above example keeps track of whether the in-scene placed `NetworkObject` has started as being de-spawned (to avoid de-spawning after its first time being spawned), and it only allows the server to execute that block of code in the overridden `OnNetworkSpawn` method. The above `MyInSceneNetworkObjectBehaviour` example also declares a public `bool` property `StartDespawned` to provide control over this through the inspector view in the editor. + +**_How do I synchronize late joining clients when an in-scene placed `NetworkObject` has been de-spawned and destroyed?_** + +Referring back to the [Complex In-Scene NetworkObject Managers](inscene-placed-networkobjects#complex-in-scene-networkobjects), it is recommended to use dynamically spawned `NetworkObject`s if you are planning on destroying the object when it is de-spawned. However, if either de-spawning but not destroying or using the hybrid approach ([discussed earlier on this page](inscene-placed-networkobjects#a-hybrid-approach-example)) (dynamically spawned) don't appear to be options for your project's needs, then really there are only two other possible (but not recommended) alternatives: +- Have another in-scene placed `NetworkObject` track which in-scene placed `NetworkObject`s have been destroyed and upon a player late-joining (i.e. OnClientConnected) you would need to send the newly joined client the list of in-scene placed NetworkObjects that it should destroy. This adds an additional in-scene placed `NetworkObject` to your scene hierarchy and will consume memory keeping track of what was destroyed. +- Disable the visual and physics related components (in editor as a default) of the in-scene placed `NetworkObject`(s) in question and only enable them in OnNetworkSpawn. This does not delete/remove the in-scene placed `NetworkObject`(s) for the late joining client and can be tricky to implement without running into edge case scenario bugs. + +These two "alternatives" *are not recommended* but worth briefly exploring to better understand why we recommend using a [non-pooled hybrid approach](../object-spawning#dynamic-spawning-non-pooled) or just not destroying the in-scene placed `NetworkObject` when de-spawning it. _The time spent implementing and possibly debugging either of the two above not recommended approaches will far exceed the time spent implementing one of the recommended approaches._ + +### Parenting +In-scene placed `NetworkObject`s follow the same parenting rules as [dynamically spawned `NetworkObject`s](../../advanced-topics/networkobject-parenting.md) with only a few differences and recommendations: +- You can create complex nested `NetworkObject` hierarchies when they are in-scene placed. +- If you plan on using full scene-migration (i.e. LoadSceneMode.Single or "scene switching") then parenting an in-scene placed `NetworkObject` that stays parented during the scene migration is not recommended. + - Under this scenario, you would want to use a hybrid approach where the in-scene placed `NetworkObject` dynamically spawns the item to be picked up. +- If you plan on using a bootstrap scene usage pattern where you use additive scene loading and unloading with no full scene-migration(s), then it is "OK" to parent in-scene placed NetworkObjects. + +:::warning +Parenting in-scene placed `NetworkObject`s under `GameObject`s with no `NetworkObject` component will currently synchronize the child `NetworkObject` as if it is in world space on the client side. To work around this particular issue you should add a `NetworkTransform` to the child and enable local space synchronization. +::: \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/scene-events.md b/versioned_docs/version-1.0.0/basics/scenemanagement/scene-events.md new file mode 100644 index 000000000..cf00e21ab --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/scenemanagement/scene-events.md @@ -0,0 +1,281 @@ +--- +id: scene-events +title: Scene Events +sidebar_label: Scene Events +--- +:::caution +If you have not already read the [Using NetworkSceneManager](using-networkscenemanager.md) section, it is highly recommended to do so before proceeding. +::: + +## Scene Event Associations +We learned that the term "Scene Event" refers to all (associated) subsequent scene events that transpire over time after a server has initiated a load or unload Scene Event. For most cases this is true, however `SceneEventType.Synchronize` is a unique type of Scene Event that handles much more than loading or unloading a single scene. In order to better understand the associations between scene event types, it is better to first see them grouped together: + +### Loading: +**Initiating Scene Event**: `SceneEventType.Load`
+**Associated Scene Events**: +- `SceneEventType.LoadComplete`:
+signifies that a scene has been loaded locally. Clients send this event to the server. +- `SceneEventType.LoadEventCompleted`:
+signifies that the server and all clients have finished loading the scene and signifies that the Scene Event has completed. + +### Unloading: +**Initiating Scene Event**: `SceneEventType.Unload`
+**Associated Scene Events**: +- `SceneEventType.UnloadComplete`:
+signifies that a scene has been unloaded locally. Clients send this event to the server. +- `SceneEventType.UnloadEventCompleted`:
+signifies that the server and all clients have finished unloading the scene and signifies that the Scene Event has completed. + +### Synchronization: +This is automatically happens after a client is connected and approved.
+**Initiating Scene Event**: `SceneEventType.Synchronize`
+**Associated Scene Events**: +- `SceneEventType.SynchronizeComplete`:
+signifies that the client has finished loading all scenes and locally spawned all Netcode objects. The client sends this scene event message back to the server. This message also includes a list of `NetworkObject.NetworkObjectId`s for all of the `NetworkObject`s the client spawned. +- `SceneEventType.ReSynchronize`:
+signifies that the server determines the client needs to be "re-synchronized" because one or more `NetworkObject`s were despawned while the client was synchronizing. This message is sent to the client with a `NetworkObject.NetworkObjectId` list for all `NetworkObject`s the client needs to despawn. + + +## Client Synchronization Details +While client synchronization does fall partially outside of the scene management realm, it ended up making more sense to handle the initial client synchronization via the `NetworkSceneManager` since a large portion of the synchronization process involves loading scenes and synchronizing (in-scene placed and dynamically spawned) `NetworkObjects`. +- Scene synchronization is the first thing a client processes. + - The synchronization message includes a list of all scenes the server has loaded via the `NetworkSceneManager`. + - The client will load all of these scenes before proceeding to the `NetworkObject` synchronization. + - This approach was used in order to assure all `GameObject`, `NetworkObject`, and `NetworkBehaviour` dependencies are loaded and instantiated before a client attempts to locally spawn a `NetworkObject`. +- Synchronizing with all spawned `NetworkObjects`. + - Typically this involves both in-scene placed and dynamically spawned `NetworkObjects`. + - Learn more about [Object Spawning here](..\object-spawning.md). + - The `NetworkObject` list sent to the client is pre-ordered, by the server, in order to account for certain types of dependencies such as when using [Object Pooling](../../advanced-topics/object-pooling.md). + - Typically object pool managers are in-scene placed and need to be instantiated and spawned prior to spawning any of its pooled `NetworkObjects` on a client that is synchronizing. As such, `NetworkSceneManager` takes this into account to assure that all `NetworkObjects` spawned via the `NetworkPrefabHandler` will be instantiated and spawned after their object pool manager dependency has been instantiated and spawned locally on the client. + - You could have parented in-scene placed NetworkObjects (i.e. items that are picked up or consumed by players) + - `NetworkSceneManager` uses a combination of the `NetworkObject.GlobalObjectIdHash` and the instantiating scene's handle to uniquely identify in-scene placed `NetworkObject`s. + +:::info +With additively loaded scenes, you can run into situations where your objet pool manager, instantiated when the scene it is defined within is additively loaded by the server, is leaving its spawned `NetworkObject` instances within the [currently active scene](https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.GetActiveScene.html). While assuring that newly connected clients being synchronized have loaded all of the scenes first helps to avoid scene dependency issues, this alone does not resolve issue with the `NetworkObject` spawning order. The integrated scene management, included in Netcode for GameObjects, takes scenarios such as this into consideration. +::: + +### The Client Synchronization Process +:::info +The following information is not required information, but could be useful to better understand the integrated scene management synchronization process. +::: +
+Below is a diagram of the client connection approval and synchronization process: + +![image](images/scenemanagement_synchronization_overview.png) + +Starting with the "Player" in the top right portion of the above diagram, the client (Player) runs through the connection and approval process first which occurs within the `NetworkManager`. Once approved, the server-side `NetworkSceneManager` begins the client synchronization process by sending the `SceneEventType.Synchronize` Scene Event message to the approved client. The client then processes through the synchronization message. Once the client is finished processing the synchronize message, it responds to the server with a `SceneEventType.SynchronizeComplete` message. At this point the client is considered "synchronized". If the server determines any `NetworkObject` was despawned during the client-side synchronization message processing period, it will send a list of `NetworkObject` identifiers to the client via the `SceneEventType.ReSynchronize` message and the client will locally despawn the `NetworkObject`s. + +:::tip +When the server receives and processes the `SceneEventType.SynchronizeComplete` message, the client is considered connected (i.e. `NetworkManager.IsConnectedClient` is set to `true`) and both the `NetworkManager.OnClientConnected` delegate handler and the scene event notification for `SceneEventType.SynchronizeComplete` are invoked locally. This can be useful to know if your server sends any additional messages to the already connected clients about the newly connected client's status (i.e. a player's status needs to transition from joining to joined). +::: + +## Scene Event Notifications + +### When are Load or Unload SceneEvents Truly Complete? +There are two special scene event types that generate messages for the server and all connected clients: +`SceneEventType.LoadEventCompleted` and `SceneEventType.UnloadEventCompleted` + +:::note +Both of these server generated messages will create local notification events (on all clients and the server) that will contain the list of all client identifiers (ClientsThatCompleted) that have finished loading or unloading a scene. This can be useful to make sure all clients are synchronized with each other before allowing any netcode related game logic to begin. If a client disconnects or there is a time out, then any client that did not load or unload the scene will be included in a second list of client identifiers (ClientsThatTimedOut). +::: + +### Tracking Event Notifications (OnSceneEvent) +The following code provides an example of how to subscribe to and use `NetworkSceneManager.OnSceneEvent`. Since we want the server or host to receive all scene event notifications, we will want to subscribe immediately after we start the server or host. Each case contains additional comments about each scene event type. Starting the client is fairly straight forward and follows the same pattern by subscribing to `NetworkSceneManager.OnSceneEvent` if the client successfully started. + +```csharp +public bool StartMyServer(bool isHost) +{ + var success = false; + if (isHost) + { + success = NetworkManager.Singleton.StartHost(); + } + else + { + success = NetworkManager.Singleton.StartServer(); + } + + if (success) + { + NetworkManager.Singleton.SceneManager.OnSceneEvent += SceneManager_OnSceneEvent; + } + + return success; +} + +public bool StartMyClient() +{ + var success = NetworkManager.Singleton.StartClient(); + if (success) + { + NetworkManager.Singleton.SceneManager.OnSceneEvent += SceneManager_OnSceneEvent; + } + return success; +} + +private void SceneManager_OnSceneEvent(SceneEvent sceneEvent) +{ + // Both client and server receive these notifications + switch (sceneEvent.SceneEventType) + { + // Handle server to client Load Notifications + case SceneEventType.Load: + { + // This event provides you with the associated AsyncOperation + // AsyncOperation.progress can be used to determine scene loading progression + var asyncOperation = sceneEvent.AsyncOperation; + // Since the server "initiates" the event we can simply just check if we are the server here + if (IsServer) + { + // Handle server side load event related tasks here + } + else + { + // Handle client side load event related tasks here + } + break; + } + // Handle server to client unload notifications + case SceneEventType.Unload: + { + // You can use the same pattern above under SceneEventType.Load here + break; + } + // Handle client to server LoadComplete notifications + case SceneEventType.LoadComplete: + { + // This will let you know when a load is completed + // Server Side: receives this notification for both itself and all clients + if (IsServer) + { + if (sceneEvent.ClientId == NetworkManager.LocalClientId) + { + // Handle server side LoadComplete related tasks here + } + else + { + // Handle client LoadComplete **server-side** notifications here + } + } + else // Clients generate this notification locally + { + // Handle client side LoadComplete related tasks here + } + + // So you can use sceneEvent.ClientId to also track when clients are finished loading a scene + break; + } + // Handle Client to Server Unload Complete Notification(s) + case SceneEventType.UnloadComplete: + { + // This will let you know when an unload is completed + // You can follow the same pattern above as SceneEventType.LoadComplete here + + // Server Side: receives this notification for both itself and all clients + // Client Side: receives this notification for itself + + // So you can use sceneEvent.ClientId to also track when clients are finished unloading a scene + break; + } + // Handle Server to Client Load Complete (all clients finished loading notification) + case SceneEventType.LoadEventCompleted: + { + // This will let you know when all clients have finished loading a scene + // Received on both server and clients + foreach (var clientId in sceneEvent.ClientsThatCompleted) + { + // Example of parsing through the clients that completed list + if (IsServer) + { + // Handle any server-side tasks here + } + else + { + // Handle any client-side tasks here + } + } + break; + } + // Handle Server to Client unload Complete (all clients finished unloading notification) + case SceneEventType.UnloadEventCompleted: + { + // This will let you know when all clients have finished unloading a scene + // Received on both server and clients + foreach (var clientId in sceneEvent.ClientsThatCompleted) + { + // Example of parsing through the clients that completed list + if (IsServer) + { + // Handle any server-side tasks here + } + else + { + // Handle any client-side tasks here + } + } + break; + } + } +} +``` + +:::tip + This code could be applied to a component on your `GameObject` that has a `NetworkManager` component attached to it. Since the `GameObject`, with the `NetworkManager` component attached to it, is migrated into the DDOL (Dont Destroy on Load) scene, it will remain active for the duration of the network game session. + With that in mind, you could cache your scene events that occurred (for debug or reference purposes) and/or add your own events that other game objects could subscribe to. The general idea is that if you want to receive all notifications from the moment you start `NetworkManager` then you will want to subscribe to `NetworkSceneManager.OnSceneEvent` immediately after starting it. +::: + +Scene event notifications provide users with all NetworkSceneManager related scene events (and associated data) through a single event handler. The one exception would be scene loading or unloading progress which users can handle with a coroutine (upon receiving a Load or Unload event) and checking the `SceneEvent.AsyncOperation.progress` value over time. + +:::caution +You will want to assign the SceneEvent.AsyncOperation to a local property of the subscribing class and have a coroutine use that to determine the progress of the scene being loaded or unloaded. +::: + +You can stop the coroutine checking the progress upon receiving any of the following event notifications for the scene and event type in question: `LoadComplete`, `UnloadComplete` to handle local scene loading progress tracking. Otherwise, you should use the `LoadEventCompleted` or `UnloadEventCompleted` to assure that when your "scene loading progress" visual handler stops it will stop at ~roughly~ the same time as the rest of the connected clients. The server will always be slightly ahead of the clients since it notifies itself locally and then broadcasts this message to all connected clients. + +### SceneEvent Properties +The SceneEvent class contains values that may or may not be set depending upon the `SceneEventType`. Below are two quick lookup tables to determine which property is set for each `SceneEventType`. + +**Part-1**
+![image](images/SceneEventProperties-1.png)
+ +**Part-2**
+![image](images/SceneEventProperties-2.png)
+ +So, the big "take-away" from the above table is that you need to understand the `SceneEventType` context of the `SceneEvent` you are processing in order to know which properties are valid and you can use. As an example, it wouldn't make sense to provide the AsyncOperation for the following `SceneEventType`s: +- LoadComplete or LoadEventCompleted +- UnloadComplete or UnloadEventCompleted +- Synchronize or Resynchronize + +### SceneEventType Specific Notifications +There might be a time where you are not interested in all of the details for each scene event type that occurs. As it just so happens, `NetworkSceneManager` includes a single delegate handler for each `SceneEventType` that is only triggered for the associated `SceneEventType`. +You can explore the [NetworkSceneManager](http://localhost:3000/netcode/current/api/Unity.Netcode.NetworkSceneManager#events) for a full listing of the corresponding single `SceneEventType` events. +Some examples: +- NetworkSceneManager.OnLoad: Triggered when for `OnLoad` scene events. +- NetworkSceneManager.OnUnload: Triggered when for `OnUnload` scene events. +- NetworkSceneManager.OnSynchronize: Triggered when a client begins synchronizing. + +:::info +The general idea was to provide several ways to get scene event notifications. You might have a component that needs to know when a client is finished synchronizing on the client side but you don't want that component to receive notifications for loading or unloading related events. Under this scenario you would subscribe to the `NetworkManager.OnSynchronizeComplete` event on the client-side. +::: + +### When is it "OK" to Subscribe? +Possibly the more important aspect of scene event notifications is knowing when/where to subscribe. The recommended time to subscribe is immediately upon starting your `NetworkManager` as a client, server, or host. This will avoid problematic scenarios like trying to subscribe to the `SceneEventType.Synchronize` event within an overridden `NetworkBehaviour.OnNetworkSpawn` method of your `NetworkBehaviour` derived child class. The reason that is "problematic" is that the `NetworkObject` has to be spawned before you can subscribe to and receive events of type `SceneEventType.Synchronize` because that will occur before anything is spawned. Additionally, you would only receive notifications of any scenes loaded after the scene that contains the `NetworkObject` (or the object that spawns it) is loaded. + +An example of subscribing to `NetworkSceneManager.OnSynchronize` for a client: +```csharp + public bool ConnectPlayer() + { + var success = NetworkManager.Singleton.StartClient(); + if (success) + { + NetworkManager.Singleton.SceneManager.OnSynchronize += SceneManager_OnSynchronize; + } + return success; + } + + private void SceneManager_OnSynchronize(ulong clientId) + { + Debug.Log($"Client-Id ({clientId}) is synchronizing!"); + } +``` +_The general idea is that this would be something you would want to do immediately after you have started the server, host, or client._ diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/scene-management-overview.md b/versioned_docs/version-1.0.0/basics/scenemanagement/scene-management-overview.md new file mode 100644 index 000000000..735670624 --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/scenemanagement/scene-management-overview.md @@ -0,0 +1,23 @@ +--- +id: scene-management-overview +title: Scene Management Overview +sidebar_label: Scene Management Overview +--- +## Netcode Scene Management +Generally speaking, netcode aware scene management complexity can vary depending upon your project's needs and goals. Netcode for GameObjects (Netcode) provides you with two potential paths: + +### [Integrated Scene Management](using-networkscenemanager.md): +The Netcode for GameObjects scene management solution is enabled by default and provides you with a fully functional netcode scene management solution. +:::info +We highly recommend advanced developers new to Netcode for GameObjects become familiar with the integrated scene management solution before creating their own netcode scene management solution. +::: + +### [Custom Scene Management](custom-management.md): +If your project has needs that go beyond the scope of the Netcode integrated scene management solution, you can disable scene management in the editor through `NetworkManager`'s properties. + +:::caution +Writing your own scene management can be time consuming and complex. We highly recommend that only advanced users already familiar with Netcode for GameObjects take this path. +::: + + + diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/timing-considerations.md b/versioned_docs/version-1.0.0/basics/scenemanagement/timing-considerations.md new file mode 100644 index 000000000..bfbf6e6de --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/scenemanagement/timing-considerations.md @@ -0,0 +1,134 @@ +--- +id: timing-considerations +title: Timing Considerations +sidebar_label: Timing Considerations +--- + +:::caution +If you have not already read the [Using NetworkSceneManager](using-networkscenemanager.md) and/or [Scene Events](scene-events.md) sections, it is highly recommended to do so before proceeding. +::: + +## Introduction +Netcode for GameObjects handles many of the more complicated aspects of scene management. This section is tailored towards those who want to better understand the client-server communication sequence for scene events as they occur over time. +In each diagram, you will see two types of black arrows: +- Horizontal arrows: Denotes a progression to the next state and/or event. +- Diagonal arrows: Denotes a message being sent (server to client or vice versa). + - These arrows will have the name of the message being sent or the type of the scene event message being sent. + + +## Client Synchronization: +The below diagram, Client Synchronization Updates, steps you through the entire client synchronization process from starting the client all the way to the client being fully synchronized and connected. +![image](images/ClientSyncUpdates.png)
+Above, we can see that the client will first send a connection request to the server that will process the request, handle the approval process via ConnectionApprovalCallback (if connection approval is enabled), and if approved the server will: +- Send a connection approved message back to the client + - This only means the connection is approved, but the client is not yet synchronized. +- Start a `SceneEventType.Synchronize` scene event + - Build the synchronization message ("Synchronize NetworkObjects") that will contain all of the + information a client will need to properly synchronize with the current netcode game session. + - Send the scene event message to the client + +:::info +Throughout the integrated scene management sections, we have used the term "client synchronization period" to denote the time it takes a client to: +- Receive the synchronization message +- Process the synchronization message +- Send the `SceneEventType.SynchronizeComplete` message back to the server
+If you look at the server portion of the timeline in the above diagram, the "client synchronization period" is everything that occurs within the green bracketed section between "Synchronize NetworkObjects" and "Synchronization" on the server-side. On the client-side, it includes the time it takes to receive the `SceneEventType.Synchronize` message, "Handle (the) SceneEvent", and the time it takes for the server to receive the `SceneEventType.SynchronizeComplete` that is sent by the client once it has completed synchronizing. +::: + +Upon receiving the synchronization event message, the client processes it, and when finished the client sends the `SceneEventType.SynchronizeComplete` scene event message. The client-side will (within the same frame) invoke the following local `NetworkSceneManager` callbacks (if subscribed to): +- `OnSceneEvent` with the scene event type being set to `SceneEventType.SynchronizeComplete` +- `OnSynchronizeComplete` + +:::important +Take note that after the client finishes processing the synchronization event, the server lags, in regards to when callbacks are triggered, behind the client. Typically this client-server latency is half RTT, and so you should be aware that just because a client has notified locally that it has finished there is a small period of time (commonly in the 10's to 100's of milliseconds) where the server is still unaware of the client having finished synchronizing. +::: + +### Client-Side Synchronization Timeline +Now that we have covered the high-level synchronization process, we can dive a little deeper into what happens on the client side as it processes the synchronize message. The below sub-diagram, "Scene Event Synchronization Timeline", provides you with a more detailed view of how the client processes the synchronize message: +![image](images/SceneEventSynchronizationTimeline.png) +You can see that upon receiving the message, the client appears to be iterating over portions of the data included in the synchronize message. This is primarily the asynchronous scene loading phase of the client synchronization process. This means the more scenes loaded, the more a client will be required to load which means the Client Synchronization Period is directly proportional to the number of scene being loaded and the size of each scene being loaded. Once all scenes are loaded, the client will then locally spawn all `NetworkObject`s. As a final step, the client sends the list of all `NetworkObjectId`s it spawned as part of its `SceneEventType.SynchronizeComplete` scene event message so the server can determine if it needs to resynchronize the client with a list of any `NetworkObjects` that might have despawned during the Client Synchronization Period. + +## Loading Scenes + +### LoadSceneMode.Additive +Looking at the timeline diagram below, "Loading an Additive Scene", we can see that it includes a server, two clients, and that the server will always precede all clients when it comes to processing the scene loading event. The big-picture this diagram is conveying is that only when the server has finished loading the scene and spawning any in-scene placed `NetworkObject`s, instantiated by the newly loaded scene, will it send the scene loading event message to the clients. + +Another point of interest in the below diagram is how Client 1 receives the scene loading event, processes it, and then responds with a `SceneEventType.LoadComplete` scene event message before client 2. This delta between client 1 and client 2 represents the varying client-server latencies and further enforces the underlying concept behind the `SceneEventType.LoadEventCompleted` message. Once a server has received all `SceneEventType.LoadComplete` messages from the connected clients, it will then broadcast the `SceneEventType.LoadEventCompleted` message to all connected clients. At this point, we can consider the scene loading event (truly) complete and all connected clients are able to receive and process netcode messages. + +![image](images/LoadingAdditiveScene.png) + +:::caution +While a client can start sending the server messages (including NetworkVariable changes) upon local `SceneEventType.LoadComplete` event notifications, under more controlled testing environments where the network being used has very little to no latency (i.e. using loopback with multiple instances running on the same system or using your LAN), this approach will not expose latency related issues. Even though the timing might "work out" under controlled low latency conditions you could still run into edge case scenarios where if a client approaches or exceeds a 500ms RTT latency you could potentially run into issues. +::: + +:::tip +It is recommended that if your project's design requires that one or more `NetworkBehaviour`s immediately send any form of client to server message (i.e. changing a `NetworkVariable`, sending an RPC, sending a custom message, etc.) upon a client being locally notified of a `SceneEventType.LoadComplete` then you should test with artificial/simulated network conditions. +[Learn More About Simulating NetworkConditions Here](../../tutorials/testing/testing_with_artificial_conditions.md) +::: + +### LoadSceneMode.Single (a.k.a. Scene Switching) +Loading a scene in `LoadSceneMode.Single` mode via `NetworkSceneManager` is almost exactly like loading a scene additively. The primary difference between additively loading and single mode loading is that when loading a scene in single mode: +- all currently loaded scenes are unloaded +- all `NetworkObject`s that have `DestroyWithScene` set to `true` will be despawned and destroyed. + +How you load scenes is really up to your project/design requirements. + +- **Boot Strap Usage Pattern (Additive Loading Only)** + - Your only single mode loaded scene is the very first scene loaded (i.e. scene index of 0 in the scenes in build list within your project's build settings). + - Because your single mode loaded scene is automatically loaded, the server and all clients will already have this scene loaded + - To prevent clients from loading the bootstrap scene, you should use server-side [scene validation](using-networkscenemanager.md#scene-validation) + - All other scenes are loaded additively + - There is no real need to preserve any `NetworkObject` you want to persist when loading a scene additively. + - You need to keep track of the scenes loaded by `NetworkSceneManager` in order to be able to unload them. + +- **Scene Switch Usage Pattern (Single and Additive Loading)** + - Typically this usage pattern is desirable when your project's design separates "areas" by a primary scene that may have companion additively loaded scenes. + - Any scenes loaded by `NetworkSceneManager`, prior to scene switching, will be unloaded and any `NetworkObject` that has the `DestroyWithScene` set to `true` will be destroyed. + - If `DestroyWithScene` is set to `false` it will be "preserved" (_see the sub-diagram "Load New Scene Timeline" below_) + +![image](images/SwitchingToNewSceneLight.png) + +## Load New Scene Timeline (Sub-Diagram) +Both scene loading diagrams (Additive and Single) refer to the below sub-diagram that provides additional details of the scene loading process. +:::important +When looking at the below sub-diagram, both single and additive scene loading modes use close to the exact same flow with the exception that additively loaded scenes only flow through the four middle steps that are grouped together by the light red filled region highlighted by red dashed lines. When loading a scene additively, no other scenes are unloaded nor are any NetworkObjects moved into the DDoL temporarily. This setting, by default, is true for dynamically spawned `NetworkObject`s unless otherwise specified when using `NetworkObject.Spawn`, `NetworkObject.SpawnWithOwnership`, or `NetworkObject.SpawnAsPlayerObject`. In-scene placed `NetworkObject`'s, by default, will be destroyed with the scene that instantiated them. At any point, within a `NetworkBehaviour` you can change the `NetworkObject.DestroyWithScene` property. +::: + +![image](images/LoadNewSceneTimeline.png) +**Load New Scene Additively** +1. Starts loading the scene +2. During the scene loading process, in-scene placed `NetworkObject`s are instantiated and their `Awake` and then `Start` methods are invoked (in that order). +3. Scene loading completes. +4. All in-scene placed `NetworkObject`s are spawned. +:::caution +Step #3 above signifies that the `UnityEngine.SceneManagement.SceneManager` has finished loading the scene. If you subscribe to the `UnityEngine.SceneManagement.SceneManager.sceneLoaded` event, then step #3 would happen on the same frame that your subscribed handler is invoked. **Do not use this event** as a way to determine that the current Load SceneEvent has completed.
_Doing so will result in unexpected results that most commonly are associated with "yet-to-be-spawned" (locally) `NetworkObject`'s and/or their related `NetworkBehaviour` dependencies._
When using Netcode Integrated SceneManagement, it is recommended to use the `NetworkSceneManager` scene events to determine when the "netcode scene loading event" has completed locally or for all clients. +::: + +**Load New Scene Single (a.k.a "Scene Switching")** +1. All `NetworkObjects` that have their `DestroyWithScene` property set to `false` are migrated into the DDoL (temporarily). +2. All currently loaded scenes are unloaded. If you loaded any scenes additively, they will be automatically unloaded. +3. _(refer to the 4 steps outlined above)_ +4. After any newly instantiated `NetworkObject`s are spawned, the newly loaded scene is set as the currently active scene and then the `NetworkObject`s that were previously migrated into th DDoL (from step 1) are now migrated into the newly loaded scene. + +## Unloading a Scene +Primarily, this applies to unloading additively loaded scenes via th `NetworkSceneManager.UnloadScene` method. In order to unload a scene it must: +- have been additively loaded by `NetworkSceneManager` +- still be loaded + + +### Unloading an Additive Scene +If you look at the below diagram, "Unloading an Additive Scene", you will see a very similar flow as that of loading a scene. The server still initiates the `SceneEventType.Unload` scene event and will not send this message to clients until it has completed the `Unload` scene event locally. + +![image](images/UnloadingAdditiveScene.png)
+ +### Unloading Scenes Timeline: +Review over the below diagram and take note of the following things: +- **Server Side:** + - When a server starts the `SceneEventType.Unload` event, Unity will naturally being to destroy all `GameObjects` in the scene being unloaded. + - If a `GameObject` has a `NetworkObject` component attached to it and it is still considered spawned at the time the `GameObject` is destroyed, then the `NetworkObject` will be despawned prior to the `GameObject` being destroyed. + - This will cause a series of server-to-client despawn messages to be sent to all clients. +- **Client Side:** + - While a server is unloading a scene, the client could begin to receive a bunch of despawn messages for the `NetworkObject`s being destroyed on the server-side while the scene is being unloaded. + - By the time a client receives the `SceneEventType.Unload` scene event message, it very well could have no remaining `NetworkObject`s in the scene being unloaded. This will not impact the client-side scene unloading process, but it is useful to know that this will happen. + +![image](images/UnloadingSceneTimeline.png) \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/basics/scenemanagement/using-networkscenemanager.md b/versioned_docs/version-1.0.0/basics/scenemanagement/using-networkscenemanager.md new file mode 100644 index 000000000..f779ae014 --- /dev/null +++ b/versioned_docs/version-1.0.0/basics/scenemanagement/using-networkscenemanager.md @@ -0,0 +1,353 @@ +--- +id: using-networkscenemanager +title: Using NetworkSceneManager +sidebar_label: Using NetworkSceneManager +--- + +## Netcode for GameObjects Integrated Scene Management +### The `NetworkSceneManager` Provides You With: +- An existing framework that supports both the bootstrap and scene transitioning scene management usage patterns. +- Automated client synchronization that occurs when a client is connected and approved. + - All scenes loaded via `NetworkSceneManager` will be synchronized with clients during client synchronization. + - _Later in this document, you will learn more about using scene validation to control what scenes are synchronized on the client, server, or both side(s)_. + - All spawned Netcode objects are synchronized with clients during client synchronization. +- A comprehensive scene event notification system that provides you with a plethora of options. + - It provides scene loading, unloading, and client synchronization events ("Scene Events") that can be tracked on both the client and server. + - The server is notified of all scene events (including the clients') + - The server tracks each client's scene event progress (scene event progress tracking) + - Clients receive scene event messages from the server, trigger local notifications as it progresses through a Scene Event's, and send local notifications to the server. + - _clients **are not** aware of other clients' scene events_ + - In-Scene placed NetworkObject synchronization + +:::info +In-Scene placed `NetworkObject`s can be used in many ways and are treated uniquely from that of dynamically spawned `NetworkObject`s. An in-scene placed `NetworkObject` is a GameObject with a `NetworkObject` and typically at least one `NetworkBehaviour` component attached to a child of or the same `GameObject`. It is recommended to read through all integrated scene management materials (this document, [Scene Events](scene-events.md), and [Timing Considerations](timing-considerations.md)) before learning about more advanced [In-Scene (placed) NetworkObjects](inscene-placed-networkobjects.md) topics. +::: + +All of these scene management features (and more) are handled by the [`NetworkSceneManager`](https://docs-multiplayer.unity3d.com/netcode/current/api/Unity.Netcode.NetworkSceneManager). + +### Accessing `NetworkSceneManager` +The `NetworkSceneManager` lives within the `NetworkManager` and is instantiated when the `NetworkManager` is started. +`NetworkSceneManager` can be accessed in the following ways: +- From within a `NetworkBehaviour` derived component, you can access it by using `NetworkManager.SceneManager` +- From anything else that does not already have a reference to `NetworkManager`, you can access it using `NetworkManager.Singleton.SceneManager`. + +**Here are some genral rules about accessing and using `NetworkSceneManager`:** +- Do not try to access the `NetworkSceneManager` when the `NetworkManager` is shutdown (it won't exist). + - The `NetworkSceneManager` is only instantiated when a `NetworkManager` is started. +- As a server: + - Any scene you want synchronized with currently connected or late joining clients **must** be loaded via the `NetworkSceneManager` + - If you use the `UnityEngine.SceneManagement.SceneManager` during a netcode enabled game session, then those scenes will not be synchronized with currently connected or late joining clients. + - A "late joining client" is a client that joins a game session that has already been started and there are already one or more clients connected + - _All netcode aware objects spawned prior to a late joining client need to be synchronized with the late joining client._ + - The server does not require any clients to be currently connected before it starts loading scenes via the `NetworkSceneManager`. + - Any scene loaded via `NetworkSceneManager` will always default to being synchronized with clients. + - _Scene validation is explained later in this document._ + +:::warning +Do not try to access the `NetworkSceneManager` when the `NetworkManager` is shutdown. The `NetworkSceneManager` is only instantiated when a `NetworkManager` is started. _This same rule is true for all Netcode systems that reside within the `NetworkManager`_. +::: + +### Loading a Scene +In order to load a scene, there are four requirements: +1. The `NetworkManager` instance loading the scene must be a host or server. +2. The `NetworkSceneManager.Load` method is used to load the scene. +3. The scene being loaded must be registered with your project's [build settings scenes in build list](https://docs.unity3d.com/Manual/BuildSettings.html) +4. A Scene Event cannot already be in progress. + +#### Basic Scene Loading Example +Imagine that you have an in-scene placed NetworkObject, let's call it "ProjectSceneManager", that handles your project's scene management using the `NetworkSceneManager` and you wanted your server to load a scene when the ProjectSceneManager is spawned. +In its simplest form, it could look something like: +```csharp +public class ProjectSceneManager : NetworkBehaviour +{ + /// INFO: You could remove the #if UNITY_EDITOR code segment and make SceneName public, + /// but this code assures if the scene name changes you won't have to remember to + /// manually update it. +#if UNITY_EDITOR + public UnityEditor.SceneAsset SceneAsset; + private void OnValidate() + { + if (SceneAsset != null) + { + m_SceneName = SceneAsset.name; + } + } +#endif + [SerializeField] + private string m_SceneName; + + public override void OnNetworkSpawn() + { + if (IsServer && !string.IsNullOrEmpty(m_SceneName)) + { + var status = NetworkManager.SceneManager.LoadScene(m_SceneName, LoadSceneMode.Additive); + if (status != SceneEventProgressStatus.Started) + { + Debug.LogWarning($"Failed to load {m_SceneName} " + + $"with a {nameof(SceneEventProgressStatus)}: {status}"); + } + } + } +} +``` +In the above code snippet, we have a `NetworkBehaviour` derived class, `ProjectSceneManager`, that has a public `SceneAsset` property (editor only property) that specifies the scene to load. In the `OnNetworkSpawn` method, we make sure that only the server loads the scene and we compare the `SceneEventProgressStatus` returned by the `NetworkSceneManager.Load` method to the `SceneEventProgressStatus.Started` status. If we received any other status, then typically the name of the status provides you with a reasonable clue as to what the issue might be. + +### Scene Events and Scene Event Progress +The term "Scene Event" refers to all subsequent scene events that transpire over time after a server has started a `SceneEventType.Load` ("load") or `SceneEventType.Unload` ("unload") Scene Event. For example, a server might load a scene additively while clients are connected. The following high-level overview provides you with a glimpse into the events that transpire during a load Scene Event(_it assumes both the server and clients have registered for scene event notifications_): +- Server starts a `SceneEventType.Load` event + - The server begins asynchronously loading the scene additively + - The server will receive a local notification that the scene load event has started + - Once the scene is loaded, the server spawns any in-scene placed `NetworkObjects` locally + - After spawning, the server will send the `SceneEventType.Load` message to all connected clients along with information about the newly instantiated and spawned `NetworkObject`s. + - The server will receive a local `SceneEventType.LoadComplete` event + - This only means the server is done loading and spawning `NetworkObjects` instantiated by the scene being loaded. +- The clients receive the scene event message for the `SceneEventType.Load` event and begin processing it. + - Upon starting the scene event, the clients will receive a local notification for the SceneEventType.Load event. + - As each client finishes loading the scene, they will generate a `SceneEventType.LoadComplete` event + - The client sends this event message to the server. + - The client is notified locally of this scene event. + - This notification only means that it has finished loading and synchronizing the scene, but does not mean all other clients have! +- The server receives the `SceneEventType.LoadComplete` events from the clients + - When all `SceneEventType.LoadComplete` events have been received, the server will generate a `SceneEventType.LoadEventCompleted` notification + - This notification is triggered locally on the server + - The server broadcasts this scene event to the clients +- Each client receives the `SceneEventType.LoadEventCompleted` event + - At this point all clients have completed the `SceneEventType.Load` event and are synchronized with all newly instantiated and spawned `NetworkObjects`. + +The purpose behind the above outline is to demonstrate that a Scene Event can lead to other scene event types being generated and that the entire sequence of events that transpire occur over a longer period of time than if you were loading a scene in a single player game. + +:::tip +When you receive the `SceneEventType.LoadEvenetCompleted` or the `SceneEventType.SynchronizeComplete` you know that the server or clients can start invoking netcode specific code (i.e. sending Rpcs, updating `NetworkVariable`s, etc.). Alternately, `NetworkManager.OnClientConnectedCallback` is triggered when a client finishes synchronizing and could be used in a similar fashion. _However, that only works for the initial client synchronization and not for scene loading or unloading events._ +::: + +:::warning +Because the `NetworkSceneManager` still has additional tasks to complete once a scene is loaded, it is not recommended to use `UnityEngine.SceneManagement.SceneManager.sceneLoaded` or `UnityEngine.SceneManagement.SceneManager.sceneUnloaded` as a way to know when a scene event has completed. These two callbacks will occur before `NetworkSceneManager` has finished the final processing after a scene is loaded or unloaded and you could run into timing related issues. If you are using the netcode integrated scene management, then it is highly recommended to subscribe to the `NetworkSceneManager`'s scene event notifications. +::: + +#### Scene Event Notifications +You can be notified of scene events by registering in one of two ways: +1. Receive all scene event notification types: `NetworkSceneManager.OnSceneEvent` +2. Receive only a specific scene event notification type: [`NetworkSceneManager`](https://docs-multiplayer.unity3d.com/netcode/current/api/Unity.Netcode.NetworkSceneManager#events) has one for each [`SceneEventType`](https://docs-multiplayer.unity3d.com/netcode/current/api/Unity.Netcode.SceneEventType)
+:::info +Receiving (via subscribing to the associated event callback) only specific scene event notification types does not change how a server or client receives and processes notifications. +::: + +**Receiving All Scene Event Notifications** +Typically, this is used on the server side in order to receive notifications for every scene event notification type for both the server and clients. You can receive all scene event type notifications by subscribing to the `NetworkSceneManager.OnSceneEvent` callback handler. + +**Receiving A Specific Scene Event Notification** +Typically, this is used with clients or components that might only need to be notified of a specific scene event type. There are 9 scene event types and each one has a corresponding "single event type" callback handler in `NetworkSceneManager`. + +**As an example:** +You might want to register for the `SceneEventType.LoadEventCompleted` scene event type to know, from a client perspective, that the server and all other clients have finished loading a scene. This notification lets you know when you can start performing other netcode related actions on the newly loaded and spawned `NetworkObject`s. + +#### Scene Event Progress Status +As we discussed in the earlier code example, it is important to check the status returned by `NetworkSceneManager.Load` to make sure your scene loading event has started. The following is a list of all [SceneEventProgressStatus](../../api/Unity.Netcode.SceneEventProgressStatus.md) `enum` values with some additional helpful information: +- Started + - The scene event has started (success) +- SceneNotLoaded + - This is returned when you attempt to unload a scene that is not loaded (or no longer is loaded) +- SceneEventInProgress + - This is returned if you attempt to start a new scene event (loading or unloading) while one is still in progress +- InvalidSceneName + - This can happen for one of the two reasons: + - The scene name is not spelled correctly or the name of the scene changed + - The scene name is not in your project's scenes in build list +- SceneFailedVerification + - This is returned if you fail scene verification on the server side (more about scene verification later) +- InternalNetcodeError + - Currently, this error will only happen if the scene you are trying to unload was never loaded by the `NetworkSceneManager`. + +### Unloading a Scene +Now that we understand the loading process, scene events, and can load a scene additively, the next step is understanding the integrated scene management scene unloading process. In order to unload a scene, here are the requirements: +1. The `NetworkManager` instance unloading the scene should have already been started in host or server mode and already loaded least one scene additively.
+ 1.1 Only additively loaded scenes can be unloaded. + 1.2 You cannot unload the currently active scene (see info dialog below) +2. The `NetworkSceneManager.Unload` method is used to unload the scene +3. A Scene Event cannot already be in progress + +:::info +Unloading the currently active scene, in Netcode, is commonly referred to as "scene switching" or loading another scene in `LoadSceneMode.Single` mode. This will unload all additively loaded scenes and upon the new scene being loaded in `LoadSceneMode.Single` mode it is set as the active scene and the previous active scene is unloaded. +::: + +#### Basic Scene Unloading Example +Below we are taking the previous scene loading example, the `ProjectSceneManager` class, and modifying it to handle unloading. This includes keeping a reference to the `SceneEvent.Scene` locally in our class because `NetworkSceneManager.Unload` requires the `Scene` to be unloaded. + +**Below is an example of how to:** +- Subscribe the server to `NetworkSceneManager.OnSceneEvent` notifications. +- Save a reference to the `Scene` that was loaded. +- Unload a scene loaded additively by `NetworkSceneManager`. +- Detect the scene event types associated with loading and unloading. + +```csharp +public class ProjectSceneManager : NetworkBehaviour +{ + /// INFO: You could remove the #if UNITY_EDITOR code segment and make SceneName public, + /// but this code assures if the scene name changes you won't have to remember to + /// manually update it. +#if UNITY_EDITOR + public UnityEditor.SceneAsset SceneAsset; + private void OnValidate() + { + if (SceneAsset != null) + { + m_SceneName = SceneAsset.name; + } + } +#endif + [SerializeField] + private string m_SceneName; + private Scene m_LoadedScene; + + public bool SceneIsLoaded + { + get + { + if (m_LoadedScene.IsValid() && m_LoadedScene.isLoaded) + { + return true; + } + return false; + } + } + + public override void OnNetworkSpawn() + { + if (IsServer && !string.IsNullOrEmpty(m_SceneName)) + { + NetworkManager.SceneManager.OnSceneEvent += SceneManager_OnSceneEvent; + var status = NetworkManager.SceneManager.LoadScene(m_SceneName, LoadSceneMode.Additive); + CheckStatus(status); + } + + base.OnNetworkSpawn(); + } + + private void CheckStatus(SceneEventProgressStatus status, bool isLoading = true) + { + var sceneEventAction = isLoading ? "load" : "unload"; + if (status != SceneEventProgressStatus.Started) + { + Debug.LogWarning($"Failed to {sceneEventAction} {m_SceneName} with" + + $" a {nameof(SceneEventProgressStatus)}: {status}"); + } + } + + /// + /// Handles processing notifications when subscribed to OnSceneEvent + /// + /// class that contains information about the scene event + private void SceneManager_OnSceneEvent(SceneEvent sceneEvent) + { + var clientOrServer = sceneEvent.ClientId == NetworkManager.ServerClientId ? "server" : "client"; + switch (sceneEvent.SceneEventType) + { + case SceneEventType.LoadComplete: + { + // We want to handle this for only the server-side + if (sceneEvent.ClientId == NetworkManager.ServerClientId) + { + // *** IMPORTANT *** + // Keep track of the loaded scene, you need this to unload it + m_LoadedScene = sceneEvent.Scene; + } + Debug.Log($"Loaded the {sceneEvent.SceneName} scene on " + + $"{clientOrServer}-({sceneEvent.ClientId})."); + break; + } + case SceneEventType.UnloadComplete: + { + Debug.Log($"Unloaded the {sceneEvent.SceneName} scene on " + + $"{clientOrServer}-({sceneEvent.ClientId})."); + break; + } + case SceneEventType.LoadEventCompleted: + case SceneEventType.UnloadEventCompleted: + { + var loadUnload = sceneEvent.SceneEventType == SceneEventType.LoadEventCompleted ? "Load" : "Unload"; + Debug.Log($"{loadUnload} event completed for the following client " + + $"identifiers:({sceneEvent.ClientsThatCompleted})"); + if (sceneEvent.ClientsThatTimedOut.Count > 0) + { + Debug.LogWarning($"{loadUnload} event timed out for the following client " + + $"identifiers:({sceneEvent.ClientsThatTimedOut})"); + } + break; + } + } + } + + public void UnloadScene() + { + // Assure only the server calls this when the NetworkObject is + // spawned and the scene is loaded. + if (!IsServer || !IsSpawned || !m_LoadedScene.IsValid() || !m_LoadedScene.isLoaded) + { + return; + } + + // Unload the scene + var status = NetworkManager.SceneManager.UnloadScene(m_LoadedScene); + CheckStatus(status, false); + } +} +``` +Really, if you take away the debug logging code the major differences are: +- We store the Scene loaded when the server receives its local `SceneEventType.SceneEventType.LoadComplete` notification +- When the `ProjectSceneManager.UnloadScene` method is invoked (_assuming this occurs outside of this class_) the `ProjectSceneManager.m_LoadedScene` is checked to make sure it is a valid scene and that it is indeed loaded before we invoke the `NetworkSceneManager.Unload` method. + +### Scene Validation +Sometimes you might need to prevent the server or client from loading a scene under certain conditions. Here are a few examples of when you might do this: +- One or more game states determine if a scene is loaded additively + - Typically, this is done on the server-side. +- The scene is already pre-loaded on the client + - Typically, this is done on the client-side. +- Security purposes + - As we mentioned earlier, `NetworkSceneManager` automatically considers all scenes in the build settings scenes in build list valid scenes to be loaded. You might use scene validation to prevent certain scenes from being loaded that could cause some form of security and/or game play issue. + - It is common to do this on either the server or client side depending upon your requirements/needs. + +**Usage Example** +The below example builds upon the previous example's code, and adds some psuedo-code for server-side scene validation: +```csharp + private bool ServerSideSceneValidation(int sceneIndex, string sceneName, LoadSceneMode loadSceneMode) + { + // Comparing against the name or sceneIndex + if (sceneName == "SomeSceneName" || sceneIndex == 3) + { + return false; + } + + // Don't allow single mode scene loading (i.e. bootstrap usage patterns might implement this) + if (loadSceneMode == LoadSceneMode.Single) + { + return false; + } + + return true; + } + + public override void OnNetworkSpawn() + { + if (IsServer && !string.IsNullOrEmpty(m_SceneName)) + { + NetworkManager.SceneManager.VerifySceneBeforeLoading = ServerSideSceneValidation; + NetworkManager.SceneManager.OnSceneEvent += SceneManager_OnSceneEvent; + var status = NetworkManager.SceneManager.LoadScene(m_SceneName, LoadSceneMode.Additive); + CheckStatus(status); + } + + base.OnNetworkSpawn(); + } +``` +The callback is the first thing invoked on the server-side when invoking the `NetworkSceneManager.Load` method. If the scene validation fails, `NetworkSceneManager.Load` will return `SceneEventProgressStatus.SceneFailedVerification` and the scene event is cancelled. + +:::caution +**Client-Side Scene Validation**
+This is where you need to be cautious with scene validation, because any scene that you do not validate on the client side should not contain Netcode objects that are considered required dependencies for a connecting client to properly synchronize with the current netcode (game) session state. +::: + +### What Next? +We have covered how to access the `NetworkSceneManager`, how to load and unload a scene, provided a basic overview on scene events and notifications, and even briefly discussed in-scene placed `NetworkObject`s. You now have the fundamental building-blocks one needs to learn more advanced integrated scene management topics. +_We recommend proceeding to the next integrated scene management topic, "Scene Events", in the link below._ + + diff --git a/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorOwnerAuthTiming.png b/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorOwnerAuthTiming.png new file mode 100644 index 000000000..6bcb7b409 Binary files /dev/null and b/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorOwnerAuthTiming.png differ diff --git a/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorServerAuthTiming.png b/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorServerAuthTiming.png new file mode 100644 index 000000000..e61e98b31 Binary files /dev/null and b/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorServerAuthTiming.png differ diff --git a/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorUsage-1.png b/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorUsage-1.png new file mode 100644 index 000000000..a6eb133d3 Binary files /dev/null and b/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorUsage-1.png differ diff --git a/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorUsage-2.png b/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorUsage-2.png new file mode 100644 index 000000000..215a9228e Binary files /dev/null and b/versioned_docs/version-1.0.0/components/Images/NetworkAnimatorUsage-2.png differ diff --git a/versioned_docs/version-1.0.0/components/networkanimator.md b/versioned_docs/version-1.0.0/components/networkanimator.md new file mode 100644 index 000000000..0dc430e6b --- /dev/null +++ b/versioned_docs/version-1.0.0/components/networkanimator.md @@ -0,0 +1,104 @@ +--- +id: networkanimator +title: NetworkAnimator +--- +## Introduction +The `NetworkAnimator` component provides you with a fundamental example of how to synchronize animations during a network session. Animation states are synchronized with players joining an existing network session and any client already connected prior to the animation state changing. +- Players joining an existing network session will be synchronized with: + - All of the `Animator`'s current properties and states. + - _With exception to `Animator` trigger properties. These are only synchronized with already connected clients._ + - Any in progress transition +- Players already connected will be synchronized with changes to `Animator`: + - States + - Transitions + - Properties + - `NetworkAnimator` will only synchronize properties that have changed since the previous frame property values. + - Since triggers are similar to an "event", when an `Animator` property is set to `true` it will always be synchronized. + +`NetworkAnimator` can operate in two authoritative modes: +- Server Authoritative (default): Server initiates animation state changes. + - Owner's can still invoke `NetworkAnimator.SetTrigger`. +- Client Authoritative: Client owners initiate animation state changes. + +### Animator Trigger Property +The `Animator` trigger property type ("trigger") is basically nothing more than a boolean value that, when set to `true`, will get automatically reset back to `false` after the `Animator` component has processed the trigger. In most cases, a trigger is used to initiate a transition between `Animator` layer states. In this sense, one can think of a trigger as a way to signal the "beginning of an event". Because trigger properties have this unique behavior, they **require** that you to set the trigger value via the `NetworkAnimator.SetTrigger` method. +:::caution +If you set a trigger property using `Animator.SetTrigger` then this will not be synchronized with non-owner clients. +::: + +### Server Authoritative Mode +The default setting for `NetworkAnimator` is server authoritative mode. When operating in server authoritative mode, any animation state changes that are set (i.e. triggers) or detected (i.e. change in layer, state, or any `Animator` properties excluding triggers) on the server side will be synchronized with all clients. Because the server initiates any synchronization of changes to an `Animator`'s state, a client that is the owner of the `NetworkObject` associated with the `NetworkAnimator` could lag by roughly the full round trip time (RTT). Below is a timing diagram to demonstrate this: +![ServerAuthMode](Images/NetworkAnimatorServerAuthTiming.png) +In the above diagram, a client might be sending the server an RPC to notify the server that the player is performing some kind of action that could change the player's animations (including setting a trigger). Under this scenario, the client sends an RPC to the server (half RTT), the server processes the RPC, the associated `Animator` state changes are detected by the `NetworkAnimator` (server-side), and then all clients (including the owner client) are synchronized with the changed. + +**Server authoritative model benefits:** +- If running a plain server (i.e. non-host), this model helps reduce the synchronization latency between all client animations. + +**Server authoritative model drawbacks:** +- Hosts will always be "slightly ahead" of all other clients which may or may not be an issue for your project. +- Client owners will experience a latency between performing an action (i.e. moving, picking something up, anything that causes an `Animator` state change). + +### Owner Authoritative Mode +In some cases, your project's design (or personal preference) might require that owners are immediately updated to any `Animator` state changes. The most typical reason would be to provide the local player with instantaneous visual (animation) feedback. To create an owner authoritative `NetworkAnimator` you need to create a new class that is derived from `NetworkAnimator`, override the `NetworkAnimator.OnIsServerAuthoritative` method, and within the overridden `OnIsServerAuthoritative` method you should return false like in the example provided below: +```csharp + public class OwnerNetworkAnimator : NetworkAnimator + { + protected override bool OnIsServerAuthoritative() + { + return false; + } + } +``` +Looking at the timing for an owner authoritative `NetworkAnimator`, in the diagram below, we can see that while the owner client gets "immediate visual animation response" the non-owner clients end up being roughly one full RTT behind the owner client and a host would be half RTT behind the owner client. +![ServerAuthMode](Images/NetworkAnimatorOwnerAuthTiming.png) +In the above diagram, it shows that the owner client has an `Animator` state change that is detected by the `NetworkAnimator` (i.e. `OwnerNetworkAnimator`) which automatically synchronizes the server with the changed state. The server applies the change(s) locally and then broadcasts this state change to all non-owner clients. + +**Owner authoritative model benefits:** +- The owner is provided instant visual feedback of `Animator` state changes, which does provide a smoother experience for the local player. + +**Owner authoritative model drawbacks:** +- Non-owner clients lag behind the owner client's animation by roughly one full RTT. +- A host lags behind the owner client's animation by roughly half RTT. + +:::caution +The same rule for setting trigger properties still applies to owner clients. As such, if you want to programmatically set a trigger then you still need to use `NetworkAnimator.SetTrigger`. +::: + +## Using NetworkAnimator +Using `NetworkAnimator` is a pretty straight forward approach with the only subtle difference being whether you are using a server or owner authoritative model. + +:::important +`NetworkAnimator` is one of several possible ways to synchronize animations during a network session. Netcode for GameObjects provides you with the building blocks (RPCs, NetworkVariables, Custom Messages, etc.) needed to create a completely unique animation synchronization system that has a completely different and potentially more optimized approach. `NetworkAnimator` is a straight forward approach provided for users already familiar with the `Animator` component and, depending upon your project's design requirements, might be all that you need. +::: + +### Server Authoritative +If you decide you want to use the server authoritative model, then you can simply add a `NetworkAnimator` component to either the same `GameObject` that has the `NetworkObject` component attached to it or any child `GameObject`. In the below screenshot, you can see a network prefab that houses two authoritative models. The `NetworkAnimatorCube-Server` `GameObject` has an `Animator` component, an `AnimatedCubeController` component (used for manual testing), and the `NetworkAnimator` component that has a reference to the `Animator` component. +![Usage-1](Images/NetworkAnimatorUsage-1.png) + +### Owner Authoritative +If you decide you want to use the owner authoritative model, then (for example purposes) you would use your derived `OwnerNetworkAnimator` component as opposed to the default `NetworkAnimator` component like in the screenshot below: +![Usage-1](Images/NetworkAnimatorUsage-2.png) + +:::info +While it isn't advised to have different `NetworkAnimator` authoritative models "under the same root network prefab `GameObject`", you can have multiple children that each have their own `Animator` and `NetworkAnimator` all housed under a single `NetworkObject` and all use the same authoritative model. However, you should always consider the balance between performance (cpu and/or bandwidth consumption) and convenience/modularity. +::: + +### Changing Animator Properties +For all `Animator` properties (with the exception of triggers), you can set them directly via the `Animator` class. As an example, you might use the player's normalized velocity as a way to control the walking or running animation of a player. You might have an an `Animator` `float` property called "AppliedMotion" that you would set on the authoritative instance (server or owner) like such: +```csharp +public void ApplyMotion(Vector3 playerVelocity) +{ + m_Animator.SetFloat("AppliedMotion", playerVelocity.normalized.magnitude); +} +``` + +For triggers you always want to use `NetworkAnimator`. One example might be that you use a trigger, let's call it "IsJumping", to start a blended transition between the player's walking/running animation and the jumping animation: +```csharp +public void SetPlayerJumping(bool isJumping) +{ + m_NetworkAnimator.SetTrigger("IsJumping"); +} +``` + + + diff --git a/versioned_docs/version-1.0.0/components/networkmanager.md b/versioned_docs/version-1.0.0/components/networkmanager.md new file mode 100644 index 000000000..0c8355d36 --- /dev/null +++ b/versioned_docs/version-1.0.0/components/networkmanager.md @@ -0,0 +1,238 @@ +--- +id: networkmanager +title: NetworkManager +--- + +The `NetworkManager` is a required **Netcode for GameObjects (Netcode)** component that contains all of your project's netcode related settings. Think of it as the "central netcode hub" for your netcode enabled project. + +### `NetworkManager` Inspector Properties + +- **LogLevel**: Sets the network logging level +- **PlayerPrefab**: When a prefab is assigned, the prefab will be instantiated as the player object and assigned to the newly connected and authorized client. +- **NetworkPrefabs**: Where you register your network prefabs. You can also create a single network prefab override per registered network prefab here. +- **Protocol Version**: Set this value to help distinguish between builds when the most current build has new assets that could cause issues with older builds connecting. +- **Network Transport**: Where your network specific settings and transport type is set. This field accepts any INetworkTransport implementation. However, unless you have unique transport specific needs UnityTransport is the recommended transport to use with Netcode for GameObjects. +- **Tick Rate**: This value controls the network tick update rate. +- **Ensure Network Variable Length Safety**: (Increases cpu processing and bandwidth) When this property is checked, Netcode for GameObjects will prevent user code from writing past the boundaries of a NetworkVariable. +- **Connection Approval**: This enables [connection approval](../basics/connection-approval.md) when this is checked and the `NetworkManager.ConnectionApprovalCallback` is assigned. +- **Client Connection Buffer Timeout**: This value sets the amount of time that has to pass for a connecting client to complete the connection approval process. If the time specified is exceeded the connecting client will be disconnected. +- **Force Same Prefabs**: When checked it will always verify that connecting clients have the same registered network prefabs as the server. When not checked, Netcode for GameObjects will ignore any differences. +- **Recycle Network Ids**: When checked this will re-use previously assigned `NetworkObject.NetworkObjectIds` after the specified period of time. +- **Network Id Recycle Delay**: The time it takes for a previously assigned but currently unassigned identifier to be available for use. +- **Enable Scene Management**: When checked Netcode for GameObjects will handle scene management and client synchronization for you. When not checked, users will have to create their own scene management scripts and handle client synchronization. +- **Load Scene Time Out**: When Enable Scene Management is checked, this specifies the period of time the `NetworkSceneManager` will wait while a scene is being loaded asynchronously before `NetworkSceneManager` considers the load/unload scene event to have failed/timed out. + +### `NetworkManager` Sub-Systems +`NetworkManager` is also where you can find references to other Netcode related management systems:
+ +:::caution +All `NetworkManager` sub-systems are instantiated once the `NetworkManager` is started (i.e. `NetworkManager.IsListening == true`). A good general "rule of thumb" is to not attempt to access the below sub-systems prior to starting the `NetworkManager`, otherwise they will not yet be initialized. +::: + +- [NetworkManager.PrefabHandler](../advanced-topics/object-pooling.md): This provides access to the NetworkPrefabHandler that is used for NetworkObject pools and to have more control overriding network prefabs. +- [NetworkManager.SceneManager](../basics/scenemanagement/using-networkscenemanager.md): When scene management is enabled, this is used to load and unload scenes, register for scene events, and other scene management related actions. +- [NetworkManager.SpawnManager](../basics/object-spawning.md): This handles NetworkObject spawn related functionality. +- [NetworkManager.NetworkTimeSystem](../advanced-topics/networktime-ticks.md): a synchronized time that can be used to handle issues with latency between a client and the server. +- [NetworkManager.NetworkTickSystem](../advanced-topics/networktime-ticks#network-ticks.md): Use this to adjust the frequency of when NetworkVariables are updated. +- [NetworkManager.CustomMessagingManager](../advanced-topics/message-system/custom-messages.md): Use this system to create and send custom messages. + +## Starting a Server, Host, or Client + +In order to perform any netcode related action that involves sending messages, you must first have a server started and listening for connections with at least one client (_a server can send RPCs to itself when running as a host_) that is connected. In order to accomplish this, you must first start your `NetworkManager` as a server, host, or client. There are three `NetworkManager` methods you can invoke to accomplish this: + +```csharp +NetworkManager.Singleton.StartServer(); // Starts the NetworkManager as just a server (i.e. no local client). +NetworkManager.Singleton.StartHost(); // Starts the NetworkManager as both a server and a client (i.e. has local client) +NetworkManager.Singleton.StartClient(); // Starts the NetworkManager as just a client. +``` + +:::warning +Do not start a NetworkManager within a NetworkBehaviour's Awake method as this can lead to undesirable results depending upon your project's settings! +::: + +:::note + When starting a Server or joining an already started session as client, the `NetworkManager` can spawn a "Player Object" belonging to the client. + + For more information about player prefabs see: + - [NetworkObject Player Prefab Documentation](../basics/networkobject.md#player-objects) + - [Connection Approval](../basics/connection-approval) +::: + +## Connecting + +When Starting a Client, the `NetworkManager` uses the IP and the Port provided in your `Transport` component for connecting. While you can set the IP address in the editor, many times you might want to be able to set the IP address and port during runtime. + +The below examples use [Unity Transport](../../../transport/current/about) to demonstrate a few ways you can gain access to the `UnityTransport` component via the `NetworkManager.Singleton` in order to configure your project's network settings programmatically: + +If you are only setting the IP address and port number, then you can use the `UnityTransport.SetConnectionData` method: +```csharp +NetworkManager.Singleton.GetComponent().SetConnectionData( + "127.0.0.1", // The IP address is a string + (ushort)12345 // The port number is an unsigned short +); +``` + +If you are using the same code block to configure both your server and your client and you want to configure your server to listen to all IP addresses assigned to it, then you can also pass a 'listen address' of "0.0.0.0" to the `SetConnectionData` method, like so: +```csharp +NetworkManager.Singleton.GetComponent().SetConnectionData( + "127.0.0.1", // The IP address is a string + (ushort)12345, // The port number is an unsigned short + "0.0.0.0" // The server listen address is a string. +); +``` + +:::note +Using an IP address of 0.0.0.0 for the server listen address will make a server or host listen on all IP addresses assigned to the local system. This can be particularly helpful if you are testing a client instance on the same system as well as one or more client instances connecting from other systems on your local area network. Another scenario is while developing and debugging you might sometimes test local client instances on the same system and sometimes test client instances running on external systems. +::: + +It is possible to access the current connection data at runtime, via `NetworkManager.Singleton.GetComponent().ConnectionData`. This will return a [`ConnectionAddressData` **struct**](https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/blob/11922a0bc100a1615c541aa7298c47d253b74937/com.unity.netcode.gameobjects/Runtime/Transports/UTP/UnityTransport.cs#L239-L286), holding this info. You are strongly advised to use the `SetConnectionData` method to update this info. + +If you are using Unity Relay to handle connections, however, **do not use `SetConnectionData`**. The host should call [`SetHostRelayData`](https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/blob/11922a0bc100a1615c541aa7298c47d253b74937/com.unity.netcode.gameobjects/Runtime/Transports/UTP/UnityTransport.cs#L575), and clients should call [`SetClientRelayData`](https://github.com/Unity-Technologies/com.unity.netcode.gameobjects/blob/11922a0bc100a1615c541aa7298c47d253b74937/com.unity.netcode.gameobjects/Runtime/Transports/UTP/UnityTransport.cs#L588). Attempting to join a **Relay**-hosted game via entering IP/port number (via `SetConnectionData`) **will not work**. + + +[More information about Netcode for GameObjects Transports](../advanced-topics/transports.md) + +## Disconnecting and Shutting Down + +Disconnecting is rather simple, but you cannot use/access any subsystems (i.e. `NetworkSceneManager`) once the `NetworkManager` is stopped because they will no longer be available. For client, host, or server modes, you only need to call the `NetworkManager.Shutdown` method as it will disconnect while shutting down. + +:::info +When no network session is active and the `NetworkManager` has been shutdown, you will need to use `UnityEngine.SceneManagement` to load any non-network session related scene. +::: + +```csharp +public void Disconnect() +{ + NetworkManager.Singleton.Shutdown(); + // At this point we must use the UnityEngine's SceneManager to switch back to the MainMenu + UnityEngine.SceneManagement.SceneManager.LoadScene("MainMenu"); +} +``` + +## Disconnecting Clients (Server Only) + +At times you might need to disconnect a client for various reasons without shutting down the server. To do this, you can call the `NetworkManager.DisconnectClient` method while passing the identifier of the client you wish to disconnect as the only parameter. The client identifier can be found within: +- The `NetworkManager.ConnectedClients` dictionary that uses the client identifier as a key and the value as the [`NetworkClient`](../api/Unity.Netcode.NetworkClient.md). +- As a read only list of `NetworkClients` via the `NetworkManager.ConnectedClientsList`. +- A full list of all connected client identifiers can be accessed via `NetworkManager.ConnectedClientsIds`. +- The client identifier is passed as a parameter to all subscribers of the `NetworkManager.OnClientConnected` event. +- The player's `NetworkObject` has the `NetworkObject.OwnerClientId` property. + +:::tip +One way to get a player's primary `NetworkObject` is via `NetworkClient.PlayerObject`. +::: + +```csharp +void DisconnectPlayer(NetworkObject player) +{ + // Note: If a client invokes this method, it will throw an exception. + NetworkManager.DisconnectClient(player.OwnerClientId); +} +``` + +### Client Disconnection Notifications + +Both the client and the server can subscribe to the `NetworkManger.OnClientDisconnectCallback` event in order to be notified when a client is disconnected. Client disconnect notifications are "relative" to who is receiving the notification. + +**There are two general "disconnection" categories:** +- **Logical**: Custom server side code (code you might have written for your project) invokes `NetworkManager.DisconnectClient`. + - Example: A host player might eject a player or a player becomes "inactive" for too long. +- **Network Interruption**: The transport detects there is no longer a valid network connection. + +**When disconnect notifications are triggered:** +- Clients are notified when they are disconnected by the server. +- The server is notified if the client side disconnects (i.e. a player exits a game session) +- Both the server and clients are notified when their network connection is disconnected (network interruption) + +**Scenarios where the disconnect notification will not be triggered**: +- When a server "logically" disconnects a client. + - _Reason: The server already knows the client is disconnected._ +- When a client "logically" disconnects itself. + - _Reason: The client already knows that it is disconnected._ + +### Connection Notification Manager Example +Below is one example of how you could provide client connect and disconnect notifications to any type of NetworkBehaviour or MonoBehaviour derived component. + +:::important +The `ConnectionNotificationManager` example below should only be attached to the same GameObject as `NetworkManager` to assure it persists as long as the `NetworkManager.Singleton` instance. +::: + + +```csharp +using System; +using UnityEngine; +using Unity.Netcode; + +/// +/// Only attach this example component to the NetworkManager GameObject. +/// This will provide you with a single location to register for client +/// connect and disconnect events. +/// +public class ConnectionNotificationManager : MonoBehaviour +{ + public static ConnectionNotificationManager Singleton { get; internal set; } + + public enum ConnectionStatus + { + Connected, + Disconnected + } + + /// + /// This action is invoked whenever a client connects or disconnects from the game. + /// The first parameter is the ID of the client (ulong). + /// The second parameter is whether or not that client is connecting or disconnecting. + /// + public event Action OnClientConnectionNotification; + + private void Awake() + { + if (Singleton != null) + { + // As long as you aren't creating multiple NetworkManager instances, throw an exception. + // (***the current position of the callstack will stop here***) + throw new Exception($"Detected more than one instance of {nameof(ConnectionNotificationManager)}! " + + $"Do you have more than one component attached to a {nameof(GameObject)}"); + } + Singleton = this; + } + + private void Start() + { + if (Singleton != this){ + return; // so things don't get even more broken if this is a duplicate >:( + } + + if (NetworkManager.Singleton == null) + { + // Can't listen to something that doesn't exist >:( + throw new Exception($"There is no {nameof(NetworkManager)} for the {nameof(ConnectionNotificationManager)} to do stuff with! " + + $"Please add a {nameof(NetworkManager)} to the scene."); + } + + NetworkManager.Singleton.OnClientConnectedCallback += OnClientConnectedCallback; + NetworkManager.Singleton.OnClientDisconnectCallback += OnClientDisconnectCallback; + } + + private void OnDestroy() + { + // Since the NetworkManager could potentially be destroyed before this component, only + // remove the subscriptions if that singleton still exists. + if (NetworkManager.Singleton != null) + { + NetworkManager.Singleton.OnClientConnectedCallback -= OnClientConnectedCallback; + NetworkManager.Singleton.OnClientDisconnectCallback -= OnClientDisconnectCallback; + } + } + + private void OnClientConnectedCallback(ulong clientId) + { + OnClientConnectionNotification?.Invoke(clientId, ConnectionStatus.Connected); + } + + private void OnClientDisconnectCallback(ulong clientId) + { + OnClientConnectionNotification?.Invoke(clientId, ConnectionStatus.Disconnected); + } +} +``` diff --git a/versioned_docs/version-1.0.0/components/networktransform.md b/versioned_docs/version-1.0.0/components/networktransform.md new file mode 100644 index 000000000..06e611f44 --- /dev/null +++ b/versioned_docs/version-1.0.0/components/networktransform.md @@ -0,0 +1,69 @@ +--- +id: networktransform +title: NetworkTransform +--- +import ImageSwitcher from '@site/src/ImageSwitcher.js'; + +The position, rotation, and scale of a [`NetworkObject`](../basics/networkobject.md) is normally only synchronized once when that object is spawned. To synchronize position, rotation, and scale at realtime during the game, a `NetworkTransform` component is needed. `NetworkTransform` synchronizes the transform from server object to the clients. + +`NetworkTransform` covers most use cases for synchronizing transforms. For some special cases such as really fast paced games a custom implementation with a different interpolation algorithm might be better. + +:::tip +You can have multiple `NetworkTransform` components on child objects of your network object to synchronize individual positions of child objects. +::: + +## Restricting Synchronization + +Quite often not all transform values of a GameObject need to be synchronized over the network. For instance if the scale of the GameObject never changes it can be deactivated in the `syncing scale` row in the inspector. Currently deactivating synchronization only saves on CPU costs but in the future it will also reduce the bandwidth used by NetworkTransform`. + +## Thresholds + +The threshold values can be used to set a minimum threshold value. Whether to properly scale to your project's world unit scale or to reduce the frequency of synchronization updates, changes below threshold values will not be synchronized. For example, if your NetworkTransform has Interpolate enabled you might find that you can lower your position threshold resolution (i.e. position threshold value increased) without impacting the "smoothness" of an object's motion. Increasing the threshold value (lowering the resolution of synchronization updates) will reduce the frequency of when the object's position is synchronized which translates to reducing bandwidth consumption. + +:::note +Many small changes below the threshold will still result in a synchronization of the values as soon as all the accumulative changes cross the threshold. +::: + +## Local Space + +By default `NetworkTransform` synchronizes the transform of an object in world space. The `In Local Space` configuration option allows to switch to synchronizing the transform in local space instead. + +Using `local space` can improve the synchronization of the transform when the object gets re-parented because the re-parenting will not change the `local space` transform of the object but would modify the `global space` position. + +## Interpolation + +Check the `Interpolate` setting to enabled interpolation. Interpolation is enabled by default and is highly recommended. With interpolation enabled the `NetworkTransform` smoothly interpolates incoming changes to position, rotation and scale. In addition interpolation buffers the incoming data with a slight delay and applies additional smoothing to the values. All these factors combined result in a much smoother transform synchronization. + +When `Interpolate` is disabled changes to the transform are applied immediately resulting in a less smooth position and more jitter. + +:::note +The NetworkTransform component only interpolates client-side. For smoother movement on the host or server, users may want to implement interpolation server-side as well. While the server will not have the jitter caused by the network, some stutter can still happen locally, for example if movement is done in FixedUpdate with a low physics update rate. +::: + +
+ +
Graphic of a buffered tick between the server and a client (i.e. interpolation)
+
+ +### ClientNetworkTransform + +`NetworkTransform` always synchronizes positions from the server to the clients and position changes on the clients are not allowed. Netcode for GameObjects comes with a sample containing a `ClientNetworkTransform`. This transform synchronizes the position of the owner client to the server and all other client allowing for client authoritative gameplay. + +You can use the existing ClientNetworkTransform in the Multiplayer Samples Utilities package.
+To add the Multiplayer Samples Utilities package: + +- Open the Package Manager by selecting Window > Package Manager. +- Select the plus button (+) > Add from git URL.... +- Copy and paste the following Git URL: https://github.com/Unity-> Technologies/com.unity.multiplayer.samples.coop.git?path=/Packages/com.unity.multiplayer.samples.coop#main +- Select Add. + +Optionally, you can directly add this line to your `manifest.json` file: +`"com.unity.multiplayer.samples.coop": "https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop.git?path=/Packages/com.unity.multiplayer.samples.coop#main"` + +You can also create your own `ClientNetworkTransform` by deriving from `NetworkTransform`, overriding the `OnIsServerAuthoritative` virtual method, and returning false: + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Packages/com.unity.multiplayer.samples.coop/Utilities/Net/ClientAuthority/ClientNetworkTransform.cs +``` diff --git a/versioned_docs/version-1.0.0/installation/installation.md b/versioned_docs/version-1.0.0/installation/installation.md new file mode 100644 index 000000000..b3e9b09a2 --- /dev/null +++ b/versioned_docs/version-1.0.0/installation/installation.md @@ -0,0 +1,66 @@ +--- +id: install +title: Install Netcode for GameObjects +description: How to install Unity Netcode for GameObjects (Netcode). +--- + +Use this guide to install Unity Netcode for GameObjects (Netcode) 1.0.0 and later. + +## Prerequisites + +Before installing Netcode, you should ensure you have: + * An active Unity account with a valid license. + * A Netcode-supported installation of Unity. See [Netcode's requirements](#netcode-installation-requirements) for full details. + * An existing Unity project. If you do not have a project yet, we recommend using the [Hello World](../tutorials/helloworld.md) example to test the Netcode installation process and learn some of the basic features of Netcode. + +### Netcode Installation Requirements + +Netcode supports the following Unity versions: +* Unity 2020.3, 2021.1, 2021.2, and 2021.3 LTS +* Mono and IL2CPP [Scripting Backends](https://docs.unity3d.com/Manual/scripting-backends.html) + +Netcode supports the following platforms: +* Windows, MacOS, and Linux +* iOS and Android +* XR platforms running on Windows, Android, and iOS operating systems +* Most [**closed platforms**](https://unity.com/platform-installation), such as consoles. Contact us for more information about specific closed platforms. + * When working with consoles (such as PlayStation, Xbox, or Nintendo Switch), there may be Netcode-specific policies you should be aware of while testing and before launching your game live. Refer to the console's internal documentation for more information. This content is typically protected by NDA. + +:::caution Using WebGL +Netcode does not support the WebGL platform because it does not allow access to IP Sockets. + +There are third party transports provided by the community that may enable you to use Netcode on WebGL platforms. A list of these transports are found [here](https://github.com/Unity-Technologies/multiplayer-community-contributions#transports). + +Use with caution: +* You may encounter bugs and issues while using Netcode on WebGL, and we will not prioritize fixing those issues. +* The server or host cannot be a WebGL client, but a Desktop or Mobile build. +* You may experience **increased** latency and jitter because of the TCP protocol used by WebSockets. +::: + +## Installing with the Package Manager + +1. Open your **Unity Hub** and select the **Project** you are presently working on or create a **New Project**. +1. From the menu bar, navigate to **Window** > **Package Manager**. +1. When using 2021.3+ click the plus sign ![Add](/img/add.png) in the **Package Manager** status bar and select **Add package by name**. +1. If using 2020.3LTS there is no option to add by package name, instead click **Add package from git URL**. + + ![Package Installed](/img/install/addbyname.png) + +1. Copy and paste the following in the pop-up window: +``` +com.unity.netcode.gameobjects +``` + +1. Click **Add**. The package installs and appears as **Netcode for GameObjects** under **Packages** in the **Package Manager** window. + +## Next Steps + +See the following content to continue your journey using Netcode: + +* Use the [Hello World project](../tutorials/helloworld.md) to create a project, test your Netcode install, and learn basic features of Netcode for GameObjects. +* Build on the Hello World project to continue learning about different features of Netcode with the [Golden Path series](../tutorials/goldenpath_series/gp_intro.md). +* Check out the educational samples to further explore Netcode and its abilities: + * [Boss Room](../learn/bossroom/getting-started-boss-room.md) + * [2D Spaceshooter Bitesize Sample](../learn/bitesize/bitesize-spaceshooter.md) + * [Invaders Bitesize Sample](../learn/bitesize/bitesize-invaders.md) + * [Client-Driven Bitesize Sample](../learn/bitesize/bitesize-clientdriven.md) diff --git a/versioned_docs/version-1.0.0/installation/migratingfromUNet.md b/versioned_docs/version-1.0.0/installation/migratingfromUNet.md new file mode 100644 index 000000000..1e404b81a --- /dev/null +++ b/versioned_docs/version-1.0.0/installation/migratingfromUNet.md @@ -0,0 +1,682 @@ +--- +id: upgrade_from_UNet +title: Migrating from UNet to Netcode for GameObjects +--- + +Use this step-by-step guide to migrate your projects from Unity UNet to Netcode for GameObjects (Netcode). If you need help, contact us in the [Unity Multiplayer Networking Discord](https://discord.gg/buMxnnPvTb). + +:::warning UNet Deprecation +UNet is an entirely deprecated product, and you should upgrade to Netcode for GameObjects as soon as possible. +::: + +## Current limitations + +Review the following limitations for upgrade and migrations from previous versions of Unity UNet to Netcode: + +- Naming constraints may cause issues. UNet prefixed methods with `Cmd` or `Rpc`. Netcode requires postfix. This may require either complicated multi-line regex to find and replace, or manual updates. For example, `CommandAttribute` has been renamed `ServerRpcAttribute` and `ClientRPCAttribute` has been renamed `ClientRpcAttribute`. +- Errors for RPC postfix naming patterns do not show in your IDE. +- Client and Server have separate representations in UNet. UNet has a number of callbacks that do not exist for Netcode. +- Prefabs need to be added to the prefab registration list for Netcode. +- Matchmaking is not available in Netcode at this time. + +## Backup your project + +It is recommended that you back up your project before proceeding with the migration. For example: + +* Create a copy of your entire project folder. +* Use source control software, like Git. + +:::bestpractice +We recommend using both methods to backup your project. This gives you a copied project and tracking through committed changes and history. +::: + +## Install Netcode and restart Unity + +See the [Netcode installation guide](installation.md) for more information. + +:::note +If you install Git for the first time, you will need to restart your system. +::: + +## RPC Invoking + +Invoking an RPC works the same way as in UNet. Just call the function and it will send an RPC. + + + +## Replace NetworkIdentity with NetworkObject + +UNet’s `NetworkIdentity` is called `NetworkObject` in Netcode and works in a similar way. + +## Replace UNet NetworkTransform with Netcode NetworkTransform + +UNet’s `NetworkTransform` is also called `NetworkTransform` in Netcode and works in a similar way. + +The `NetworkTransform` does not have full feature parity with UNET's `NetworkTransform`. It lacks features like position synchronizing for rigidbodies. + +## Replace UNet NetworkAnimator with Netcode NetworkAnimator + +Replace UNEt's `NetworkAnimator` with Netcode's `NetworkAnimator` component everywhere in your project. + +## Update NetworkBehaviour + +Replace UNet `NetworkBehaviour` with Netcode's `NetworkBehaviour` everywhere in your project. + + + + + +```csharp +public class MyUnetClass : NetworkBehaviour +{ + [SyncVar] + public float MySyncFloat; + public void Start() + { + if (isClient) + { + CmdExample(10f); + } + else if (isServer) + { + RpcExample(10f); + } + } + [Command] + public void CmdExample(float x) + { + Debug.Log(“Runs on server”); + } + [ClientRpc] + public void RpcExample(float x) + { + Debug.Log(“Runs on clients”); + } +} +``` + + + + +```csharp +public class MyNetcodeExample : NetworkBehaviour +{ + public NetworkVariable MyNetworkVariable = new NetworkVariable(); + public override void OnNetworkSpawn() + { + ExampleClientRpc(10f); + ExampleServerRpc(10f); + } + [ServerRpc] + public void ExampleServerRpc(float x) + { + Debug.Log(“Runs on server”); + } + [ClientRpc] + public void ExampleClientRpc(float x) + { + Debug.Log(“Runs on clients”); + } +} +``` + + + + +See [NetworkBehaviour](../basics/networkbehaviour.md) for more information. + +## Replace SyncVar + +Replace `SyncVar` with `NetworkVariable` everywhere in your project. + +To achieve equivalent functionality of `SyncVar` hooks in Netcode subscribe a function to the `OnValueChanged` callback of the `NetworkVariable`. A noteable difference between the UNet hooks and Netcode's `OnValueChanged` callback is that Netcode gives you both the old and the newly changed value while UNet provides you only with the old value. With UNet, you also had to manually assign the value of the SyncVar. + + + + + +```csharp +public class SpaceShip : NetworkBehaviour +{ + [SyncVar] + public string PlayerName; + + + [SyncVar(hook = "OnChangeHealth"))] + public int Health = 42; + + void OnChangeHealth(int newHealth){ + Health = newHealth; //This is no longer necessary in Netcode. + Debug.Log($"My new health is {newHealth}."); + } +} +``` + + + + +```csharp +// Don't forget to initialize NetworkVariable with a value. +public NetworkVariable PlayerName = new NetworkVariable(); + +public NetworkVariable Health = new NetworkVariable(42); + +// This how you update the value of a NetworkVariable, you can also use .Value to access the current value of a NetworkVariable. +void MyUpdate() +{ + Health.Value += 30; +} + + +void Awake() +{ + // Call this is in Awake or Start to subscribe to changes of the NetworkVariable. + Health.OnValueChanged += OnChangeHealth; +} + +void OnChangeHealth(int oldHealth, int newHealth){ + //There is no need anymore to manually assign the value of the variable here with Netcode. This is done automatically by Netcode for you. + Debug.Log($"My new health is {newHealth}. Before my health was {oldHealth}"); +} +``` + + + + +Replace all postfix increment and decrement usages of SyncVar in your project. Netcode's `NetworkVariable.Value` exposes a value type that's why postfix increment/decrement is not supported. + + + + + +```csharp + +public int Health = 42; + +public void Update(){ + Health++; +} + + +``` + + + + +```csharp + +public NetworkVariable Health = new NetworkVariable(42); + +public void Update(){ + Health.Value = Health.Value + 1; +} +``` + + + + +See [NetworkVariable](../basics/networkvariable.md) for more information. + + +## Replace SyncList with NetworkList + +Replace `SyncList` with `NetworkList` everywhere in your project. `NetworkList` has a `OnListChanged` event which is similar to UNet's `Callback`. + + + + + +```csharp +public SyncListInt m_ints = new SyncListInt(); + +private void OnIntChanged(SyncListInt.Operation op, int index) +{ + Debug.Log("list changed " + op); +} + + +public override void OnStartClient() +{ + m_ints.Callback = OnIntChanged; +} +``` + + + +```csharp +NetworkList m_ints = new NetworkList(); + +// Call this is in Awake or Start to subscribe to changes of the NetworkList. +void ListenChanges() +{ + m_ints.OnListChanged += OnIntChanged; +} + +// The NetworkListEvent contains information about the operation and index of the change. +void OnIntChanged(NetworkListEvent changeEvent) +{ + +} +``` + + + + + +## Replace Command/ClientRPC + +UNet’s `Command/ClientRPC` is replaced with `Server/ClientRpc` in Netcode which works in a similar way. + + + + + +```csharp + [Command] + public void CmdExample(float x) + { + Debug.Log(“Runs on server”); + } + [ClientRpc] + public void RpcExample(float x) + { + Debug.Log(“Runs on clients”); + } +``` + + + + +```csharp + [ServerRPC] + public void ExampleServerRpc(float x) + { + Debug.Log(“Runs on server”); + } + [ClientRPC] + public void ExampleClientRpc(float x) + { + Debug.Log(“Runs on clients”); + } +``` + + + + +:::note +In Netcode, RPC function names must end with a `ClientRpc/ServerRpc` suffix. +::: + +See [Messaging System](../advanced-topics/messaging-system.md) for more information. + +## Replace OnServerAddPlayer + +Replace `OnServerAddPlayer` with `ConnectionApproval` everywhere in your project. + + + + + +```csharp +using UnityEngine; +using UnityEngine.Networking; +using UnityEngine.Networking.NetworkSystem; + +class MyManager : NetworkManager +{ + public override void OnServerAddPlayer(NetworkConnection conn, short playerControllerId, NetworkReader extraMessageReader) + { + if (extraMessageReader != null) + { + var s = extraMessageReader.ReadMessage(); + Debug.Log("my name is " + s.value); + } + OnServerAddPlayer(conn, playerControllerId, extraMessageReader); + } +} +``` + + + + + +Server-only example: + +```csharp +using Unity.Netcode; + +private void Setup() +{ + NetworkManager.Singleton.ConnectionApprovalCallback += ApprovalCheck; + NetworkManager.Singleton.StartHost(); +} + +private void ApprovalCheck(byte[] connectionData, ulong clientId, NetworkManager.ConnectionApprovedDelegate callback) +{ + //Your logic here + bool approve = true; + bool createPlayerObject = true; + + // The prefab hash. Use null to use the default player prefab + // If using this hash, replace "MyPrefabHashGenerator" with the name of a prefab added to the NetworkPrefabs field of your NetworkManager object in the scene + ulong? prefabHash = NetworkpawnManager.GetPrefabHashFromGenerator("MyPrefabHashGenerator"); + + //If approve is true, the connection gets added. If it's false. The client gets disconnected + callback(createPlayerObject, prefabHash, approve, positionToSpawnAt, rotationToSpawnWith); +} +``` + + + + +See [Connection Approval](../basics/connection-approval.md) for more information. + +## Replace NetworkServer.Spawn with NetworkObject.Spawn + +Replace `NetworkServer.Spawn` with `NetworkObject.Spawn` everywhere in your project. + + + + + +```csharp + +using UnityEngine; +using UnityEngine.Networking; + +public class Example : NetworkBehaviour +{ + //Assign the prefab in the Inspector + public GameObject m_MyGameObject; + GameObject m_MyInstantiated; + + void Start() + { + //Instantiate the prefab + m_MyInstantiated = Instantiate(m_MyGameObject); + //Spawn the GameObject you assign in the Inspector + NetworkServer.Spawn(m_MyInstantiated); + } +} + +``` + + + + +```csharp +GameObject go = Instantiate(myPrefab, Vector3.zero, Quaternion.identity); +go.GetComponent().Spawn(); +``` + + + + + +See [Object Spawning](../basics/object-spawning.md) for more information. + +## Custom Spawn Handlers + +Netcode has `Custom Spawn Handlers` to replace UNet's `Custom Spawn Functions`. See [Object Pooling](../advanced-topics/object-pooling) for more information. + +## Replace NetworkContextProperties + +Netcode has `IsLocalPlayer`, `IsClient`, `IsServer` and `IsHost` to replace UNets `isLocalPlayer`, `isClient` and `isServer`. In Netcode each object can be owned by a specific peer. This can be checked with `IsOwner` which is similar to UNets ``hasAuthority``. + +## Network Proximity Checker/ OnCheckObserver with Netcode visibility + +There is no direct equivalent to the `NetworkPromimityChecker` UNet component in Netcode. Network visiblilty for clients works similar as in UNet. Netcode does not have an equivalent to the `ObjectHide` message from UNet. In Netcode networked objects on the host are always visible. There is no equivalent to the `OnSetLocalVisibility` function in UNet. A manual network promiximty implementation with the `OnCheckObserver` can be ported to Netcode by using `NetworkObject.CheckObjectVisibility`. `OnRebuildObservers` is not needed for Netcode visibilty system. + + + + + +```csharp +public override bool OnCheckObserver(NetworkConnection conn) +{ + return IsvisibleToPlayer(getComponent(), coon); +} + +public bool IsVisibleToPlayer(NetworkIdentity identity, NetworkConnection conn){ + // Any promimity function. + return true; +} +``` + + + + + + +```csharp +public void Start(){ + NetworkObject.CheckObjectVisibility = ((clientId) => { + return IsVisibleToPlayer(NetworkObject, NetworkManager.Singleton.ConnectedClients[clientId]); + }); +} + +public bool IsVisibleToPlayer(NetworkObject networkObject, NetworkClient client){ + // Any promimity function. + return true; +} +``` + + + + +See [Object Visbility](../basics/object-visibility.md) to learn more about Netcodes network visiblity check. + +## Update SceneManagement + +In Netcode, scene management is not done over the `NetworkManager` like in UNet. The `NetworkSceneManager` provides equivalent functionality for switching scenes. + + + + + +```csharp +public void ChangeScene() +{ + MyNetworkManager.ServerChangeScene("MyNewScene"); +} +``` + + + + +```csharp +public void ChangeScene() +{ + NetworkSceneManager.LoadScene("MyNewScene", LoadSceneMode.Single); +} +``` + + + + +## Update ClientAttribute/ClientCallbackAttribute and ServerAttribute/ServerCallbackAttribute + +Netcode currently does not offer a replacement for marking a function with an attribute so that it only runs on the server or the client. You can manually return out of the function instead. + + + + + +```csharp +[Client] +public void MyClientOnlyFunction() +{ + Debug.Log("I'm a client!"); +} +``` + + + + + + +```csharp +public void MyClientOnlyFunction() +{ + if (!IsClient) { return; } + + Debug.Log("I'm a client!"); +} +``` + + + + + +## Replace SyncEvent with RPC event + +Netcode does not provide an equivalent for `SyncEvent`. To port `SyncEvent` code from UNet to Netcode, send an RPC to invoke the event on the other side. + + + + + +```csharp +public class DamageClass : NetworkBehaviour +{ + public delegate void TakeDamageDelegate(int amount); + + [SyncEvent] + public event TakeDamageDelegate EventTakeDamage; + + [Command] + public void CmdTakeDamage(int val) + { + EventTakeDamage(val); + } +} +``` + + + + + +```csharp +public class DamageClass : NetworkBehaviour +{ + public delegate void TakeDamageDelegate(int amount); + + public event TakeDamageDelegate EventTakeDamage; + + [ServerRpc] + public void TakeDamageServerRpc(int val) + { + EventTakeDamage(val); + OnTakeDamageClientRpc(val); + } + + [ClientRpc] + public void OnTakeDamageClientRpc(int val){ + EventTakeDamage(val); + } +} +``` + + + + +## Network Discovery + +Netcode does not provide Network Discovery. The Contributions repository provides an example implementation for [NetworkDiscovery](https://github.com/Unity-Technologies/multiplayer-community-contributions/tree/main/com.community.netcode.extensions/Runtime/NetworkDiscovery). + +## Next Steps + +After migrating and updating to the Netcode package, we recommend looking into the following: + +* Consider using the [Hello World](../tutorials/helloworld.md) and [Golden Path series](../tutorials/goldenpath_series/gp_intro.md) to learn some basics of Netcode for GameObjects. +* Explore the educational samples content for a deeper exploration into Netcode for GameObjects: + * [Boss Room](../learn/bossroom/getting-started-boss-room.md) + * [2D Spaceshooter Bitesize Sample](../learn/bitesize/bitesize-spaceshooter.md) + * [Invaders Bitesize Sample](../learn/bitesize/bitesize-invaders.md) + * [Client-Driven Bitesize Sample](../learn/bitesize/bitesize-clientdriven.md) + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import useBaseUrl from '@docusaurus/useBaseUrl'; +import Link from '@docusaurus/Link'; \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/installation/migratingfrommlapi.md b/versioned_docs/version-1.0.0/installation/migratingfrommlapi.md new file mode 100644 index 000000000..d46c0d941 --- /dev/null +++ b/versioned_docs/version-1.0.0/installation/migratingfrommlapi.md @@ -0,0 +1,175 @@ +--- +id: upgrade_from_mlapi +title: Upgrade MLAPI to Netcode for GameObjects +description: How to upgrade your current MLAPI installation to the Netcode for GameObjects (Netcode). +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +Use this guide to upgrade from MLAPI 0.1.0 to Netcode for GameObjects (Netcode) 1.0.0. + +:::caution Upgrade to Netcode for GameObjects +It is recommended to upgrade to Netcode from MLAPI as soon as possible. MLAPI is not maintained and will not have future updates. MLAPI should be considered a deprecated product. +::: + +## Backup your MLAPI project + +:::important +Consider this step a **required**: Upgrading to the package version of Netcode can cause issues with your current project. The new version modifies files and locations that are drastically different than previous MLAPI versions. +::: + +Backup your project using the following recommended methods: + +* Create a copy of your entire project folder. +* Use source control software, like Git. + +:::bestpractice +We recommend using both methods to backup your project. This gives you a copied project and tracking through committed changes and history. +::: + +## Use the Upgrade Tool on your MLAPI project + +Manually upgrading from the `.dll` version installed by MLAPI to the new package version breaks all MLAPI component references in your scenes and prefabs. Netcode references components using GUIDs that work differently for packages than for `.dll`s. + +To help with the upgrade process to Netcode, we have created an upgrade tool. + +To start upgrading, add the upgrade tool to your project by using the **Add package from git URL..** option in the **Package Manager** window. Use the following URL: + +```html +https://github.com/Unity-Technologies/mlapi-community-contributions.git?path=/com.unity.multiplayer.mlapi-patcher +``` + +After installing the patcher package, you can continue the upgrade process. + +## Install the Netcode Package +Follow the [installation guide](installation.md) to install Netcode. + +After installing the package, you will have error messages in the console, which is expected behavior because your project now contains MLAPI and Netcode at the same time. This will be remedied by the end of this guide. + +Installing the Netcode package will also install some other packages such as [`Unity Transport`](https://docs.unity3d.com/Packages/com.unity.transport@latest/), [`Unity Collections`](https://docs.unity3d.com/Packages/com.unity.collections@latest/), [`Unity Burst`](https://docs.unity3d.com/Packages/com.unity.burst@latest/) etc. + +The `Burst` package requires an Editor restart. So restart your Unity after the installation. Unity will ask you to enter Fail Safe mode at the next boot, which is normal behaviour since all your network code is not compiling anymore. + +:::warning +Do not remove the old version of MLAPI yet. It will still be used in the next step. +::: + +## Updating Script References + +Open the Netcode patcher window by selecting **Window** > **Netcode Patcher** in the menu bar. The patcher will ask you whether you are using the *Installer* version of MLAPI or the *Source* version. + +Previously there were two major ways to use MLAPI in projects. You could either download a release version of MLAPI using the MLAPI installer or manually copy the source files into your project. + +:::tip +If you are not sure which way of MLAPI you are using check whether you have the `Assets/MLAPI/Lib/MLAPI.dll` file in your project. If that's the case you are using the `Installer` version. +::: + +In the Patcher window, select **Installer** or **Source** button: + + + + + +1. Select **Installer**. +1. Select **Update Script References**. + + + + +1. Select **Source**. +1. The window prompts you to link a MLAPI source directory. +1. Take the directory in your project containing the MLAPI source and drop it into the field. +1. Select **Update Script References**. + + + + +After you complete the **Update Script References** process of the patcher, the Netcode components on your `Prefabs` and `GameObject`s should have been updated to their new names. + +There is also a **Replace Type Names** button in the Patcher window. This step is optional. It automatically renames old type names in your scripts to the API changes made in Netcode, saving you some time to manually rename it. It performs a simple global replace of some of the type names. You may want to manually do this process instead if you want more control over changes. + +## Remove older MLAPI versions + +Remove all the folders containing the existing non-package version of MLAPI from your project. Usually this means removing the `Assets/MLAPI` and `Assets/Editor/MLAPI` folders from the project. + +## Upgrade your code to the new Netcode APIs + +:::info +Upgrading your code is a manual and long process. If you run into difficulties while upgrading please join our [Discord](https://discord.gg/buMxnnPvTb), and we will support you. +::: + +The Unity Multiplayer team tried to keep most of the MLAPI intact in Netcode. However, a successful compilation still requires some changes. + +### `NetworkVariable` changes + +`NetworkVariable` type is now generic only and the type specified in the generic needs to be a value type. First, change all your `NetworVariable*` types for their generic counterpart. For example, `NetworkVariableInt` becomes `NetworkVariable`, NetworkVariableFloat becomes `NetworkVariable` and so on. Now, some of your types (string, for example) will not match the new type requirements for `NetworkVariable`. If your type is a string, you can use `FixedString32Bytes` instead. One should note that this type does not allow you to change the size of the string. For custom structs that only contain value types, you can implement `INetworkSerializable`, and it will work. Finally, for the other types, you will need to create your own `NetworkVariable`. To achieve that, create a new class, inherit from `NetworkVariableBase`, and implement all the abstract members. If you already had custom `NetworkVariable`, read and write functions now uses our `FastBuffer` to read or write from and to the stream. + +### Scene Management changes + +The scene management had some changes unifying the way users uses it. First, it is now under the `NetworkManager` Singleton. Consequently, you directly access it by: + +```csharp +var sceneManager = NetworkManager.Singleton.SceneManager; +``` + +Next, there is now only one scene event instead of many: `OnSceneEvent`. You can subscribe to it and get scene events information from the `SceneEvent` class. In this class, you will find the `SceneEventType`, which will give you precisions on what type of event is coming from the Scene Manager. Finally, the primary function to switch between scenes has changed to match the Unity Scene Manager. Instead of `SwitchScene`, you now call `LoadScene` with two parameters: the scene name and the `LoadSceneMode`, which is the standard way to load a scene in Unity. + +### `NetworkBehavior` changes + +There are two main changes in `NetworkBehavior`. First, the `NetworkStart` method becomes `OnNetworkSpawn`, and we introduced `OnNetworkDespawn` to keep things symmetrical. Second, `OnDestroy` now needs to be overridden since NetworkBehavior already uses it. + +## Changes in behavior + +We tried to keep the behavior changes minimal but two changes may cause errors in your scripts. First, the `NetworkManager` now does its connection shut down when the application quits. If you were doing it by yourself, you would end up with an error saying that you tried to disconnect twice. Second, the library now fires all the `OnValueChanged` events from the `NetworkVariable` **after** the `OnNetworkSpawn` (previously known as `NetworkStart`) method has returned. You will need to refactor any scripts depending on this order accordingly. + +### Upgrade RPCs + +The way RPCs are invoked has changed with this version of Netcode. Please read our new [documentation about RPCs](../advanced-topics/messaging-system.md) and replace your existing RPCs with the new system. + +### Serialization + +We replaced the old `INetworkSerializable` interface with a new `INetworkSerializable` interface. The interface works a bit different. See [`INetworkSerializable`](../advanced-topics/serialization/inetworkserializable.md). + +The page also includes information on nested serial types. + +### SyncVars + +SyncVars have been removed in Netcode. Convert your existing SyncVars into [NetworkVariables](../basics/networkvariable). + +## Remove the Patcher Package +After you are done upgrading your project, you can remove the Netcode Patcher package from your project in the Unity Package Manager as it is no longer needed. + +## Troubleshooting + +**Error: The type or namespace name 'MLAPI' could not be found** + +This error will pop up if your project uses Assembly definition (`.asmdef`) files. After switching to the package version your assembly definition files will need to reference `com.unity.multiplayer.mlapi.runtime`. + +**Error: The type or namespace name 'NetworkedBehaviour' could not be found** + +If you get an error message like this (or for another Netcode type than `NetworkedBehaviour`) in the console it is most likely because your code contains outdated APIs. Open the script indicated in the error messagea and update all APIs to the new names. + +**Error: SerializedObjectNotCreatableException: Object at index 0 is null** + +If this appears whenever you enter playmode or save a scene, close the Unity Editor and open it again and this should be gone. + +## Next Steps + +After migrating and updating to the Netcode package, we recommend looking into the following: + +* Consider using the [Hello World](../tutorials/helloworld.md) and [Golden Path series](../tutorials/goldenpath_series/gp_intro.md) to learn some basics of Netcode for GameObjects. +* Explore the educational samples content for a deeper exploration into Netcode for GameObjects: + * [Boss Room](../learn/bossroom/getting-started-boss-room.md) + * [2D Spaceshooter Bitesize Sample](../learn/bitesize/bitesize-spaceshooter.md) + * [Invaders Bitesize Sample](../learn/bitesize/bitesize-invaders.md) + * [Client-Driven Bitesize Sample](../learn/bitesize/bitesize-clientdriven.md) + +import useBaseUrl from '@docusaurus/useBaseUrl'; +import Link from '@docusaurus/Link'; \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/learn/bitesize/bitesize-clientdriven.md b/versioned_docs/version-1.0.0/learn/bitesize/bitesize-clientdriven.md new file mode 100644 index 000000000..873ac4379 --- /dev/null +++ b/versioned_docs/version-1.0.0/learn/bitesize/bitesize-clientdriven.md @@ -0,0 +1,68 @@ +--- +id: bitesize-clientdriven +title: ClientDriven Sample +description: Learn more about Client driven movements, networked physics, spawning vs statically placed objects, object reparenting +--- + +## Client Driven Movements +Making movements feel responsive while staying consistent over multiple game executables, each with their own timelines, is a challenge for many networked games. + +## TLDR: + +- Use [ClientNetworkTransform](../../components/networktransform.md#clientnetworktransform) to sync client authoritative transform updates to the server and other clients. +- Make sure ownership is set properly on that NetworkObject to be able to move it. +- Since your clients live on different timelines (one per player), you have to be careful about who takes decisions and keep some of those decisions centralized on the server. +- DON'T FORGET to test with latency, as your game will behave differently depending on whether client or server make decisions. + +## Sample: + +ClientDriven's aim is to create a quick sample to show responsive character movements that don't feel sluggish, even under bad network conditions. +It uses the ClientNetworkTransform sample and moves your own player's position client side, [client authoritatively](../dealing-with-latency.md#allow-low-impact-client-authority). + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/9854697081df4962dd525d7c3bd65f9f88c7ee60/Basic/ClientDriven/Assets/Scripts/ClientPlayerMove.cs#L57-L64 +``` + +### Client side object detection for pickup with server side pickup validation +Ingredients in ClientDriven are owned by the server, since they are [shared objects](../dealing-with-latency.md#issue-world-consistency). This means if a player tries to grab an object while that object is moving, a server side range detection would sometimes fail, even though it should have succeeded (since ingredients are replicated with some lag, so the player would try to grab ingredients that are a few milliseconds behind). +To make sure this doesn't happen, the object detection done to grab an ingredient is also done client side. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/develop/Basic/ClientDriven/Assets/Scripts/ClientPlayerMove.cs#L66-L94 +``` + +But the pickup itself is done server side. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/996ac9785c4e825c0e4692f115c9b5f2b4c7c386/Basic/ClientDriven/Assets/Scripts/ServerPlayerMove.cs#L41-L69 +``` + +Notice how we're checking whether that object can be picked up or not (since another player could have picked it up at the same time, creating a conflict). + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/996ac9785c4e825c0e4692f115c9b5f2b4c7c386/Basic/ClientDriven/Assets/Scripts/ServerPlayerMove.cs#L45 +``` +If the object is already picked up, we're not doing anything. You client side animations should take this into account and cancel any animations "carrying" something. + +### Server side player spawn points +In this sample, our spawn points list is server side (to have a single source of truth). +ClientNetworkTransforms can be updated by owners only, which means the server can't update the player's position directly. +This means OnNetworkSpawn, the server will need to assign a position to the player using a ClientRPC. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/0c9081b27e66879ce5742314c13ff69ac45ff02e/Basic/ClientDriven/Assets/Scripts/ServerPlayerMove.cs#L24-L37 +``` + +## Server physics with client driven movements (interactions on different timelines) +All the ingredients can be bumped against by players. However, since ingredients are server driven, bumping against them with client driven movements can cause desync issues. +This sample uses NetworkRigidbody for ingredients, which sets Kinematic = true, making them immovable client side. This way, only server side movements (from the replicated player movements) will move the ingredients. Two players bumping the same ingredient will still only have one single result, calculated server side, with no risk of desync. + +## Reparenting + +This sample uses Netcode's automatic reparenting synchronization. By setting a NetworkObject's parent to another NetworkObject, that reparenting will be synced to connected clients. +Note that we're also setting InLocalSpace while reparenting, to make sure the client side ingredient will be tracked the same way as the server side one (else the ingredient would be carried with latency, making it appear "dragging along behind you"). +An ownership change could also have been used here, but the client would have needed to ask the server for that change first. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/0c9081b27e66879ce5742314c13ff69ac45ff02e/Basic/ClientDriven/Assets/Scripts/ServerPlayerMove.cs#L42-L54 +``` diff --git a/versioned_docs/version-1.0.0/learn/bitesize/bitesize-introduction.md b/versioned_docs/version-1.0.0/learn/bitesize/bitesize-introduction.md new file mode 100644 index 000000000..57bce568b --- /dev/null +++ b/versioned_docs/version-1.0.0/learn/bitesize/bitesize-introduction.md @@ -0,0 +1,42 @@ +--- +id: bitesize-introduction +title: About Bitesize Samples +--- + +The Bitesize Samples repository provides a series of sample code as modules to use in your games and better understand Netcode for GameObjects (Netcode). + +* [2D Space Shooter Sample](bitesize-spaceshooter.md) - Learn more about physics movement and status effects using Netcode `NetworkVariables` and `ObjectPooling`. +* [Invaders Sample](bitesize-invaders.md) - Learn more about game flow, modes, unconventional movement networked, and a shared timer. +* [Client Driven Sample](bitesize-clientdriven.md) - Learn more about Client driven movements, networked physics, spawning vs statically placed objects, object reparenting + +## Requirements + +You need Unity and Netcode for GameObjects installed to work with these samples. See [Install Netcode for GameObjects ](../../installation/installation.md) for details. + +## Get the samples + +### Get the project files + +Download the project files from the [Bitesize Samples Repository](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize) + +![how to download](/img/bitesize/bitesize-download.png) + +After download, unzip the archive file. You are now ready to add the project to Unity Hub. + +### Add a sample to the Unity Hub + +1. Open Unity Hub. +1. Click **Add**. +1. Navigate to the unzipped folder. select the one of the projects in the `Basic` folder to add the respective project. + +:::important Compatibility +The Bitesize Samples have been built for a specific Unity version. You can see the version after adding a sample to the Unity Hub or in the description of the [repository](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize). We recommend using the same Unity version to avoid potential issues. +::: + +## Troubleshooting + +**Error building** + +*Error:* Error building Player: Currently selected scripting backend (IL2CPP) is not installed. + +Currently, you may need to have [Unity IL2CPP](https://docs.unity3d.com/Manual/IL2CPP.html) installed. Bitesize Samples should not require IL2CPP, and may have updates to resolve this error. diff --git a/versioned_docs/version-1.0.0/learn/bitesize/bitesize-invaders.md b/versioned_docs/version-1.0.0/learn/bitesize/bitesize-invaders.md new file mode 100644 index 000000000..3fe7ee7a4 --- /dev/null +++ b/versioned_docs/version-1.0.0/learn/bitesize/bitesize-invaders.md @@ -0,0 +1,129 @@ +--- +id: bitesize-invaders +title: Invaders Sample +description: Learn more about game flow, modes, unconventional movement networked, and a shared timer using Netcode for GameObjects. +--- + +The [Invaders Sample Project](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders) to understand the game flow and modes with Netcode for GameObjects (Netcode) using Scene Management, Unconventional Movement Networked, and a Shared Timer between clients updated client-side with server side seeding. + +## Game Flows + +Most Multiplayer games have multiple Networked Scenes, where players can join, communicate, and progress through scenes and maps together. This is a game flow: players join and establish communication together, the server determines the next scene or map, and transitions all clients to the new scene and loads the required map. This ensures players can play together. + +The logic and transitions are a specified game flow. To transition in a smooth manner, you need to create game flows and back-end systems that support those flows. + +Invaders implements this game-flow by creating different controller classes that handle each Game Mode such as MainMenu, a simple Networked Lobby and InGame modes, and other support classes that help with the transition from one Game Mode to another. + +The backbones of the flow/system mentioned above is consisting of two main components: + +* `SceneTransitionHandler` +* `SceneState` +* `Lobby Controller` + +### SceneTransitionHandler + +A `SceneTransitionHandler` with a lightweight state machine allows you to track clients' progress in regards to Scene Loading. It notifies the server when clients finish loading so that the other listeners are informed, by subscribing to the `NetworkedSceneManager` load events and creating a wrapper around it that others can subscribe to. + +Those events are invoked by `NetworkSceneManager` during the loading process. Invaders subscribe to these events when strating the server in the [MenuControl](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/MenuControl.cs) via the [SceneTransitionHandler.cs](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/SceneTransitionHandler.cs): + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/MenuControl.cs#L16-L30 +``` + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/SceneTransitionHandler.cs#L90-L97 +``` + +### SceneState + +At the same time, we have implemented a light State Machine to keep track of the current `SceneState`. For example, the `SceneState` could indicate if players are in the Init or Bootstrap scene, Start or Lobby, or InGame. You can run a different Behavior or in this case a different `UpdateLoop` function, for each state. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/SceneTransitionHandler.cs#L25-L34 +``` + +One example of how to update the current `SceneState` is in *[InvadersGame.cs](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/InvadersGame.cs)*, in the `OnNetworkSpawn` function. + +:::note +This class has the same role as the Lobby Controller, it acts as a Manager, for a specific part of the game. +::: + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/InvadersGame.cs#L156-L194 +``` + +### Lobby Controller + +A Lobby Controller is a Manager for the lobby. This is where we applied a simple Mediator Design Pattern that restricts direct communications between the objects and forces them to collaborate only using a moderator object. In this case, the *[LobbyControl.cs](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/LobbyControl.cs)* handles Lobby interactions and state. This works hand-in-hand with the `SceneTransitionHandler`, by subscribing to the `OnClientLoadedScene` of that class in `OnNetworkSpawn`. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/LobbyControl.cs#L23-L45 +``` + +Whenever the `OnClientLoadedScene` callback is called, the custom `ClientLoadedScene` function is also called. And that is the location where you add the new Player to a container that just loaded the Lobby Scene, generates user stats for it (which is just a random name), and then later sends an update to the rest of the users notifying them that someone new has joined the Lobby. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/LobbyControl.cs#L90-L107 +``` + +When the players join this Lobby, they all need to click **Ready** before the game can progress to the next scene (before the Host can start the game). After players click Ready, you send a `ServerRPC` called `OnClientIsReadyServerRpc` (inside the `PlayerIsReady` function). When it arrives server-side, it marks the client state as ready based on its `ClientId`. You keep track of if a client is ready in the `m_ClientsInLobby` `Dictionary`. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/LobbyControl.cs#L195-L209 +``` + +At the same time, in order to sync up with the rest of the clients and update their UI, we send a ClientRpc. The update is handled by the ClientRpc called `SendClientReadyStatusUpdatesClientRpc` in `UpdateAndCheckPlayersInLobby`. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/LobbyControl.cs#L126-L144 +``` + +When all the players have joined the lobby and are ready, `UpdateAndCheckPlayersInLobby` calls `CheckForAllPlayersReady` to transition to the next scene. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/LobbyControl.cs#L146-L174 +``` + +## Unconventional Networked Movement + +Invaders has an easy movement type - moving only on one (horizontal) axis - which allows you to only modify the transform client-side without waiting for server-side validation. You can find where we perform the move logic in *[PlayerControl.cs](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/PlayerControl.cs)* in the `InGameUpdate` function . With the help of a [`NetworkTransform`](../../components/networktransform.md) that is attached directly to the Player Game Object, it will automatically sync up the Transform with the other clients. At the same time, it will smooth out the movement by interpolating or extrapolating for all of them. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/PlayerControl.cs#L176-L193 +``` + +## Shared Start/Round Timer updated Client-Side + +Games commonly have timers to display in the UI such as Start Timer, Round Timer, and Cooldowns. The Invaders sample also has a shared timer to ensure all players start the game at the same time. Otherwise, players with higher-end devices and better network access may have an unfair advantage by loading scenes and maps faster. + +When you implement this kind of timer, usually you would use a `NetworkVariable` to replicate and display the exact time value across all clients. To improve performance, you do not need to replicate that float every Network Tick to the Clients, which would only waste network bandwidth and some minimal CPU resources. + +An alternative solution is to sync only the start of the timer to the clients, and afterwards only sync the remaining value of the timer when a new client joins. For the remaining time, clients can update the timer locally. This method ensures the server does not need to send the value of that timer every Network Update tick since you know what the approximated value will be. + +In Invaders we chose the second solution instead, and simply start the timer for clients via an RPC. + +### Start the game timer + +First, use `ShouldStartCountDown` to start the timer and send the time remaining value to the client-side. This initiates and sends the value only once, indicating the game has started and how much time remains. The game then counts down locally using these values. See [Update game timer Client-Side](#update-game-timer-client-side). + +Example code to start the countdown: + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/InvadersGame.cs#L205-L229 +``` + +In the case of a late-joining client, if the timer is already started, we send them an RPC to tell them the amount of time remaining. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/InvadersGame.cs#L196-L203 +``` + +### Update game timer Client-Side + +On the client-side, use the `UpdateGameTimer` to locally calculate and update the `gameTimer`. The server only needs to be contacted once to check if the game has started (`m_HasGameStared` is true) and the `m_TimeRemaining` amount, recieved by `ShouldStartCountDown`. When met, it locally calculates and updates the `gameTimer` reducing the remaining time on the client-side for all players. When `m_TimeRemaining` reaches 0.0, the timer is up. + +Example code to update the game timer: + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/Invaders/Assets/Scripts/InvadersGame.cs#L276-L299 +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/learn/bitesize/bitesize-spaceshooter.md b/versioned_docs/version-1.0.0/learn/bitesize/bitesize-spaceshooter.md new file mode 100644 index 000000000..0b4cdbc8c --- /dev/null +++ b/versioned_docs/version-1.0.0/learn/bitesize/bitesize-spaceshooter.md @@ -0,0 +1,70 @@ +--- +id: bitesize-spaceshooter +title: 2D Space Shooter Sample +description: Learn more about physics movement and status effects using Netcode for GameObjects (Netcode) NetworkVariables and ObjectPooling . +--- + +The [2D Space Shooter Project](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/tree/master/Basic/2DSpaceShooter) provides examples of physics, player health, and status effects using Netcode for GameObjects (Netcode). Technical features include[NetworkVariable](../../basics/networkvariable.md) and [ObjectPooling](../../advanced-topics/object-pooling.md). + +## Server Authorative Physics Movement + +The movement in 2DSpaceShooter is physics based. The player object is a dynamic rigidbody and can collide with other players or asteroids. Physics in multiplayer games can be hard to get right. For simplicity, 2DSpaceShooter runs all movement and physics just on the server-side. + +The client sends inputs in the form of RPCs to the server. The server then uses those inputs to adjust the throttle and turn values of the player. + +This method of running physics makes sure that there are no desyncs or other physics issues between the client and server, but it introduces more latency. + +## Player Health + +2DSpaceShooter uses `NetworkVariable`s to track the players health and energy. Both variables are server authorative, only the host or server can make changes to them. The client draws the player's health bar simply by accessing the value of the `NetworkVariable`. + +For example: + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/2DSpaceShooter/Assets/Scripts/ShipControl.cs#L488-L490 +``` + +## Power-ups and Status Effects + +The 2DSpaceShooter sample has power-ups which apply different status effects to a player on collection. The core implementation of the power up effects in `ShipControl.cs` is very simplistic. + +The power-ups themselves are server authorative. On the server they check if a player has entered their trigger and then apply a timed status effect to that player and disappear. + +The `ShipControl.cs` of the player object tracks each status effect. `NetworkVariable`s are used as duration timers to control the beginning and end of status effects. You could also use regular floats for timers. By using `NetworkVariable`s, the client can use this information to display different graphics based on active buffs to players. + +```csharp reference +https://github.com/Unity-Technologies/com.unity.multiplayer.samples.bitesize/blob/master/Basic/2DSpaceShooter/Assets/Scripts/ShipControl.cs#L45-L51 +``` + +## NetworkObject Pooling + +The `2DSpaceShooter` object creates many objects dynamically at runtime including bullets, asteroids, and pickups. 2DSpaceShooter uses object pooling to avoid performance issues of instantiating and destroying Unity Objects all the time and creating allocations in the process. + +2DSpaceShooter uses the NetworkObjectPool script, which can be found in the Community Contributions Repository. + +![pool img](/img/bitesize/invader-networkobjectpool.png) + +All of the runtime spawnable objects have been registered to the pool. On the client-side, this will cause Netcode to use an object from the pool instead of instantiating a new Object. When the `NetworkObject` is despawned, it will be automatically returned to the pool instead of getting destroyed. + +Adding the `NetworkObjectPool` to the scene will not yet pool server objects because these must be manually created and then spawned by the user. Instead of instantiating objects, your code should take them from the pool. + +Regular Netcode Spawn Code example: + +```csharp +GameObject powerUp = Instantiate(m_PowerupPrefab); +powerUp.GetComponent().Spawn(null, true); +``` + +Pooled Netcode Spawn Code example: + +```csharp +GameObject powerUp = m_ObjectPool.GetNetworkObject(m_PowerupPrefab); +powerUp.GetComponent().Spawn(null, true); +``` + + + +:::tip +If you are using Unity 2021, you can use the built-in [Object Pooling API](https://docs.unity3d.com/2021.1/Documentation/ScriptReference/Pool.ObjectPool_1.html) instead to build your own object pools. +::: + diff --git a/versioned_docs/version-1.0.0/learn/bossroom/bossroom-actions.md b/versioned_docs/version-1.0.0/learn/bossroom/bossroom-actions.md new file mode 100644 index 000000000..250a74152 --- /dev/null +++ b/versioned_docs/version-1.0.0/learn/bossroom/bossroom-actions.md @@ -0,0 +1,57 @@ +--- +id: bossroom-actions +title: Boss Room Actions Walkthrough +--- +import ImageSwitcher from '@site/src/ImageSwitcher.js'; + +Boss Room's actions each use a different pattern for good multiplayer quality. This doc walks you through each of them and goes into details about how we implemented each and what lessons you can learn from each. You can get their implementations [here](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/tree/main/Assets/Scripts/Gameplay/Action) + +
+ +
Playing an anticipatory animation on the owner client to appear reactive and hide Network Latency
+
+ + + +
+ +
Boss Room's mage's bolt doesn't use NetworkVariables and NetworkObjects to track the bolt's state. Since its movement is very fast, we only send an RPC to trigger VFX on clients. No need to waste CPU and bandwidth on a NetworkObject over time for this. Even if the FX passes through a wall on some clients (due to network discrepancies in target positions), the FX is so quick it wouldn't be visible to players.
+
+ +
+ +
Boss Room's archer's arrows use fully replicated NetworkObjects + NetworkTransform. Since they are slow moving, we want them to be seen by late joining players. We also want to make sure their behaviour is the same for all clients (so they don't go through walls for example). This will use more bandwidth, but will be more accurate.
+
+ +
+ +
The archer's volley takes multiple steps. First on click, the client will show a circle VFX tracking the mouse. That FX is not networked and client side only. Then on click, the client will send a ServerRPC to the server. The server will then apply it's gameplay logic, update the imp's health (tracked by NetworkVariables) and trigger a Client RPC to play the volley animation on all clients.
+
+ + + +
+ +
Emotes only use RPCs. We don't care if a late joining player doesn't see other player's emotes.
+
+ +
+ +
Most of the rogue sneak's logic happens server side. Since Boss Room is a coop game, we're not using Network invisibility here, only client side effects. Clients will still receive that invisible player's information and imp AIs will ignore invisible players.
+
+ + + + diff --git a/versioned_docs/version-1.0.0/learn/bossroom/getting-started-boss-room.md b/versioned_docs/version-1.0.0/learn/bossroom/getting-started-boss-room.md new file mode 100644 index 000000000..de248940c --- /dev/null +++ b/versioned_docs/version-1.0.0/learn/bossroom/getting-started-boss-room.md @@ -0,0 +1,205 @@ +--- +id: bossroom +title: Getting Started with Boss Room +description: Learn more about installing and running the Boss Room game sample. +--- + +![Boss Room banner](/img/banner.png) + +Boss Room is a fully functional co-op multiplayer RPG made with Unity Netcode. It is an educational sample designed to showcase typical netcode patterns that are frequently featured in similar multiplayer games. + +PLEASE NOTE: Boss Room is compatible with the latest Unity Long Term Support (LTS) editor version, currently 2021 LTS. Please include standalone support for Windows/Mac in your installation. + + +## Download the project files + +1. Go to the Multiplayer Samples Co-Op [Latest Release](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/releases/latest) on GitHub. +1. Click on `Project.zip` to automatically start downloading the folder. +1. Unzip the Project zip file. It unzips a folder named `com.unity.multiplayer.samples.coop-`. +:::note Windows users +Using Windows' built-in extracting tool may generate an "Error 0x80010135: Path too long" error window which can invalidate the extraction process. As a workaround, shorten the zip file to a single character (for example *c.zip*) and move it to the shortest path on your computer (such as in root C:\) and retry. If that solution fails, another workaround is to extract the downloaded zip file using an application like 7zip. +::: +1. You may choose to move your unzipped folder to a new location. My default location is my `Downloads` folder that I regularly clean out, so I moved the folder to my desktop. +1. You can now add the Boss Room project to your Unity Hub. + +:::important Compatibility +Boss Room has been developed and tested on the following platforms: + +* Windows +* Mac +* iOS +* Android +Boss Room's min spec devices are: + +* iPhone 6S +* Samsung Galaxy J2 Core +::: + +## Add the project with Unity Hub + +1. Open your Unity Hub. +1. Click the dropdown arrow next to **Open**, then select **Add project from disk**. +1. Select the root folder of the downloaded project. For example, `com.unity.multiplayer.samples.coop-`. + +:::note +The first time you open the project, Unity will import all assets, which will take longer than usual - this is normal. The Unity Netcode for GameObjects package will also be installed with Boss Room. + +**Issues with importing due to parental control software**: If you have issues with importing you may want to check your DNS settings as some ISP parental controls may block GitHub access. For example, see this information on [WebSafe](https://community.virginmedia.com/t5/Networking-and-WiFi/Web-Safe-Breaks-GitHub/td-p/4279652). +::: + +## Register the project with Unity Gaming Services (UGS) + +This project leverages several services from UGS to facilitate connectivity between players. To use these services inside your project, you must first [create an organization](https://support.unity.com/hc/en-us/articles/208592876-How-do-I-create-a-new-Organization-) inside the **Unity Dashboard**, and enable both the [Relay](https://docs.unity.com/relay/get-started.html) and [Lobby](https://docs.unity.com/lobby/game-lobby-sample.html) services. + +## Open the project + +To open the project for the first time: + +1. In your Unity Hub, double-click the project. +1. Navigate to the Editor window. +2. Then under the **Project** tab, go to **Assets** > **Boss Room** > **Scenes** and double-click on the **Startup** scene. +3. Click **Play**. The Boss Room menu scene loads. + +## Test multiplayer + +To see the multiplayer functionality in action, you can either run multiple instances of the game [locally on your computer](#local-multiplayer-setup) or choose to [connect through the internet](#multiplayer-over-internet). + +## Local multiplayer setup + +For a local multiplayer setup, you must build an executable and launch several instances of this executable to both host and join a game. + +1. With the Boss Room project open in your Unity editor, click **File** > **Build Settings** > **Build**. +2. Save the binary as `Boss Room`. + +After the build has completed, you can launch several instances of the built executable to both host and join a game. + +:::important Mac Users +To run multiple instances of the same app, you need to use the command line: +1. First, change your directory to the folder where you saved the Boss Room executable. For example, `cd Desktop/com.unity.multiplayer.samples.coop-`. +2. Run the command `Open -n YourAppName.app`. If you saved the app as `BossRoom`, your command is `Open -n BossRoom.app`. However, if you saved your app as `Boss Room` with a space, your command needs to include quotation marks ("") around the executable name: `Open -n "BossRoom.app"`. +::: + +## Multiplayer over internet + +In contrast to running a local setup, when playing over internet we do not necessarily need a built executable. You can run the game in editor. + +Running the game over internet currently requires using [Port Forwarding](#port-forwarding) or [Integrating Boss Room with Unity Gaming Services](#integrating-boss-room-with-unity-gaming-services). + +### Port Forwarding + +The [Portforward Site](https://portforward.com/) has guides on how to enable port forwarding on a huge number of routers. Boss Room uses UDP and needs a 9998 external port to be open. + +import Iframe from 'react-iframe' + +### Integrating Boss Room with Unity Gaming Services + +With the release of Boss Room 1.1.0, Boss Room integrated with Unity Gaming Services (UGS): [Authentication](https://docs.unity.com/authentication/IntroUnityAuthentication.html), [Relay](https://docs.unity.com/relay/introduction.html), and [Lobby](https://docs.unity.com/lobby/unity-lobby-service-overview.html). These services make it easy for players to host and join games that are playable over the internet, without the need for port forwarding or out-of-game coordination. + +#### Authentication + +To interact with the rest of UGS, the user must be authenticated. Therefore, authentication is kicked off as soon as the game launches and the main menu scene loads. + +:::note +The Authentication service supports [anonymous sign-in](https://docs.unity.com/authentication/UsingAnonSignIn.html) and doesn't require any additional input from the player. +::: + +The Authentication API doesn't distinguish multiple instances of the same project running on the same machine and logs in the same user in all those different instances. Both ParrelSync clones and actual game builds are affected and can mess up testing the game locally. + +However, Authentication supports [Profiles](https://docs.unity.com/authentication/ProfileManagement.html) that allows different users existing on the same physical machine. To test locally, we need both builds and editor players to be able to switch to different Profiles. + +The [`ProfileManager`](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/Utils/ProfileManager.cs) class wraps the logic for deciding what Profile you should be using, if any. In builds, the command-line argument `-AuthProfile` specifies the new profile id. When iterating in the editor, ParrelSync can use its `CloneManager` custom arguments to decide what user profile to use. Users can also change profile using the in-game menu. + +`ProfileManager.Profile` generates the custom `InitializationOptions`: + +``` +var unityAuthenticationInitOptions = new InitializationOptions(); +var profile = ProfileManager.Profile; + + +if (profile.Length > 0) +{ + unityAuthenticationInitOptions.SetProfile(profile); +} + +``` + +The code that executes profile switch and sign-in logic itself is as follows: + +``` +async Task TrySignIn(InitializationOptions initializationOptions) +{ + await Unity.Services.Core.UnityServices.InitializeAsync(initializationOptions); + + if (!AuthenticationService.Instance.IsSignedIn) + { + await AuthenticationService.Instance.SignInAnonymouslyAsync(); + } +} +``` + +Next is lobby and relay. + +#### Lobby and Relay + +##### The Lobby Host Flow + +1. The would-be host enters the lobby name, specifies if it's public or private and hits the **Create** button. +1. The [Lobby creation API](https://docs.unity.com/lobby/creating-a-lobby.html) call is made. The newly created lobby is **locked** (i.e prevented from appearing in the list of publicly available, fully set up games that are ready to be joined) until we successfully complete the relay allocation and Netcode startup steps below. +1. The host requests a relay allocation from the [Relay service](https://docs.unity.com/relay/introduction.html). +2. [UTP](../../../transport/about.md)) starts and the host is switches to the character selection scene. The lobby itself is now considered unlocked and is available for other clients to join. + +##### The Lobby Client Flow +* There are several ways to connect to a lobby: + * Choose one of the public lobbies regularly fetched from the Lobby service + * [Quickjoin](https://docs.unity.com/lobby/quick-join.html): Randomly selects a public lobby + * Using a [lobby key](https://docs.unity.com/lobby/joining-lobbies.html), shared through out-of-game means. This works for both public and private lobbies. +* After joining a lobby, the [relay join code passes through lobby metadata](https://docs.unity.com/lobby/relay-integrations.html) to connect to the host via UTP Relay transport. +* The host receives a request to approve the connecting client, and the host would server-authoritatively switch the player to the appropriate scene. + +Currently, the Lobby service has to be [polled for updates](https://docs.unity.com/lobby/polling-for-lobby-state.html). This is not ideal for a responsive feel to character selection; however, when there is an option to get real time updates from the Lobby service, it would be a good alternative way to implement something like this. + +##### Disconnection and Reconnection + +Handling player disconnections and reconnections is a necessity in a multiplayer game. + +Boss Room uses a [session management](../../advanced-topics/session-management.md) system that ensures when a player disconnects, some data is kept and accurately assigned back to that player if or when they reconnect (see [SessionManager.cs – OnClientDisconnect](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Packages/com.unity.multiplayer.samples.coop/Utilities/Net/SessionManager.cs)). + +The way Boss Room handles restoration of user data on reconnection can be found in [SessionManager.cs - SetupConnectingPlayerSessionData](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Packages/com.unity.multiplayer.samples.coop/Utilities/Net/SessionManager.cs), which is called as a part of a connection approval check that is handled by the host (see [ServerGameNetPortal.s – ApprovalCheck](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/Gameplay/ConnectionManagement/ServerGameNetPortal.cs)). + +:::important +It's important to promptly remove disconnected players from the lobby. Otherwise, the disconnected player cannot rejoin the lobby because they are still considered in it. +::: + +When a player [disconnects from Relay](https://docs.unity.com/relay/disconnection.html), eventually the Lobby and Relay service integration (necessary before we run UTP connection) kicks out the disconnected players. However, the timeout for disconnect is quite long (~2 minutes), and we do not rely solely on this mechanism. + +To make the process of leaving lobby more reliable, there are several additional cleanup mechanisms: +* The client code contains application quit logic (see [ApplicationController.cs - OnWantToQuit and LeaveSession](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/ApplicationLifecycle/ApplicationController.cs)) that sends a request to remove the player from the lobby +* The host has special logic that removes the disconnected player from the lobby as soon as the host knows about it (`NetworkManager.OnClientDisconnectCallback`). This is helpful when the client has crashed and couldn't send a "leave lobby" request. + * For this to work, the host uses `SessionManager` to store the mapping between UGS playerId and their NGO clientId. You can find this logic in [ServerGameNetPortal.cs - OnClientDisconnect](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/Gameplay/ConnectionManagement/ServerGameNetPortal.cs). +* Lastly, the client contains checks that determine if the host has left the lobby, and if so, the client leaves the lobby too. The code for this can be found at [ClientGameNetPortal.cs - OnDisconnectOrTimeout](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/Gameplay/ConnectionManagement/ClientGameNetPortal.cs). + +## Troubleshooting + +**Errors finding Git installation** + +If you receive an OS or Unity error trying to locate Git after updating or installing Git, you need to fully restart your computer. Restarting only Unity may not fully update system information to correctly locate the install. + +**Windows Error 0x80010135: Path too long** + +Using Windows' built-in extracting tool may generate an "Error 0x80010135: Path too long" error window which can invalidate the extraction process. As a workaround, shorten the zip file to a single character (for example *c.zip*) and move it to the shortest path on your computer (such as in root C:\) and retry. If that solution fails, another workaround is to extract the downloaded zip file using an application like 7zip. + +**Run builds on Mac OSX gives "unidentified developer"** + +If you attempt to run a build on OSX and receive a warning dialog mentioning an "unidentified developer", you may need to override your security settings for this application: + +1. In the Finder on your Mac, locate the application you want to open. + + :::note + Do not use Launchpad, it does not allow you to access the shortcut menu. + ::: + +1. Control-click the app icon, then choose **Open** from the shortcut menu. +1. Click **Open**. +1. The app is saved as an exception to your security settings. You can open it in the future by double-clicking it just as you can any registered app. + +See [Apple Support](https://support.apple.com/guide/mac-help/open-a-mac-app-from-an-unidentified-developer-mh40616/mac) for details. diff --git a/versioned_docs/version-1.0.0/learn/bossroom/networkobject-parenting.md b/versioned_docs/version-1.0.0/learn/bossroom/networkobject-parenting.md new file mode 100644 index 000000000..6b203bfbe --- /dev/null +++ b/versioned_docs/version-1.0.0/learn/bossroom/networkobject-parenting.md @@ -0,0 +1,23 @@ +--- +id: networkobject-parenting +title: NetworkObject Parenting inside Boss Room +description: Learn about Boss Room's approach to NetworkObject parenting. +--- +:::note +Required reading: [NetworkObject Parenting](../../advanced-topics/networkobject-parenting.md) +::: + +Before detailing Boss Room’s approach toon `NetworkObject` parenting, it’s important to highlight a limitation of Netcode: A dynamically-spawned `NetworkObject` **cannot** contain another `NetworkObject` in its hierarchy. If you spawn such a `NetworkObject`, you cannot spawn children `NetworkObjects`. You can only add children `NetworkObject` components to a `NetworkObject` that is part of a scene. + +Boss Room leverages `NetworkObject` parenting through the server-driven `PickUp` action (see [`PickUpAction.cs`](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/Gameplay/Action/ConcreteActions/PickUpAction.cs)), where a character has the ability to pick up a specially-tagged, in-scene placed `NetworkObject` (see [`PickUpPot` prefab](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Prefabs/Game/PickUpPot.prefab)]. + +At its root, `PickUpPot` contains a `NetworkObject`, a `NetworkTransform`, and a `PositionConstraint` component. `AutoObjectParentSync` is enabled on its `NetworkTransform` (as is by default) so that: + +1. The `NetworkObject` can verify server-side if parenting a Heavy object to another `NetworkObject` is allowed. +2. The `NetworkObject` can notify us when the parent has successfully been modified server-side. + +To accommodate the limitation highlighted at the beginning of this document, Boss Room leverages the `PositionConstraint` component to simulate an object following a character’s position. + +A special hand bone has been added to our Character’s avatar. Upon a character’s successful parenting attempt, this special bone is set as the `PickUpPot`’s `PositonConstraint` target. So while the `PickUpPot` is technically parented to a player, the `PositionConstraint` component allows the `PickUpPot` to follow a bone’s position, presenting the **illusion** that the `PickUpPot` is parented to the player’s hand bone itself. + +Once the `PickUpPot` is parented, local space simulation is enabled on its [`NetworkTransform` component](../../components/networktransform.md). diff --git a/versioned_docs/version-1.0.0/learn/bossroom/networkrigidbody.md b/versioned_docs/version-1.0.0/learn/bossroom/networkrigidbody.md new file mode 100644 index 000000000..a69500486 --- /dev/null +++ b/versioned_docs/version-1.0.0/learn/bossroom/networkrigidbody.md @@ -0,0 +1,12 @@ +--- +id: networkrigidbody +title: NetworkRigidbody inside Boss Room +description: Learn how Boss Room leverages NetworkRigidbody. +--- +:::note +Required reading: [Physics](../..//advanced-topics/physics.md) +::: + +Boss Room leverages `NetworkRigidbody` to simulate physics-based projectiles. See the Vandal Imp’s tossed projectile, the [`ImpTossedItem` prefab](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Prefabs/Game/ImpTossedItem.prefab). At its root, this prefab contains a `NetworkObject`, a `NetworkTransform`, a `Rigidbody`, and a `NetworkRigidbody` component. Refer to [`TossAction.cs`](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/Gameplay/Action/ConcreteActions/TossAction.cs) for more implementation details. + +An important note: Any modifications to a `Rigidbody` that involve Physics (that is, modifying velocity, applying forces, applying torque, and the like) must be done **after** the `NetworkObject` is spawned since `NetworkRigidbody` forces the Rigidbody’s `isKinematic` flag to be true on `Awake()`. Once spawned, this flag is modified depending on the ownership status of the `NetworkObject`. diff --git a/versioned_docs/version-1.0.0/learn/bossroom/spawn-networkobjects.md b/versioned_docs/version-1.0.0/learn/bossroom/spawn-networkobjects.md new file mode 100644 index 000000000..eac9be7a3 --- /dev/null +++ b/versioned_docs/version-1.0.0/learn/bossroom/spawn-networkobjects.md @@ -0,0 +1,27 @@ +--- +id: spawn-networkobjects +title: Dynamically spawning NetworkObjects in Boss Room to Resolve Zombie NetworkObjects +description: Learn how to dynamically spawn NetworkObjects in Boss Room to resolve zombie NetworkObjects. +--- +:::note +Required reading: [Object Spawning](../../basics/object-spawning.md). +::: + +This document serves as a walkthrough of Boss Room’s approach to solving the following issue: Late-joining clients entering networked sessions encountering zombie `NetworkObjects`. Zombie `NetworkObjects` represent `NetworkObjects` that are instantiated for a client due to scene loads but are not despawned or destroyed by Netcode. + +This is a particular Netcode limitation of `NetworkObject` spawning: `NetworkObjects` that belong to a scene object should not be destroyed until its scene has been unloaded through Netcode’s scene management. + +The scenario in question: + +* A host loads a scene and destroys a `NetworkObject` that belonged to that scene. +* A client joins the host’s session and loads the additive scene. This operation loads **all** the `GameObjects` included in the additive scene. The `NetworkObject` that was destroyed on the server will not be destroyed on the client’s machine. + +This scenario manifested inside Boss Room, whereby late-joining clients joining a game session encountered zombie `NetworkObject`s that were not destroyed over the network. + +Additive scenes now contain prefab instances of a custom spawner, [`NetworkObjectSpawner`](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Packages/com.unity.multiplayer.samples.coop/Utilities/Net/NetworkObjectSpawner.cs) to accommodate this visual inconsistency. + +Compositionally, these additive scenes now only contain the following: + +* Prefab instances of level geometry. +* Prefab instances of `NetworkObject`s that will **not** be despawned nor destroyed for the scene’s lifetime. Examples include [BreakablePot](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Prefabs/Game/BreakablePot.prefab) and [BreakableCrystal](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Prefabs/Game/BreakableCrystal.prefab). +* Prefab instances of `NetworkObjectSpawner`, which spawn `NetworkObject`s that **may** be destroyed or despawned during the scene’s lifetime. Examples include [Imp](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/GameData/Character/Imp/Imp.asset), [VandalImp](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/GameData/Character/VandalImp/VandalImp.asset), and [ImpBoss](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/GameData/Character/ImpBoss/ImpBoss.asset). diff --git a/versioned_docs/version-1.0.0/learn/clientside-interpolation.md b/versioned_docs/version-1.0.0/learn/clientside-interpolation.md new file mode 100644 index 000000000..18a185879 --- /dev/null +++ b/versioned_docs/version-1.0.0/learn/clientside-interpolation.md @@ -0,0 +1,42 @@ +--- +id: clientside_interpolation +title: Client-side Interpolation +description: Guide covering the basics of lag mitigation and a way to produce smooth gameplay. +--- + +As we discussed in [Lag and Packet Loss](lagandpacketloss.md) - latency is our enemy, with [Jitter](lagandpacketloss#jitter) being the chaotic element that adds complexity to our task of producing "smooth" gameplay experience. + +If we just accept the fact that latency exists, but chose not to do anything about it - we would implement what is known as "dumb terminal". Dumb Terminals do not need to understand anything about the simulation they are visualizing for the client - all they do is: + +* Send inputs from Clients to the Server +* Receive the resulting state from the Server and render it appropritely + +This is a conservative approach that makes no attempt to mitigate delay, but also never shows an incorrect user state. The problems with this approach is that not only will the user feel the latency, the frequency of updates from the server would dictate how choppy our gameplay experience is for the clients. In effect, regardless of the potential framerate that the client could achieve, the game would only run at the cadence the server (with its limiting networking factors) is capable of. This could reduce a good 60 FPS experience into a bad 15 FPS experience with perceivable input lag. + +Not only does this approach cause some unresponsiveness (which may be acceptable in certain game genres), it also makes it more difficult to aim at other players. The non-up-to-date rendering of the world forces the player to aim ahead of their target to compensate for lag. As a worst case scenario, the player could be legitimately aiming at the enemy player, but due to the fact that the enemy was actually a 100-150ms "ahead" (as in forward in time, not necessarily ahead in a positional sense) of what is being rendered, they may be unable to hit the enemy unless he runs predictably in a straight line. + +Now throw in some chaos by means of [RTT fluctuations](lagandpacketloss#round-trip-time-rtt) and [Jitter](lagandpacketloss#jitter), and we are getting into an unacceptable gameplay experience. + +Fortunately we can mitigate the effects of latency and jitter. + +## Client-Side Interpolation + +Visual choppiness is caused by infrequent (in comparison to the speed at which clients are rendering their screens) updates from the server and it could also be exasperated by bad network conditions causing jitter. We can employ **Client-Side Interpolation** to reduce this effect. + +In client-side Interpolation instead of just snapping objects to their positions that are transmitted from the server the client smoothly interpolates to this state over time. This approach is still conservative - the client just smoothens out the transition between valid states that were sent from the server. + +Normally a client in a server-authoritative topology, barring any additional tricks and techniques, would be able to render state that is approximately half the Round Trip Time (RTT) behind the actual state of simulation on the server. In order for client-side interpolation to be able to work it needs to be somewhat behind (catching up to) the most recent state passed to us from the server. In effect, our latency would increase by our [Interpolation Period](../reference/glossary/ticks-and-update-rates#interpolation-period). In order to avoid stutter, we want that period to be less than the [Packet Sending Period](../reference/glossary/ticks-and-update-rates#packet-sending-period). When the client is done interpolating to the previous state, it would always have received a new state to repeat the process. + +Client-side interpolation is implemented in Netcode for GameObjects (Netcode) in the [NetworkTransform](../components/networktransform.md) component. + +:::unity Future Netcode Feature +This implementation of Client-side Interpolation provides some improvement to the choppiness problem, but it does not completely solve the issues caused by jitter. + +An improvement that produces even smoother gameplay at the cost of even more added latency is Snapshot Interpolation, where instead of interpolating towards the most up-to-date state, we introduce a buffer that keeps several snapshots of incoming state and interpolates through them. This technique provides better handling of Jitter, but, again, it introduces slight additional latency on top of what we had in Clientside Interpolation. + +Snapshot Interpolation is not implemented in Netcode at this time. +::: + +## Boss Room Example + +In the [Boss Room sample](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/), NetworkTransform components are used for client-side interpolation. Since transforms are updated in FixedUpdate, however, there is also some server-side interpolation that is needed on the host to smooth out movement. See [ClientProjectileVisualization](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/Gameplay/GameplayObjects/ClientProjectileVisualization.cs) and [PositionLerper](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/blob/main/Assets/Scripts/Utils/PositionLerper.cs) for an example of how it is done. diff --git a/versioned_docs/version-1.0.0/learn/codemonkey/codemonkey-complete-tutorial.md b/versioned_docs/version-1.0.0/learn/codemonkey/codemonkey-complete-tutorial.md new file mode 100644 index 000000000..727eb42cb --- /dev/null +++ b/versioned_docs/version-1.0.0/learn/codemonkey/codemonkey-complete-tutorial.md @@ -0,0 +1,63 @@ +--- +id: codemonkey-complete +title: Complete Unity Multiplayer Tutorial (Netcode for Game Objects) +description: This Unity Multiplayer tutorial will teach you use Unity's Netcode For GameObjects to create a multiplaer game +--- + +This Unity Multiplayer video tutorial will teach you use Unity's Netcode For GameObjects to create a multiplaer game. + + + +### Add the clone to Unity Hub + + + + + +To add your clone project in Unity Hub version 3.0.0+: + +1. Open Unity Hub. +1. From the dropdown arrow between **Open** and **New project**, click **Add project from disk**. +1. Navigate to where the clone folder is saved, select `GoldenPath_<modulenumber>`, and click **Open**/**Select Folder**. + +The clone project should now appear in your projects list of the Unity Hub as `GoldenPath_<modulenumber>`. + + + + +To add your clone project in previous Unity Hub versions: + +1. Open Unity Hub. +2. Click **Add**. +3. Navigate to where the clone folder is saved, select `GoldenPath_<modulenumber>`, and click **Open**/**Select Folder**. + +The clone project should now appear in your projects list of the Unity Hub as `GoldenPath_<modulenumber>`. + + \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/shared/_create_commandline_helper.md b/versioned_docs/version-1.0.0/shared/_create_commandline_helper.md new file mode 100644 index 000000000..3fce3534c --- /dev/null +++ b/versioned_docs/version-1.0.0/shared/_create_commandline_helper.md @@ -0,0 +1,95 @@ +This command line helper will launch our project outside Unity and make testing builds easier. + +1. Right-click the **Assets** folder and create a new folder by hovering over **Create** and selecting **Folder**. Name it **Scripts**. +2. Create a script called `NetworkCommandLine` by right-clicking on your **Scripts** folder, hovering over **Create** and selecting **C# Script**. +3. In the **Hierarchy** menu, right-click on the `NetworkManager` and choose **Create Empty**. + + This will create an empty `GameObject` with `NetworkManager` as its parent. + +4. Rename this child `GameObject` `NetworkCommandLine`. +5. With the new `NetworkCommandLine` object selected, click **Add Component** from the **Inspector** tab. +6. Select **Scripts** from the drop-down and click on the `NetworkCommandLine.cs` script you created earlier. +7. Open the `NetworkCommandLine.cs` script by double-clicking from the **Project** tab > **Assets** > **Scripts**. It will open in your text editor +8. Edit the `NetworkCommandLine.cs` script to match the following: + +:::info How to Copy +We recommend that you use the **Copy** function in our code blocks to reduce errors when copying and pasting content. Hover over the block and select the **Copy** button that appears in the upper-right corner of the code block. +::: + +
+Click to show/hide the Code. + + + +``` csharp +using System.Collections.Generic; +using Unity.Netcode; +using UnityEngine; + +public class NetworkCommandLine : MonoBehaviour +{ + private NetworkManager netManager; + + void Start() + { + netManager = GetComponentInParent(); + + if (Application.isEditor) return; + + var args = GetCommandlineArgs(); + + if (args.TryGetValue("-mlapi", out string mlapiValue)) + { + switch (mlapiValue) + { + case "server": + netManager.StartServer(); + break; + case "host": + netManager.StartHost(); + break; + case "client": + + netManager.StartClient(); + break; + } + } + } + + private Dictionary GetCommandlineArgs() + { + Dictionary argDictionary = new Dictionary(); + + var args = System.Environment.GetCommandLineArgs(); + + for (int i = 0; i < args.Length; ++i) + { + var arg = args[i].ToLower(); + if (arg.StartsWith("-")) + { + var value = i < args.Length - 1 ? args[i + 1].ToLower() : null; + value = (value?.StartsWith("-") ?? false) ? null : value; + + argDictionary.Add(arg, value); + } + } + return argDictionary; + } +} +``` + +
+ +9. Paste the copied code into your code editor. +1. Save your changes. Your script will reload in the Unity Editor. +1. Back in the Editor, select **File** > **Build Settings** > **Player Settings...**. Beneath **Settings for PC, Mac, & Linux Standalone**, click **Resolution and Presentation** to open the section options. +1. From **Resolution** > **Fullscreen Mode**, change `Fullscreen Window` to `Windowed`. +1. Back to the Editor main window, save your scene. + + +:::tip + If you are using a Pro Unity license, you may want to disable the splash screen by unchecking **Splash Image** > **Splash Screen** > **Show Splash Screen**. +::: + + diff --git a/versioned_docs/version-1.0.0/shared/_create_networkmanager_and_transport.md b/versioned_docs/version-1.0.0/shared/_create_networkmanager_and_transport.md new file mode 100644 index 000000000..ce1fdc0d0 --- /dev/null +++ b/versioned_docs/version-1.0.0/shared/_create_networkmanager_and_transport.md @@ -0,0 +1,24 @@ +1. Right-click in the **Hierarchy** tab of your Unity Project Window. +1. Select **Create Empty**. +1. Rename the `GameObject` **NetworkManager**. + + :::note + We renamed the `GameObject` because: + * It makes it easier to refer to later. + * There should only be one **NetworkManager** object that contains the `NetworkManager` component. You may get unexpected results if you create more than one **NetworkManager**. + ::: + +You have created a new `GameObject` called **NetworkManager**. Now we will add the `NetworkManager` component and select the transport type. + +1. Select **NetworkManager**. +1. Click **Add Component** in the **Inspector** tab. +1. Select **Netcode* from the list. +1. Select `NetworkManager` component. +1. Inside the `NetworkManager` component tab, locate the `NetworkTransport` field. It may have a warning icon stating that a transport is required for Netcode to work. +1. From the **Select Transport...** dropdown, select `UnetTransport`. +1. Save your scene. + + + + diff --git a/versioned_docs/version-1.0.0/shared/_create_new_project.md b/versioned_docs/version-1.0.0/shared/_create_new_project.md new file mode 100644 index 000000000..a02fd440c --- /dev/null +++ b/versioned_docs/version-1.0.0/shared/_create_new_project.md @@ -0,0 +1,12 @@ + +1. Open the Unity Hub. +1. Click New. +1. Select type ‘3D’ +1. Rename the project 'GoldenPath'. + +:::note + For some of the Golden Path Training modules you may already have a project named `GoldenPath` for these cases we recommended you name the project `GoldenPath_` where `modulenumber>` is the current Golden Path Module number. +::: + +5. Select the location to save the project. + diff --git a/versioned_docs/version-1.0.0/shared/_create_spawn_for_player.md b/versioned_docs/version-1.0.0/shared/_create_spawn_for_player.md new file mode 100644 index 000000000..a5e9c172c --- /dev/null +++ b/versioned_docs/version-1.0.0/shared/_create_spawn_for_player.md @@ -0,0 +1,30 @@ +This section adds in a player object and spawns it for each connected player. + +1. Right-click in the **Hierarchy** tab of your Unity Project Window. +2. Select **3D Object** > **Capsule**, and rename it **Player**. +3. While **Player** is selected, add a `NetworkObject` component by clicking **Add Component** in the **Inspector** tab, select **Netcode**, then **NetworkObject**. +4. From the **Projects** tab, right-click the **Assets** folder, hover over **Create**, and select **Folder**. Name this folder **Prefabs**. +5. Drag your recently created **Player** object to your new **Prefabs** folder. This makes the **Player** object a [prefab](https://docs.unity3d.com/Manual/Prefabs.html). +6. Right-click and delete **Player** from the scene. + + :::tip + We remove **Player**, because we will be using the built-in functionality of the NetworkManager to spawn the player. Doing so will make the NetworkManager spawn a player object for each connecting client and automatically give that client ownership over their player object. + + If you do not remove **Player**, a player object will exist at scene load that doesn't react with the NetworkManager. + ::: +1. Select your `NetworkManager` object from the **Hierarchy** tab. +2. Go to the **Inspector** tab > **NetworkManager** component > **NetworkPrefabs**. +3. Click `+` to create a slot. +4. Drag the **Player** prefab from **Assets** > **Prefabs** to the new empty slot +5. 1. Drag the prefab also into the `Player Prefab` slot. + + :::important + When you drop the prefab into the `Player Prefab` slot, you are telling the library that when a client connects to the game, automatically spawn this prefab as the character for the connecting client. If you do not have any prefab set as the `Player Prefab` no player object will be spawned. + ::: + +5. Finish this section by right-clicking in the **Hierarchy** tab, hover over **3D Object**, select **Plane**. +6. Save your scene. + + + diff --git a/versioned_docs/version-1.0.0/shared/_test_spawn_for_player.md b/versioned_docs/version-1.0.0/shared/_test_spawn_for_player.md new file mode 100644 index 000000000..e143a1567 --- /dev/null +++ b/versioned_docs/version-1.0.0/shared/_test_spawn_for_player.md @@ -0,0 +1,7 @@ +Now we will test to see if everything works as expected. + +1. Click **Play**. A **DontDestroyOnLoad** scene will appear on the **Hierarchy** tab. +1. Select the **NetworkManager** object under **DontDestroyOnLoad**. Then click **Start Host** under **NetworkManager** component on the **Inspector** tab. A **Player(Clone)** object will appear under your sample scene on the **Hierarchy** tab. + + \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/shared/_testing_commandline_helper.md b/versioned_docs/version-1.0.0/shared/_testing_commandline_helper.md new file mode 100644 index 000000000..5bb3c1869 --- /dev/null +++ b/versioned_docs/version-1.0.0/shared/_testing_commandline_helper.md @@ -0,0 +1,114 @@ +Now we will test that the command line helper script works. + +1. Select **File** > **Build and Run**. +1. Create a new folder called `Build` inside your Golden Path project folder. +1. **Save As** the binary `GoldenPath`. +1. Your project will build and launch in a new window, and you should see the plane. +1. Quit your app. +1. Now to launch from the command line. + + + + + + +For Windows you should do the following: + + +1. Open your Command Prompt. +1. Enter the following. Be sure to change the noted section `< >` of **both** commands to your project. + +:::note +You may get a UAC prompt requesting permission for the binary to run you should allow it. +::: + + Server: + ``` + \Build\GoldenPath.exe -mlapi server + ``` + + Client: + ``` + \Build\GoldenPath.exe -mlapi client + ``` + + To run these commands on a single line: + ``` + GoldenPath\Build\GoldenPath.exe -mlapi server & GoldenPath\Build\GoldenPath.exe -mlapi client + ``` + + Example: + ``` + C:\Users\sarao>GoldenPath\Build\GoldenPath.exe -mlapi server & GoldenPath\Build\GoldenPath.exe -mlapi client + ``` + +:::important +On Windows, no standard out stream exists by default, so you will need to view the Debug.log file to see the outputs. You can find the Debug.log files in: + +`C:\Users\username\AppData\LocalLow\CompanyName\ProductName\Player.log` + +Where the `CompanyName` should default to `DefaultCompany` for a new project and `ProductName` should be equal to the project's name. + +Alternatively you can modify the Windows commands to create a log.txt file in the same folder as your **GoldenPath** folder. + +Modify the commands as follows: + + Server: + ``` + \Build\GoldenPath.exe -logfile log-server.txt -mlapi server + ``` + + Client: + ``` + \Build\GoldenPath.exe -logfile log-client.txt -mlapi client + ``` + + Example (Running as a single command line): + ``` + C:\Users\sarao>GoldenPath\Build\GoldenPath.exe -logfile -log-server.txt -mlapi server & GoldenPath\Build\GoldenPath.exe -logfile log-client.txt -mlapi client + ``` +::: + + + + + +For Mac you should do the following: + +1. Open Terminal. +2. Enter the following. Be sure to change the noted section `< >` of **both** commands to your project. + +Server +``` +/Build/GoldenPath.app/Contents/MacOS/ -mlapi server -logfile - +``` + +Client +``` +/Build/GoldenPath.app/Contents/MacOS/ -mlapi client -logfile - +``` + +Run both as a single command: +``` +/Build/GoldenPath.app/Contents/MacOS/ -mlapi server -logfile - & ; ~ /Build/GoldenPath.app/Contents/MacOS/ -mlapi client -logfile - +``` + +Example scene in video: + ``` + ~/dev/mlapi-golden-path/GoldenPath/Build/GoldenPath.app/Contents/MacOS/GoldenPath -mlapi server -logfile - & ; ~/dev/mlapi-golden-path/GoldenPath/Build/GoldenPath.app/Contents/MacOS/GoldenPath -mlapi client -logfile - + ``` + + + + + + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/troubleshooting/error-messages.md b/versioned_docs/version-1.0.0/troubleshooting/error-messages.md new file mode 100644 index 000000000..05152eff0 --- /dev/null +++ b/versioned_docs/version-1.0.0/troubleshooting/error-messages.md @@ -0,0 +1,31 @@ +--- +id: errormessages +title: Netcode for GameObjects (Netcode) Error Messages +--- + +Learn more about Unity error messages, including error collecting, issues that cause them, and how to handle. + +## Error Capturing + +Error messages are captured and returned through Unity Editor Diagnostics (required) and Roslyn Analyzers. + +* Unity ILPP and Editor errors are the source of truth. ILPP occurs in Unity and returns error messages, which prevents you from building/playing your game (hard compile errors). +* [Roslyn Analyzers](https://devblogs.microsoft.com/dotnet/write-better-code-faster-with-roslyn-analyzers/) provide immediate feedback within the IDE, without jumping back to Unity to let it compile with your new changes. + +## NetworkObject errors + +**Error:** +* `Cannot find pending soft sync object. Is the projects the same? UnityEngine.Debug:LogError(Object)` +* `ArgumentNullException: Cannot spawn null object Parameter name: netObject` + +This exception should only occur if your scenes are not the same, for example if the scene of your server contains a `NetworkObject` which is not present in the client scene. Verify the scene objects work correctly by entering playmode in both editors. + +## ServerRPC errors + +**Error:** +* Server: `[Netcode] Only owner can invoke ServerRPC that is marked to require ownership` +* Host: `KeyNotFoundException: The given key was not present in the dictionary.` + +The ServerRPC should only be used on the server. Make sure to add `isServer` check before calling. + +If the call is added correctly but still returns a `nullreferenceexception`, `NetworkManager.Singleton` may be returning `null`. Verify you created the `GameObject` with a `NetworkManager` component, which handles all initialization. `NetworkManager.Singleton` is a reference to a instance of the `NetworkManager` component. \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/troubleshooting/troubleshooting.md b/versioned_docs/version-1.0.0/troubleshooting/troubleshooting.md new file mode 100644 index 000000000..163eb7946 --- /dev/null +++ b/versioned_docs/version-1.0.0/troubleshooting/troubleshooting.md @@ -0,0 +1,43 @@ +--- +id: troubleshooting +title: Troubleshooting +--- + +See the following information for common troubleshooting for Netcode for GameObjects. + +## NullReferenceException when trying to start a server/host/client + +**Issue:** When trying to start a server, host, or client by executing one of these lines of code: + +```csharp +NetworkManager.Singleton.StartServer() +NetworkManager.Singleton.StartHost() +NetworkManager.Singleton.StartClient() +``` + +The following exception is thrown: + +```csharp +NullReferenceException: Object reference not set to an instance of an object +``` + +**Solution:** You most likely forgot to add the `NetworkManager` component to a game object in your scene. + +## NullReferenceException when trying to send an RPC to the server + +**Issue:** When the client tries to run `InvokeServerRpc`, the following exception is thrown: + +```csharp +NullReferenceException: Object reference not set to an instance of an object +``` + +**Solution:** You most likely forgot to `Spawn()` your object. Run `Spawn()` on your `NetworkObject` component as the server to fix this issue. + +## Server build is using 100% CPU + +**Issue**: When running an MLAPI server created from a server build it has a cpu usage of 100% blocking all my other applications. + +**Solution**: Unity server builds try to push as many Updates per second as possible. On a server this is most often not necessary. You can limit the target frame rate to reduce the amounts of Updates with this: +```csharp +Application.targetFrameRate = 30; +``` \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/tutorials/goldenpath_series/gp_intro.md b/versioned_docs/version-1.0.0/tutorials/goldenpath_series/gp_intro.md new file mode 100644 index 000000000..cd8b3f897 --- /dev/null +++ b/versioned_docs/version-1.0.0/tutorials/goldenpath_series/gp_intro.md @@ -0,0 +1,31 @@ +--- +id: gp_intro +title: Learning with Golden Path +description: Introduction to the Golden Path series, explaining the aim of the series +--- + +The Hello World/Golden Path series is meant to guide you through the Netcode installation and implement some of the basic features of Netcode. They also provide a way to test if your installation and feature implementations are correct. + +You should start with the [Hello World guide](../helloworld) as the base before moving to [Golden Path One](gp_module_one.md) and [Golden Path Two](gp_module_two.md). + +:::important Future plans for Hello World and Golden Paths +We are planning to revamp the Hello World and Golden Paths series to be far more useful. For users that have used these docs in the past may have noticed a lot of repetition between the Golden Paths and Hello World tutorials, this first phase was to make the Hello World and Golden Paths more cohesive and remove the repetition. + +Next steps will likely involve the existing Golden Path series to be completely part of Hello World as a series, and the Golden Path series become a completely different experience that is more use case focused and more relatable to the game building experience. +::: + +
+ + +|
Hello World
|
Golden Path One
| +| --- | --- | +| Creating a new project
Installing Netcode
Creating and testing the basic networking building blocks
| Adding scripts to objects
Editor modes (Host Server and Client)
Basic player movement
Basic RPC and Network variable use | +
+
+ +|
Golden Path Two
| +| --- | +| Network variables (server-controlled)
Network transforms
More on RPCs| + + +
\ No newline at end of file diff --git a/versioned_docs/version-1.0.0/tutorials/goldenpath_series/gp_module_one.md b/versioned_docs/version-1.0.0/tutorials/goldenpath_series/gp_module_one.md new file mode 100644 index 000000000..ef89c1c3d --- /dev/null +++ b/versioned_docs/version-1.0.0/tutorials/goldenpath_series/gp_module_one.md @@ -0,0 +1,472 @@ +--- +id: goldenpath_one +title: Golden Path Module One +description: Tutorial that explains adding scripts to objects, editor modes (Host Server and Client), basic player movement and basic RPC use. +--- + +Golden Path One continues on the work from [Hello World](../helloworld.md) to add a few more features. + +This guide covers: + +- Adding scripts to your objects +- Adding editor modes inside your game (Host, Server, and Client) +- Basic Player Movement +- Permissions +- Basic RPC use + +:::note +The videos on this page were removed because they were out-of-date and caused more confusion than help. All videos in the Hello World and Golden Path series will be recreated and added back at a later time. +::: + +## Prerequisites + +You should have completed the [Hello World project](../helloworld.md) before starting this tutorial. We use Hello World as the base for this and other Golden Path modules. + +## Open your Hello World project + +1. Open Unity Hub. +1. Select `Hello World` from the list of projects displayed. + +## Adding Scripts to Hello World + +This section adds some scripts to Hello World that contain the new features covered in the tutorial. +1. Click the **Assets** folder. +2. Open the **Scripts** folder. + +### Adding the `HelloWorldPlayer.cs` script + +1. Create a new script `HelloWorldPlayer`. +1. Open the `HelloWorldPlayer.cs` script. +1. Edit the `HelloWorldPlayer.cs` script to match the following. + +
+Click to show/hide the Code. + +```csharp +using Unity.Netcode; +using UnityEngine; + +namespace HelloWorld +{ + public class HelloWorldPlayer : NetworkBehaviour + { + public NetworkVariable Position = new NetworkVariable(); + + public override void OnNetworkSpawn() + { + if (IsOwner) + { + Move(); + } + } + + public void Move() + { + if (NetworkManager.Singleton.IsServer) + { + var randomPosition = GetRandomPositionOnPlane(); + transform.position = randomPosition; + Position.Value = randomPosition; + } + else + { + SubmitPositionRequestServerRpc(); + } + } + + [ServerRpc] + void SubmitPositionRequestServerRpc(ServerRpcParams rpcParams = default) + { + Position.Value = GetRandomPositionOnPlane(); + } + + static Vector3 GetRandomPositionOnPlane() + { + return new Vector3(Random.Range(-3f, 3f), 1f, Random.Range(-3f, 3f)); + } + + void Update() + { + transform.position = Position.Value; + } + } +} +``` +
+ +### Adding the `HelloWorldManager.cs` script + +1. Create an empty `GameObject` rename it **HelloWorldManager**. +1. Create a script called `HelloWorldManager`. +1. Open the `HelloWorldManager.cs` script. +1. Edit the `HelloWorldManager.cs` script to match the following. + +:::tip +You can copy the script from here and paste it into your file. + 1. Select the code sample. + 1. Click **Copy** in the top right corner. + 1. Paste it into your code editor. +::: + +
+Click to show/hide the Code. + + +```csharp + +using Unity.Netcode; +using UnityEngine; + +namespace HelloWorld +{ + public class HelloWorldManager : MonoBehaviour + { + void OnGUI() + { + GUILayout.BeginArea(new Rect(10, 10, 300, 300)); + if (!NetworkManager.Singleton.IsClient && !NetworkManager.Singleton.IsServer) + { + StartButtons(); + } + else + { + StatusLabels(); + + SubmitNewPosition(); + } + + GUILayout.EndArea(); + } + + static void StartButtons() + { + if (GUILayout.Button("Host")) NetworkManager.Singleton.StartHost(); + if (GUILayout.Button("Client")) NetworkManager.Singleton.StartClient(); + if (GUILayout.Button("Server")) NetworkManager.Singleton.StartServer(); + } + + static void StatusLabels() + { + var mode = NetworkManager.Singleton.IsHost ? + "Host" : NetworkManager.Singleton.IsServer ? "Server" : "Client"; + + GUILayout.Label("Transport: " + + NetworkManager.Singleton.NetworkConfig.NetworkTransport.GetType().Name); + GUILayout.Label("Mode: " + mode); + } + + static void SubmitNewPosition() + { + if (GUILayout.Button(NetworkManager.Singleton.IsServer ? "Move" : "Request Position Change")) + { + if (NetworkManager.Singleton.IsServer && !NetworkManager.Singleton.IsClient ) + { + foreach (ulong uid in NetworkManager.Singleton.ConnectedClientsIds) + NetworkManager.Singleton.SpawnManager.GetPlayerNetworkObject(uid).GetComponent().Move(); + } + else + { + var playerObject = NetworkManager.Singleton.SpawnManager.GetLocalPlayerObject(); + var player = playerObject.GetComponent(); + player.Move(); + } + } + } + } +} +``` +
+ + +1. Add the `HelloWorldManager` script component to the `HelloWorldManager` `GameObject`. + +## Adding Editor Modes to Hello World + +Inside the `HelloWorldManager.cs` script, we define two methods which mimic the editor buttons inside of **NetworkManager** during Play mode. + +
+Click to show/hide the Code. + + +```csharp + static void StartButtons() + { + if (GUILayout.Button("Host")) NetworkManager.Singleton.StartHost(); + if (GUILayout.Button("Client")) NetworkManager.Singleton.StartClient(); + if (GUILayout.Button("Server")) NetworkManager.Singleton.StartServer(); + } + + static void StatusLabels() + { + var mode = NetworkManager.Singleton.IsHost ? + "Host" : NetworkManager.Singleton.IsServer ? "Server" : "Client"; + + GUILayout.Label("Transport: " + + NetworkManager.Singleton.NetworkConfig.NetworkTransport.GetType().Name); + GUILayout.Label("Mode: " + mode); + } +``` +
+ +`NetworkManager` implements the singleton pattern as it declares its singleton named `Singleton`. This is defined when the `MonoBehaviour` is enabled. This component also contains very useful properties, such as `IsClient`, `IsServer`, and `IsLocalClient`. The first two dictate the connection state we have currently established that you will use shortly. + +We call these methods inside of `OnGUI()`. + +
+Click to show/hide the Code. + + +```csharp + + void OnGUI() + { + GUILayout.BeginArea(new Rect(10, 10, 300, 300)); + if (!NetworkManager.Singleton.IsClient && !NetworkManager.Singleton.IsServer) + { + StartButtons(); + } + else + { + StatusLabels(); + + SubmitNewPosition(); + } + + GUILayout.EndArea(); + } + +``` +
+ +:::note +You will notice the introduction of a new method, `SubmitNewPosition()`. This is used later. +::: + +## Adding basic movement to the Player object + +The `HelloWorldPlayer.cs` script adds some basic movement to the Hello World player. + + +1. Select the **Player** prefab. +1. Add the script `HelloWorldPlayer` script as a component. +This class will inherit from `NetworkBehaviour` instead of `MonoBehaviour`. + +
+Click to show/hide the Code. + + + + +```csharp + public class HelloWorldPlayer : NetworkBehaviour + +``` +
+ +Inside this class we now define a `NetworkVariable` to represent this player's networked position. + +
+Click to show/hide the Code. + + + + +```csharp + public NetworkVariable Position = new NetworkVariable(); +``` +
+ +`HelloWorldPlayer` overrides `OnNetworkSpawn`. + +
+Click to show/hide the Code. + + + + +```csharp + public override void OnNetworkSpawn() + { + if (IsOwner) + { + Move(); + } + } +``` +
+ +Any `MonoBehaviour` implementing `NetworkBehaviour` can override the Netcode method `OnNetworkSpawn()`. This method is fired when the `NetworkObject` gets spawned. We override `OnNetworkSpawn` since a client and a server will run different logic here. + +:::note +This can be overriden on any `NetworkBehaviour`. +::: + +On both client and server instances of this player, we call the `Move()` method, which will simply do the following. + +
+Click to show/hide the Code. + + + + +```csharp + public void Move() + { + if (NetworkManager.Singleton.IsServer) + { + var randomPosition = GetRandomPositionOnPlane(); + transform.position = randomPosition; + Position.Value = randomPosition; + } + else + { + SubmitPositionRequestServerRpc(); + } + } +``` +
+ +### Some simple RPC use + +If this player is a server-owned player, at `OnNetworkSpawn()` we can immediately move this player, as suggested in the following code. + +
+Click to show/hide the Code. + + + + +```csharp + if (NetworkManager.Singleton.IsServer) + { + var randomPosition = GetRandomPositionOnPlane(); + transform.position = randomPosition; + Position.Value = randomPosition; + } +``` + +
+ +If we are a client, we call a `ServerRpc`. A `ServerRpc` can be invoked by a client to be executed on the server. + +
+Click to show/hide the Code. + + + + +```csharp + else + { + SubmitPositionRequestServerRpc(); + } + +``` +
+ +This `ServerRpc` simply sets the position `NetworkVariable` on the server's instance of this player by just picking a random point on the plane. + +
+Click to show/hide the Code. + + + +```csharp + [ServerRpc] + void SubmitPositionRequestServerRpc(ServerRpcParams rpcParams = default) + { + Position.Value = GetRandomPositionOnPlane(); + } +``` +
+ +The server instance of this player has just modified the Position `NetworkVariable`, meaning that if we are a client, we need to apply this position locally inside of our Update loop. + +
+Click to show/hide the Code. + + + +```csharp + void Update() + { + transform.position = Position.Value; + } +``` +
+ +We can now go back to `HelloWorldManager.cs` and define the contents of `SubmitNewPosition()`. + +
+Click to show/hide the Code. + + + +```csharp + static void SubmitNewPosition() + { + if (GUILayout.Button(NetworkManager.Singleton.IsServer ? "Move" : "Request Position Change")) + { + var playerObject = NetworkManager.Singleton.SpawnManager.GetLocalPlayerObject(); + var player = playerObject.GetComponent(); + player.Move(); + } + } +``` +
+ +Whenever you press the GUI button (which is contextual depending on if you are server or a client), you find your local player and simply call `Move()`. + +You can now create a build which will demonstrate the concepts outlined above. + +:::tip +Make sure **SampleScene** is included in **BuildSettings** > **Scenes in Build** list. +::: + +One build instance can create a host. Another client can join the host's game. Both are able to press a GUI button to move. Server will move immediately and be replicated on client. Client can request a new position, which will instruct the server to modify that server instance's position `NetworkVariable`. That client will apply that `NetworkVariable` position inside of it's Update() method. + +## Next Steps + +See the following content to continue your journey using Netcode: + +* Build on the your growing Hello World project to continue learning about different features of Netcode with [Golden Path Two](goldenpath_two) +* Check out the educational samples to further explore Netcode and its abilities: + * [Boss Room](../../learn/bossroom/bossroom) + * [2D Spaceshooter Bitesize Sample](../../learn/bitesize/bitesize-spaceshooter) + * [Invaders Bitesize Sample](../../learn/bitesize/bitesize-invaders) + * [Client-Driven Bitesize Sample](../../learn/bitesize/bitesize-clientdriven) diff --git a/versioned_docs/version-1.0.0/tutorials/goldenpath_series/gp_module_two.md b/versioned_docs/version-1.0.0/tutorials/goldenpath_series/gp_module_two.md new file mode 100644 index 000000000..10ad0233d --- /dev/null +++ b/versioned_docs/version-1.0.0/tutorials/goldenpath_series/gp_module_two.md @@ -0,0 +1,239 @@ +--- +id: goldenpath_two +title: Golden Path Module Two +description: Tutorial covering, Network variables (client and server-controlled), Network transforms, and RPCs. +--- + +Golden Path Two continues on the work from [Hello World](../helloworld.md) and [Golden Path One](gp_module_one.md) to add a few more features. + +This guide covers: + +- Network variables (client and server-controlled) +- Network transforms +- RPCs + +:::note +The videos on this page were removed because they were out-of-date and caused more confusion than help. All videos in the Hello World and Golden Path series will be recreated and added back at a later time. +::: + +## Prerequisites + +You should have completed the [Hello World project](../helloworld.md) and [Golden Path One](gp_module_one.md) before starting this tutorial. + +## Open your Hello World project + +1. Open Unity Hub. +1. Select `Hello World` from the list of projects displayed. + +## Introducing a Server-controlled Network Variable + +This section adds a Server-controlled Network Variable to the project. + +1. Open the **Scripts** Folder. +1. Create a script called `NetworkVariableTest`. +1. Click the **Player** prefab. +1. In the **Player** prefab Inspector tab, click **Add Component**. +1. Click **Scripts**, and add the `NetworkVariableTest.cs` script you created earlier. +1. Open the `NetworkVariableTest.cs` script. +1. Edit the `NetworkVariableTest.cs` script to match the following. + + +
+Click to show/hide the Code. + + + +``` csharp +using Unity.Netcode; +using UnityEngine; + +public class NetworkVariableTest : NetworkBehaviour +{ + private NetworkVariable ServerNetworkVariable = new NetworkVariable(); + private float last_t = 0.0f; + + public override void OnNetworkSpawn() + { + if (IsServer) + { + ServerNetworkVariable.Value = 0.0f; + Debug.Log("Server's var initialized to: " + ServerNetworkVariable.Value); + } + } + + void Update() + { + var t_now = Time.time; + if (IsServer) + { + ServerNetworkVariable.Value = ServerNetworkVariable.Value + 0.1f; + if (t_now - last_t > 0.5f) + { + last_t = t_now; + Debug.Log("Server set its var to: " + ServerNetworkVariable.Value); + } + } + } +} +``` +
+ +8. Save your scene. + +### Testing Server-controlled Network Variables + +Now we will test the Server-controlled Network Variable works as we intended. + +1. Select **File > Build and Run**. +1. Stop the player. +2. Launch the client and server together in a terminal as shown in [Testing the command line helper](../helloworld.md#testing-the-command-line-helper). +3. After a brief delay, the client and server will spawn. +4. You should see the following in the console, showing that the server and client are sharing the variable: + + +``` +Server's var initialized to: 0 +Server set its var to: 0.1 +Server set its var to: 3.099999 +Server set its var to: 6.099997 +``` +:::note +Since the printing to the terminal does not happen on every tick, the numbers will not match up perfectly. +::: + +## Introducing Network Transform + +This section adds a Network Transform component that will move the player. + +1. Click **Player** prefab. +1. Click **Add Component** in the Inspector Tab. +1. Select **Netcode** from the list shown. +1. Select the **Network Transform** component from the list shown. +1. Open the **Scripts** Folder. +1. Create a script called `NetworkTransformTest`. +1. Click the **Player** prefab. +1. In the **Player** prefab Inspector tab, click **Add Component** +1. Click **Scripts**, and add the `NetworkTransformTest.cs` script you created earlier. +1. Open the `NetworkTransformTest.cs` script. +1. Edit the `NetworkTransformTest.cs` script to match the following. + +
+Click to show/hide the Code. + + + +```csharp +using System; +using Unity.Netcode; +using UnityEngine; + +public class NetworkTransformTest : NetworkBehaviour +{ + void Update() + { + if (IsServer) + { + float theta = Time.frameCount / 10.0f; + transform.position = new Vector3((float) Math.Cos(theta), 0.0f, (float) Math.Sin(theta)); + } + } +} +``` +
+ +12. Save your scene. + +### Testing Network Transform + +Now we check that the Network Transform functions correctly. + +1. Select **File** > **Build and Run**. +1. Stop the player. +1. Launch the client and server together in a terminal as shown in [Testing the command line helper](#testing-the-command-line-helper). +1. After a brief delay, the client and server will spawn. +1. You should see the player capsule moving in a circle on both the client and the server. + +## Introducing RPCs + +This section adds some basic RPCs to the project. + +1. Open the **Scripts** Folder. +1. Create a script called `RpcTest`. +1. Click the **Player** prefab. +1. In the **Player** prefab Inspector tab, click **Add Component**. +1. Click **Scripts**, and add the `RpcTest.cs` script you created earlier. +2. Open the `RpcTest.cs` script. +3. Edit the `RpcTest.cs` script to match the following. + +
+Click to show/hide the Code. + + + +```csharp +using Unity.Netcode; +using UnityEngine; + +public class RpcTest : NetworkBehaviour +{ + public override void OnNetworkSpawn() + { + if (!IsServer) + { + TestServerRpc(0); + } + } + + [ClientRpc] + void TestClientRpc(int value) + { + if (IsClient) + { + Debug.Log("Client Received the RPC #" + value); + TestServerRpc(value + 1); + } + } + + [ServerRpc] + void TestServerRpc(int value) + { + Debug.Log("Server Received the RPC #" + value); + TestClientRpc(value); + } +} +``` +
+ +9. Save your scene. + +### Testing RPCs + +Now we will test that the client and server are both recieving the RPCs correctly. + +1. Select **File** > **Build and Run**. +1. Stop the player. +1. Launch the client and server together in a terminal as shown in [Testing the command line helper](#testing-the-command-line-helper). +1. After a brief delay, the client and server will spawn. +1. In the console, you should expect to see the client and server sending RPC messages to each other. +1. The client kicks off the exchange in its `Update` call the first time with a counter value of 0. +1. It then makes an RPC call to the server with the next value. The server receives this and calls the client. In the console view, you will see: + +``` +Server Received the RPC #1 +Client Received the RPC #1 +Server Received the RPC #2 +Client Received the RPC #2 +Server Received the RPC #3 +Client Received the RPC #3 +... +``` + +## Next Steps + +See the following content to continue your journey using Netcode: + +* Check out the educational samples to further explore Netcode and its abilities: + * [Boss Room](../../learn/bossroom/getting-started-boss-room.md) + * [2D Spaceshooter Bitesize Sample](../../learn/bitesize/bitesize-spaceshooter.md) + * [Invaders Bitesize Sample](../../learn/bitesize/bitesize-invaders.md) + * [Client-Driven Bitesize Sample](../../learn/bitesize/bitesize-clientdriven.md) diff --git a/versioned_docs/version-1.0.0/tutorials/helloworld.md b/versioned_docs/version-1.0.0/tutorials/helloworld.md new file mode 100644 index 000000000..360483a6f --- /dev/null +++ b/versioned_docs/version-1.0.0/tutorials/helloworld.md @@ -0,0 +1,307 @@ +--- +id: helloworld +title: Your Netcode "Hello World" Project +description: Tutorial that explains creating a project, installing the Netcode for GameObjects package, and creating the basic components for your first networked game. +--- + +A "Hello World" program is a computer program that outputs or displays the message "Hello, World!". Normally it is the first program written by people learning to code. It is also used as a sanity test to make sure that a computer language is correctly installed and that the operator understands how to use it. + +This "Hello World" tutorial walks you through creating a project, installing Netcode for GameObjects (Netcode), and creating the basic components for your first networked game. It is also the base for the [Golden Path series](goldenpath_series/gp_intro.md). + +:::note +The videos on this page were removed because they were out-of-date and caused more confusion than help. All videos in the Hello World and Golden Path series will be recreated and added back at a later time. +::: + +## Create a new project in Unity + +1. Open the **Unity Hub**. +1. Click **New**. +1. Select type ‘3D’ +1. Name the project *Hello World*. +1. Select the location you want to save the project. + +## Install Netcode + +See the [install Netcode guide](../installation/installation.md) to install the Netcode package. + +## Create the Basic Components + +In this section we will create the basic building blocks of a multiplayer game. + +### Creating Network Manager and selecting the Transport + +In this section we will add a Network Manager and add Unity Transport (UTP) to our project. + +1. Right-click in the **Hierarchy** tab of the main Unity Window. +1. Select **Create Empty**. +1. Rename the `GameObject` **NetworkManager**. + + :::tip + We renamed the `GameObject` because: + * It makes it easier to refer to later. + * There should only be one **NetworkManager**, this is the object that contains the `NetworkManager` component. You may get unexpected results if you create more than one **NetworkManager**. + ::: + +2. Select **NetworkManager**. +3. Click **Add Component** in the Inspector Tab. +4. Select **Netcode** from the list shown. +5. Select `NetworkManager` Component from the list displayed. +6. Inside the `NetworkManager` component tab, locate the `NetworkTransport` field. +7. Click "Select Transport". +8. Select `UnityTransport`. +9. Save your scene. + +## Creating an object to spawn for each connected player + +This section adds in a player object and spawns it for each connected player. + +1. Right-click in the **Hierarchy** tab of the Unity Window to create a **3D Object > Capsule** +1. Rename it **Player**. +1. While **Player** is selected, add a **Netcode** > `NetworkObject` component in the Inspector Tab. +1. Click the **Assets** folder under the **Project** tab. +2. Right-click inside the **Assets** folder to **Create** > **Folder** and call it **Prefabs**. +3. Make **Player** a prefab by dragging it to **Prefabs** folder you just created. +4. Delete **Player** from scene. + + :::tip + We remove the **Player** object from the scene because we assign this network prefab to the `Player Prefab` property in the `NetworkManager` component. The library does not support defining a player object as an in-scene placed `NetworkObject`. + ::: + +5. Select `NetworkManager`. +6. Inside the `NetworkManager` component tab, locate the `Player Prefab` field. +7. Drag this player prefab from above into this field. + + :::important + When you drop the prefab into the `Player Prefab` slot, you are telling the library that when a client connects to the game, automatically spawn this prefab as the character for the connecting client. If you do not have any prefab set as the `Player Prefab` no player object will be spawned. + ::: + +1. Create a **3D Object->Plane**, centered at (0,0,0). +1. Save your scene + +### Adding your scene to the build +:::important +When 'Enable Scene Management' is enabled for the NetworkManager (allowing the server to control which scenes should be loaded for the clients), we must ensure that the current scene has been added to the build, otherwise, we will be unable to enter play mode. This option is enabled by default. +::: + +1. Click **File** > **Build Settings**, in the upper-left corner of the Unity window +2. Click **Add Open Scenes** +3. Close the `Build Settings` window. + +## Creating a command line helper + +This command line helper launches our project outside Unity and can make testing builds easier. + +1. Right-click the **Assets** folder and create a new folder by hovering over **Create** and selecting **Folder**. Name it **Scripts**. +2. Create a script called `NetworkCommandLine` by right-clicking on your **Scripts** folder, hovering over **Create** and selecting **C# Script**. +3. In the **Hierarchy** menu, right-click on the `NetworkManager` and choose **Create Empty**. + + This will create an empty `GameObject` with `NetworkManager` as its parent. + +4. Rename this child `GameObject` `NetworkCommandLine`. +5. With the new `NetworkCommandLine` object selected, click **Add Component** from the **Inspector** tab. +6. Select **Scripts** from the drop-down and click on the `NetworkCommandLine.cs` script you created earlier. +7. Open the `NetworkCommandLine.cs` script by double-clicking from the **Project** tab > **Assets** > **Scripts**. It will open in your text editor +8. Edit the `NetworkCommandLine.cs` script to match the following: + +
+Click to show/hide the Code. + + + +``` csharp +using System.Collections.Generic; +using Unity.Netcode; +using UnityEngine; + +public class NetworkCommandLine : MonoBehaviour +{ + private NetworkManager netManager; + + void Start() + { + netManager = GetComponentInParent(); + + if (Application.isEditor) return; + + var args = GetCommandlineArgs(); + + if (args.TryGetValue("-mode", out string mode)) + { + switch (mode) + { + case "server": + netManager.StartServer(); + break; + case "host": + netManager.StartHost(); + break; + case "client": + + netManager.StartClient(); + break; + } + } + } + + private Dictionary GetCommandlineArgs() + { + Dictionary argDictionary = new Dictionary(); + + var args = System.Environment.GetCommandLineArgs(); + + for (int i = 0; i < args.Length; ++i) + { + var arg = args[i].ToLower(); + if (arg.StartsWith("-")) + { + var value = i < args.Length - 1 ? args[i + 1].ToLower() : null; + value = (value?.StartsWith("-") ?? false) ? null : value; + + argDictionary.Add(arg, value); + } + } + return argDictionary; + } +} +``` + +
+ +9. Paste the copied code into your code editor. +1. Save your changes. Your script will reload in the Unity Editor. +1. Back in the Editor, open **Edit** -> **Project Settings** +1. Select the **Player tab**. +1. Expand the **Resolution and Presentation**. +1. From **Resolution** > **Fullscreen Mode**, change `Fullscreen Window` to `Windowed`. +1. Back to the Editor main window, save your scene. + + +:::tip + If you are using a Pro Unity license, you may want to disable the splash screen by unchecking **Splash Image** > **Splash Screen** > **Show Splash Screen**. +::: + +### Testing the command line helper + +Now we will test that the command line helper script works. + +1. Select **File** > **Build and Run**. +1. Create a new folder called `Build` inside your Hello World project folder. +1. **Save As** the binary `HelloWorld`. +1. Your project will build and launch in a new window, and you should see the plane. +1. Quit your app. +1. Now to launch from the command line. + + + + + + +For Windows you should do the following: + + +1. Open your Command Prompt. +1. Enter the following. Be sure to change the noted section `< >` of **both** commands to your project. + +:::note +You may get a UAC prompt requesting permission for the binary to run you should allow it. +::: + + Server: + ``` + \Build\HelloWorld.exe -mode server + ``` + + Client: + ``` + \Build\HelloWorld.exe -mode client + ``` + + To run these commands on a single line: + ``` + HelloWorld\Build\HelloWorld.exe -mode server & HelloWorld\Build\HelloWorld.exe -mode client + ``` + + Example: + ``` + C:\Users\sarao>HelloWorld\Build\HelloWorld.exe -mode server & HelloWorld\Build\HelloWorld.exe -mode client + ``` + +:::important +On Windows, no standard out stream exists by default, so you will need to view the Debug.log file to see the outputs. You can find the Debug.log files in: + +`C:\Users\username\AppData\LocalLow\CompanyName\ProductName\Player.log` + +Where the `CompanyName` should default to `DefaultCompany` for a new project and `ProductName` should be equal to the project's name. + +Alternatively you can modify the Windows commands to create a log.txt file in the same folder as your **HelloWorld** folder. + +Modify the commands as follows: + + Server: + ``` + \Build\HelloWorld.exe -logfile log-server.txt -mode server + ``` + + Client: + ``` + \Build\HelloWorld.exe -logfile log-client.txt -mode client + ``` + + Example (Running as a single command line): + ``` + C:\Users\sarao>HelloWorld\Build\HelloWorld.exe -logfile -log-server.txt -mode server & HelloWorld\Build\HelloWorld.exe -logfile log-client.txt -mode client + ``` +::: + + + + + +For Mac you should do the following: + +1. Open Terminal. +2. Enter the following. Be sure to change the noted section `< >` of **both** commands to your project. + +Server +``` +/Build/HelloWorld.app/Contents/MacOS/ -mode server -logfile - +``` + +Client +``` +/Build/HelloWorld.app/Contents/MacOS/ -mode client -logfile - +``` + +Run both as a single command: +``` +/Build/HelloWorld.app/Contents/MacOS/ -mode server -logfile - & ; ~ /Build/HelloWorld.app/Contents/MacOS/ -mode client -logfile - +``` + + + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; + +## Testing Hello World + +Now we will test to see if everything works as expected. + +1. Click **Play**. +1. Click **Start Host** under **NetworkManager**. + +## Next Steps + +See the following content to continue your journey using Netcode: + +* Build on the Hello World project to continue learning about different features of Netcode with the [Golden Path series](../tutorials/goldenpath_series/gp_intro.md). +* Check out the educational samples to further explore Netcode and its abilities: + * [Boss Room](../learn/bossroom/getting-started-boss-room.md) + * [2D Spaceshooter Bitesize Sample](../learn/bitesize/bitesize-spaceshooter.md) + * [Invaders Bitesize Sample](../learn/bitesize/bitesize-invaders.md) + * [Client-Driven Bitesize Sample](../learn/bitesize/bitesize-clientdriven.md) diff --git a/versioned_docs/version-1.0.0/tutorials/testing/techniques_and_tricks_for_debugging_multiplayer_games.md b/versioned_docs/version-1.0.0/tutorials/testing/techniques_and_tricks_for_debugging_multiplayer_games.md new file mode 100644 index 000000000..cf7ea57b2 --- /dev/null +++ b/versioned_docs/version-1.0.0/tutorials/testing/techniques_and_tricks_for_debugging_multiplayer_games.md @@ -0,0 +1,180 @@ +--- +id: techniques_and_tricks_for_debugging_multiplayer_games +title: Techniques and tricks for debugging multiplayer games +description: Guide covering some of the techniques that are either specific to or are useful when debugging multiplayer games. +--- + +When debugging games, multiplayer games included, it helps to know the toolbag that we have at our disposal. + +All the conventional game development wisdom applies, however certain scenarios that are typical to multiplayer game development call for special tricks and approaches. + +Below is a list of practices and techniques that we use daily when working on the Boss Room sample. These recommendations, we find, compound into a more comfortable working experience when developing multiplayer games with Unity. + +## Debugging tricks for multiplayer games + +### Use ParrelSync clone-based workflow during development. + +[ParrelSync workflow](testing_locally.md#parrelsync) is faster than creating builds and it allows you to debug the separate editor instances via separate IDE debuggers. + +Use ParrelSync to run separate editor instances for your Host/Server and Client. + +### Use debug drawing techniques extensively + +Unity engine has two debug rendering APIs that are very useful for the purposes of multiplayer game debugging: + - [Debug.DrawRay](https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html) + - [Debug.DrawLine](https://docs.unity3d.com/ScriptReference/Debug.DrawLine.html) + +Both of these functions allow us to draw arbitrary debug lines that would be visible in the Scene view and in the Game view, provided Gizmo rendering is enabled (to enable Gizmo rendering in Game view you need to click on the `Gizmos` menu at the top of the Game view). + +The key trick here is to use different colors for different kinds of information and to make the lines stay long enough for visual inspection by setting `duration` parameter. This technique shines when it is combined with [screen recordings](#7-recording-the-video-of-gameplay) of [multiple peers running side by side in separate editor instances via ParrelSync](#1-use-parrelsync-workflow-during-development). + +The code below would render a green debug line that's 2 units tall at the position of the transform, and this line would stay on screen for 4 seconds: +`Debug.DrawLine(this.transform.position, this.transform.position + Vector3.UP * 2f, Color.green, duration: 4f);` + +When working on Boss Room we found it valuable to draw debug lines for the following items: + - Visual position + - Network position + - Movement intention + - Object interactions + +### A Netcode Enabled Line Renderer +Sometimes it is useful to have visual feedback that shows a specific direction, value, or any other useful debug metric pertinent to your project. Below is a fully working example of a netcode enabled line renderer that could be used for visual debugging purposes: +```csharp +using UnityEngine; +using Unity.Netcode; +public class NetcodeEnabledLineRenderer : NetworkBehaviour +{ + private LineRenderer m_LineRenderer; + private Vector3[] m_Positions; + private Material m_LineMaterial; + + [Tooltip("The default state of the netcode debug render lines")] + [SerializeField] + private bool m_EnableDebugLines = true; + + [Tooltip("The length of the line")] + public float LineLength = 4.0f; + + [Tooltip("The width of the line")] + public float LineWidth = 0.3f; + + private void Awake() + { + // Add a line renderer component + m_LineRenderer = gameObject.AddComponent(); + + // Switch to a legacy built-in shader that will work with just colors and/or a color gradient + m_LineMaterial = new Material(Shader.Find("Legacy Shaders/Particles/Alpha Blended Premultiply")); + + // Assign this new material to the line renderer + m_LineRenderer.material = m_LineMaterial; + + // Create our start color for the gradient + var colorKeyStart = new GradientColorKey(); + colorKeyStart.color = Color.red; + // The "start" should be 0.0f + colorKeyStart.time = 0.0f; + + // Create our end color for the gradient + var colorKeyEnd = new GradientColorKey(); + colorKeyEnd.color = Color.blue; + // The "end" should be 1.0f + colorKeyEnd.time = 1.0f; + + // Now create and apply the gradient + m_LineRenderer.colorGradient = new Gradient() { colorKeys = + new GradientColorKey[2] { colorKeyStart, colorKeyEnd }, + mode = GradientMode.Blend }; + + //declare two positions for the start and end of the line + m_Positions = new Vector3[2]; + + //Ensure that the line renderer knows to draw in world space + m_LineRenderer.useWorldSpace = true; + + //set the beginning and ending width of the line in units + m_LineRenderer.startWidth = 0.3f; + m_LineRenderer.endWidth = 0.3f; + } + + public override void OnDestroy() + { + // With NetworkBehaviours, always make sure to invoke the + // base.OnDestroy method + base.OnDestroy(); + + // We should always destroy any runtime materials we create + if (m_LineMaterial != null) + { + Destroy(m_LineMaterial); + } + } + + /// + /// Update the position of the line + /// + private void Update() + { + if (IsSpawned && m_EnableDebugLines) + { + //set the start and end positions of our line + m_Positions[0] = transform.position; + m_Positions[1] = transform.position + Vector3.up * LineLength; + + //feed the values to the line renderer + m_LineRenderer.SetPositions(m_Positions); + } + } + + /// + /// Example for having netcode debug render lines + /// + [ClientRpc] + private void ToggleDebugLinesClientRpc(bool drawDebugLines) + { + m_EnableDebugLines = drawDebugLines; + } + + /// + /// Server-Side only + /// Enables/Disables the debug line rendering + /// + public void DebugLinesEnabled(bool enableDebugLines) + { + if (IsSpawned && IsServer) + { + m_EnableDebugLines = enableDebugLines; + ToggleDebugLinesClientRpc(m_EnableDebugLines); + } + } +} +``` + +### Use debug logging for situations where visual debugging is not appropriate. + +Text-based logging is valuable for tracking down non-visual events (such as RPCs) and information. +It is a good idea to include network tick and client id in log messages so that it's easier to build a timeline when reading the logs. + +### Use the artificial network conditioning tools. + +The options that are currently available to us are covered in the related [article on artificial network conditioning tools](testing_with_artificial_conditions.md). + +Of particular interest to us is the application-level network conditioning provided by [Unity Transport Simulator Tools](testing_with_artificial_conditions.md#unity-transport---simulator-tools), as it allows us to easily specify conditions for our individual peers that live within separate editors by means of ParrelSync. + +Artificial network conditions allow the errors and oddities that are hidden by nigh-absence of lag when running your instances locally to show up, and it's a good thing! + +### Capturing screen recordings of the game instances. + +First of all, it is very valuable to record both your Client and Server at the same time - it allows you to compare what is happening on either peer in realtime. + +When recording your screen, sometimes it’s hard to see if we are legitimately missing an update in our game or if it’s just our recording refresh rate isn’t synced with Unity’s refresh calls. + +In debug builds it's a great idea to show the Peer ID and the current frame number somewhere in the corner of the screen - this way there is a visual reference to the number of the frame we're currently observing on the recording. + +Sometimes, despite us using good debug rendering and logging it's still hard to understand what's going on even when going through the frames one by one. Increasing our FixedTimeStep setting to a ridiculous value (something as high as `0.2`) helps to have more time to really see what’s going on. + +The same applies to very high latencies (1000ms) - these stress the lag hiding techniques, allowing us to visualize what the different lag hiding techniques are doing. + +### Using breakpoints to debug a Client or Server + +You can use breakpoints to debug a game, but your connection may time out if you stay too long in this mode. Since it pauses your game, you can temporarily increase the timeout value to avoid disconnecting. diff --git a/versioned_docs/version-1.0.0/tutorials/testing/testing_client_connection_management.md b/versioned_docs/version-1.0.0/tutorials/testing/testing_client_connection_management.md new file mode 100644 index 000000000..2aa7050d5 --- /dev/null +++ b/versioned_docs/version-1.0.0/tutorials/testing/testing_client_connection_management.md @@ -0,0 +1,60 @@ +--- +id: testing_client_connection_management +title: Testing Client Connection Management +description: Guide covering the test cases to handle when managing client connection and common pitfalls to avoid +--- + +Managing client connections in a networked game can lead to many unexpected edge-cases which if not properly tested and handled may cause bugs. Here is a non-exhaustive list of test cases that should be handled, depending on what features a game provides, and things to look out for. + +### Clients connecting +- test cases: + - Client connecting to a new game session + - Client connecting to a new game session after leaving a previous game session + - in the case of a client-hosted game, after ending a previous game as a host + - Client connecting to an ongoing game session (late-joining) + - Client reconnecting to an ongoing game session (see [Session Management](../../advanced-topics/session-management.md#Reconnection)) + - Client failing to connect due to approval denied (see [Connection Approval](../../basics/connection-approval.md)) +- things to look out for: + - Client-Side: + - Does the state of the client prior to connecting have an impact (i.e. if connecting after disconnecting from another game or hosting one) + - Does the game state get properly replicated from the server when connecting? + - Server-Side: + - Does the server properly handle reconnections or late-joining, if the game supports it, or does it deny approval if not? + + +### Clients disconnecting +- test cases: + - Client disconnecting gracefully by shutting down NetworkManager + - Client disconnecting by closing the application + - Client timing out when losing connection to the host/server + - By disabling internet on client + - By disabling it on the host/server +- things to look out for: + - Client-side: + - Is the state of every object tied to the game session properly reset if not destroyed? (for example, if a NetworkBehaviour is not destroyed when despawning, is its state properly reset via OnNetworkDespawn and OnNetworkSpawn?) + - Is the client brought back to a state from which it can try to connect to a new game? + - Server-Side: + - Is the server notified of this disconnection and does it handle it properly? + - If using outside services, are they notified of this? (for example if using a lobby service, is the client removed from the lobby?) + +### Host / Server starting the session +- test cases: + - Host/Server starting a new game session + - Host/Server starting a new game session after shutting down a previous game session + - in the case of a client-hosted game, after disconnecting from a preivious game as a client +- things to look out for: + - Server-side: + - Does the state of the application prior to starting a new session have an impact (i.e. if starting after shutting down another game or disconnecting from one as a client) + +### Host / Server shutting down +- test cases: + - Host/Server disconnecting gracefully by shutting down NetworkManager + - Host/Server disconnecting by closing the application + - If requiring services (i.e Unity Game Services or other services) to function: + - Host/Server timing out when losing connection to services +- things to look out for: + - Client-side: + - Are clients notified of this shut down, and do they handle it? + - Server-side: + - Are the services used notified of this? (for example if using a lobby service, does the game properly close the lobby when shutting down the game session?) + - Is the state of every object tied to the game session properly reset if not destroyed? (for example, if a NetworkBehaviour is not destroyed when despawning, is its state properly reset via OnNetworkDespawn and OnNetworkSpawn?) diff --git a/versioned_docs/version-1.0.0/tutorials/testing/testing_locally.md b/versioned_docs/version-1.0.0/tutorials/testing/testing_locally.md new file mode 100644 index 000000000..e8958a4e2 --- /dev/null +++ b/versioned_docs/version-1.0.0/tutorials/testing/testing_locally.md @@ -0,0 +1,107 @@ +--- +id: testing_locally +title: Testing multiplayer games locally +description: Guide covering the available workflows for testing multiplayer games locally. +--- +Testing a multiplayer game presents unique challenges: + - You need to run multiple instances of the game in order to test multiplayer scenarios. + - You also need to iterate quickly on custom code and asset changes and validate work in a multiplayer scenario. + - You need to be able to debug work in a multiplayer scenario using editor tools. + +Currently, Unity does not provide any workflow that covers all of these requirements. (See our [roadmap here](https://unity.com/roadmap/unity-platform/multiplayer-networking)) + +There will always be a need to validate work in the target distribution format (ie. on platform) and the way to do it is by creating [Player Builds](#player-builds). + +:::important +Player builds do not meet the quick iteration and easy debuggability using editor tools requirement. As such the current recommended workflow for local iteration is [ParrelSync](#parrelsync). +::: + +## Player Builds + +:::tip hint +This approach is great when we need to verify work on the target platform or with a wider group of testers. +::: + +First step is to build an executable. + +1. Navigate to `File->Build Settings` in the menu bar. +1. Click `Build`. + +Then the build can be shared among the testers. + +### Local iteration using Player Builds + +Once the build has completed you can launch several instances of the built executable in order to both host and join a game. + +It is also possible to run the builds along with an editor that produced said build, which could be useful during iterations. + +:::unity For Mac +Mac users: to run multiple instances of the same app, you need to use the command line. +Run `open -n YourAppName.app` +::: + +:::tip hint +Though functional, we find this approach to be somewhat slow for the purposes of local iteration. Head on to the [ParrelSync](#parrelsync) section for our suggested workflow for local iteration. +::: + +## ParrelSync +:::caution + +ParallelSync is **not** supported by Unity. More information on its usage is available [here](https://github.com/VeriorPies/ParrelSync). Troubleshooting information can be found [here](https://github.com/VeriorPies/ParrelSync/wiki/Troubleshooting-&-FAQs) + +::: +![parrelsync-bossroom-demo](../../../../static/img/parrelsync-bossroom-demo.gif) + + + +[**ParrelSync**](https://github.com/VeriorPies/ParrelSync) is an open-source Unity editor extension that allows users to **test multiplayer gameplay without building the project** by having another Unity editor window opened and mirror the changes from the original project. + +**ParrelSync** works by making a copy of the original project folder and creating symbolic links to the `Asset` and `Project Settings` folders back from the original project. + +We use **ParrelSync** for local iteration in [Boss Room sample](https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop/). + +:::important + +**ParrelSync** relies on symbolic links and partial copies of the original project folder structure - generally it is completely safe. + +To ensure that no bug in any of the software you use can destroy your work - it is recommended that you consistently backup your project or use a version control system. Some common examples are: +- [Git](https://git-scm.com/) +- [SVN](https://subversion.apache.org/) +- [Plastic](https://www.plasticscm.com/) + +::: + +### Installation + +Follow the installation instructions on **ParrelSync** repo [page](https://github.com/VeriorPies/ParrelSync#installation) + +### Usage + - Navigate to `ParrelSync->Preferences` in the menu bar to open the preferences window. + - Ensure that both Options are selected as shown below + +![parrelsync-preferences](/img/parrelsync-preferences.png) + +:::important + +By default **ParrelSync** prevents asset serialization in all clone instances and changes can only be made from the original project editor. This is a **very important setting** that prevents issues with multiple editors accessing the same `Library` folder (which is not supported and breaks basic assumptions in Unity design). + +::: + + - Open the `ParrelSync->Clones Manager` from which you can launch, create and remove clone editors. + - Advanced usage is to utilize **ParrelSync's** capability of passing [Arguments](https://github.com/VeriorPies/ParrelSync/wiki/Argument) to clones, thus allowing to run custom logic on a per-clone basis. + +### Known issues and workarounds + - An important nuance is that **ParrelSync** does not sync changes made to packages. `Packages` folder is synced on clone opening, so if you made package changes - you should close and re-open your clones. + - [Relevant GitHub issue](https://github.com/VeriorPies/ParrelSync/issues/48) + - If you encounter a Netcode error that mentions `soft sync` - that generally means that prefabs or scenes are not in sync between editors. You should save the project in the main editor via `File->Save Project` and refresh the projects in the clone editors by pressing `Ctrl + R` (which is by default done automatically) or reimport networked prefabs in the main editor. + - More information and general **ParrelSync** FAQ: https://github.com/VeriorPies/ParrelSync/wiki/Troubleshooting-&-FAQs + - The ultimate workaround in case nothing helps - deleting and re-creating the clone instance via `ParrelSync->Clones Manager` window. + +## General tips + - Bigger screens or multi-screen setups allow for more screen real estate, which is handy when one has to have multiple instances of an app opened at the same time. + - **ParrelSync** has to copy and update separate `Packages` and `Library` folders for every clone, and in certain cases a fix for misbehaving clone is re-creation - a good SSD makes this process quite a bit faster. + - Creating a fork of any git repository that your project relies upon in production could help avoid bad surprises if the repo gets taken down or introduces an undesirable change. You should fork **ParrelSync** before using it in your live project. + +:::contribution Special Thanks +This guide would not have been possible without the hard work and support of Philipp Deschain, Unity. +::: \ No newline at end of file diff --git a/versioned_docs/version-1.0.0/tutorials/testing/testing_with_artificial_conditions.md b/versioned_docs/version-1.0.0/tutorials/testing/testing_with_artificial_conditions.md new file mode 100644 index 000000000..701f95cd1 --- /dev/null +++ b/versioned_docs/version-1.0.0/tutorials/testing/testing_with_artificial_conditions.md @@ -0,0 +1,226 @@ +--- +id: testing_with_artificial_conditions +title: Testing multiplayer games with artificial network conditions +description: Guide covering the available tools for local testing of multiplayer games with artificial latency, jitter and packet loss . +--- + +When we are developing a multiplayer game that is intended to operate over the internet we inevitably have to deal with the reality of poor network conditions. + +Adverse network factors, such as latency, jitter, and packet loss all have to be taken into account during development and the tolerance thresholds for these should not be an afterthought or something relegated to an "optimization pass". + +:::warning +Not testing with artificial network conditions makes it significantly more likely to have unexpected behaviors when the game is running over the internet. +::: + +This is challenging when we are [iterating on our game locally](testing_locally.md) - after all, all of the game instances are still running on the same network interface. It's reasonable to expect that there will be little to no latency between the clients, which is no good for our purposes - we want the network to **misbehave**. + +Thankfully there are a number of tools that can simulate adverse network conditions. + +For testing locally within the editor we suggest using [Unity Transport - Simulator Tools](#unity-transport---simulator-tools) along with [clone-based workflow via ParrelSync](testing_locally.md#parrelsync). + +For testing development builds with built-in artificial latency we suggest using [Unity Transport Simulator Tools with some custom code to inject artifical conditions into the build](#debug-builds). + +For testing release builds we suggest using [Clumsy](#clumsy-windows) if you're on Windows and Network Link Conditioner if you're on [macOS](#network-link-conditioner-mac-os) or [iOS](#network-link-conditioner-ios). A scriptable alternative to Network Link Conditioner on macOS is [dummynet](#dummynet-dnctl-and-pftcl-mac-os), which offers great control and comes packaged with the operating system. + +:::important +While artificial latency is great for simulating network conditions during development - it will not accurately emulate real world conditions. We recommend to test your game frequently on the targeted platforms and real live networking conditions. +::: + +## How much lag/packet loss/jitter should we use? + +It's not immediately obvious what the values and options we should enable in our network conditioning tools. All of them allow us to alter various aspects of network conditions such as latency, jitter and packet loss, though the names for concepts and the specific functionality varies between tools. + +Determining which network conditions to test with is about what your users will encounter while playing your game, which will vary by region and by platform. + +However, deciding what experience degradation is acceptable is dependant on game genre and on your game design decisions and other requirements. It's up to you to determine what's acceptable, there's no single rule for this. + +What latency value to use for general development? + +To test Boss Room, we used around 100ms-150ms for desktop platforms and around 200ms-300ms for mobile platforms and 5%-10% packet loss. These are just the values we used, the actual values you should test with will depend on your target platform and region. + +:::important +It's valuable to test at 100ms, 200ms, 500ms, even 1000ms and potentially higher to make sure that we don't have weird race conditions that present at different latency ranges. The users in the wild WILL have those latencies. +::: + +Next we should determine how much chaos we want to introduce - that's largely based on the target platform and the typical network conditions that our users would experience: + - Is the game meant to be played from a good broadband internet connection? + - Is the game meant to run on mobile networks? + +This question tells us if our users are likely to experience more jitter and packet loss - mobile networks are notorious for having widely varying quality of connection. Mobile users also could experience frequent network changes during active application usage, and even though [UTP has reconnection mechanism](https://github.com/Unity-Technologies/com.unity.multiplayer.rfcs/blob/rfc/device-reconnection/text/0000-device-reconnection.md), it still requires our applicaton to factor in the possibility of an occasional lag burst. + +What's important here is that testing purely with added delay and no packet loss and jitter is unrealistic. These values shouldn't be high - the baseline scenario is not what we would call stress-testing, but they should be non-zero. + +Adding jitter to the base delay value adds a layer of chaotic unreliability that would make our peers behave in a more natural way, allowing us to tweak our interpolation, buffering and other techniques to compensate for these instabilities. + +Adding packet loss, apart from introducing even more effective delay to our system could also wreak havoc on our unreliable messages, thus allowing us to explore if we need more defensive logic surrounding our unreliable messages or if we should opt for a reliable message instead. + +### Different network conditions for different peers + +:::important +[Clumsy](#clumsy-on-windows), [Network Link Conditioner](#network-link-conditioner-mac-os) and [dummynet](#dummynet-dnctl-and-pftcl-mac-os) are introducing changes on OS level, thus all the instances of the game that we open on our local machine would run under the same network conditions. + +Do not forget to disable it once you're done debugging, else your network connection will feel slow! + +QA teams run playtests with multiple people, each with their own system-wide conditioning settings settings. We can imitate this workflow locally by setting different per-peer network conditions. This approach is not as reflective of reality as good QA tests on different machines, but it allows us to test these more peculiar scenarios locally. +::: + +There is a group of scenarios where we would want to test how the game behaves when a player with a different baseline connection quality from most of our other peers joins the game - an example of such case could be someone playing from a significantly remote location or connecting from a device that's on a mobile network. + +In this case we would want to have an ability to set artifical conditions on a per-peer basis, which is possible with [Unity Transport Simulator Tools](#unity-transport---simulator-tools). + +### Clone-based workflow (ParrelSync) + +:::caution + +ParallelSync is **not** supported by Unity. More information on its usage is available [here](https://github.com/VeriorPies/ParrelSync). Troubleshooting information can be found [here](https://github.com/VeriorPies/ParrelSync/wiki/Troubleshooting-&-FAQs) + +::: + + +Simulator Tools effects only apply to editor instances and to [debug builds](#debug-builds), as such it matches really well with [clone-based workflow via ParrelSync](testing_locally.md#parrelsync). + +Other tools should be used when testing release builds locally. + +To combine the benefits of Simulator Tools Window with ParrelSync - create or open a clone of your project, open up the simulator tools window in both the main project and the clone and play with the settings to alter how network behaves for each individual peer. Remember to re-launch your game if you change the values in the tools window - the effects only take place when the UTP driver is being created. + +:::important +With Simulator Tools we can't specify if inbound packets and outbound packets would experience different conditions - artificial latecny, jitter and packet loss are bi-directional. +::: + +:::important +Simulator Tools window settings will not be committed to version control and need to be set up manually on different editor instances. +::: + +### Debug Builds + +Debug builds do allow for the possibility of applying artificial network conditions to the UTP driver, but the Simulator Tools window itself only sets these values in the Editor. + +To set the latency, jitter and packet-loss percentage values for develop builds we need the following code to execute before `NetworkManager` attempts to connect (changing the values of the paramters as desired): + +``` +#if DEVELOPMENT_BUILD && !UNITY_EDITOR + NetworkManager.Singleton.GetComponent().SetDebugSimulatorParameters( + packetDelay: 120, + packetJitter: 5, + dropRate: 3); +#endif +``` + +## System-wide network conditioners + +These tools are useful when we want to test builds as opposed to running multiple editor instances. It is also an option that works for **release** builds. + +:::important +The solutions described below share some common features: + - They do not support latency variability over time, so in effect we can't imitate artificial jitter with them. + - They are system-wide, thus all the local instances of our game would run under the same network conditions. + - They allow to control the settings for sending and receiving separately. +::: + +There are some inherent limitations that come with the system-wide level of application of these tools - they are not ideal for local testing of more than two peers because we can't have peers with different network conditions between them (if that is important for the test ofcourse). + +:::important +Some consoles offer similar functionality at the native SDK level. Check their documentation for details. +::: + +### Clumsy (Windows) + +:::note +dummynet is another option that can be used on Windows, however there are known issues when running it on Windows 10 related to signed driver enforcement setting. As such we found Clumsy to be a good default option on Windows. +::: + +Follow the installation instructions on the official [Clumsy Webpage](https://jagt.github.io/clumsy/). + +To test the builds with Clumsy: + - Run Clumsy + - Run instance 1 + - Run instance 2 + - At any point you can adjust Clumsy settings and observe the changes in gameplay fidelity + +#### Settings quickstart + + - Lag - that's our primary lever to control artifical latency + - Drop - that's our packet loss + - Throttle, Out of Order, Duplicate, Tamper - these will manifest as additional latency but should be automatically handled for us by Netcode. + - Since Clumsy doesn't have Jitter functionality - we can emulate jitter (inconsistnent latency over time) by playing with these parameters. Their cumulative effect would produce artifical latency fluctuations. + +For further reading please refer to the Details section of the [Clumsy Webpage](https://jagt.github.io/clumsy/) - the settings explanation there goes more into the actual mechanics of each individual setting. + + +### Network Link Conditioner (macOS) + +Apple's Network Link Conditioner can be downloaded from the [Additional Tools for XCode page](https://developer.apple.com/download/all/?q=Additional%20Tools). This page requires logging in with Apple developer account. +Download the version that's appropriate for your XCode version and then run the .dmg file. Navigate to the `Hardware` folder and install the Network Link Conditioner panel. + +After that you will be able to find Network Link Conditioner in the System Preferences panel of your Mac: +![nlc-in-system-preferences](../../../../static/img/nlc-in-system-preferences.png) + +To test the builds with Network Link Conditioner: + - Run Network Link Conditioner + - Run instance 1 + - Run instance 2 + - At any point you can adjust Network Link Conditioner settings and observe the changes in gameplay fidelity + +#### Settings quickstart + +In order to get to the settings we need to go into the `Manage Profiles` menu and either pick one or create our own. + + - Downlink and Uplink Bandwidth are useful for testing how our game would behave if it's starved for bandwidth, but generally tightening it too much would gradually degrade any networked game. + - Downlink and Uplink Packets Dropped % is exactly what it seems - packet loss percentage. + - Downlink and Uplink Delay are our levers for controling artificial latency + +### Network Link Conditioner (iOS) + +Apple's iOS also has it's version of Network Link Conditioner. + +Your iOS device needs to be enabled for development, then you'd be able to find Network Link Conditioner in Settings > Developer > Network Link Conditioner. + +### dummynet, dnctl and pftcl (macOS) + +**[dummynet](https://manpagez.com/man/8/dnctl/)** is a traffic shaper, delay and bandwidth manager utility that comes standard with the macOS. + + - **dnctl** is the command-line interface to operate the `dummynet` utiity. + - **pfctl** is the control interface for the internal firewall, which we can make obey dummynet rules, thus creating artificial network conditions on our host. + +To enable artificial conditions we need to create a `pf.conf` file in our user home directory with the following contents: +``` +#Testing udp, such as most realtime games and audio-video calls +dummynet in proto udp from any to any pipe 1 +dummynet out proto udp from any to any pipe 1 +``` + +Then we need to run the following commands in the console: +``` +sudo dnctl pipe 1 config delay 40 plr 0.1 +sudo dnctl show + +sudo pfctl -e +sudo pfctl -f pf.conf +``` + +:::warning +This set of commands enables dummynet, but when we are done testing - we should disable it, otherwise our system would continue to experience these artificial network conditions! +::: + +To disable dummynet execute the following: + +``` +sudo dnctl -q flush +sudo dnctl show + +sudo pfctl -e +sudo pfctl -f /etc/pf.conf +``` + +After you start dummynet, testing the builds is as easy as launching several instances of your game. + +#### Settings quickstart + - `bw` - this parameter controls bandwidth. + - `dnctl pipe 1 config bw 40Kbit/s` will set our bandwidth to 40 Kbit per second. + - `delay` - this parameter is our artifical latency. + - `dnctl pipe 1 config delay 100` will set our artifical latecny to 100 ms. + - `plr` - this parameter is our packet loss percentage. + - `dnctl pipe 1 config plr 0.1` will set our packet loss percetage to 10% + +You can chain these parameters to achieve a combination of these settings that will apply all of them at once: +`dnctl pipe 1 config bw 40Kbit/s delay 100 plr 0.1` diff --git a/versioned_sidebars/version-1.0.0-sidebars.json b/versioned_sidebars/version-1.0.0-sidebars.json new file mode 100644 index 000000000..9fdd27578 --- /dev/null +++ b/versioned_sidebars/version-1.0.0-sidebars.json @@ -0,0 +1,1061 @@ +{ + "version-1.0.0/netcode": [ + { + "type": "doc", + "id": "version-1.0.0/about" + }, + { + "collapsed": true, + "type": "category", + "label": "Getting Started", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/installation/install" + }, + { + "type": "doc", + "id": "version-1.0.0/installation/upgrade_from_mlapi" + }, + { + "type": "doc", + "id": "version-1.0.0/installation/upgrade_from_UNet" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Networking", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/basics/connection-approval" + }, + { + "type": "doc", + "id": "version-1.0.0/basics/max-players" + }, + { + "type": "doc", + "id": "version-1.0.0/basics/networkobject" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/networkobject-parenting" + }, + { + "type": "doc", + "id": "version-1.0.0/basics/networkbehavior" + }, + { + "type": "doc", + "id": "version-1.0.0/basics/networkvariable" + }, + { + "type": "doc", + "id": "version-1.0.0/basics/object-visibility" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/fastbufferwriter-fastbufferreader" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/networktime-ticks" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/physics" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/transports" + }, + { + "type": "doc", + "id": "version-1.0.0/relay/relay" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/session-management" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/reconnecting-mid-game" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Components", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/components/networkmanager" + }, + { + "type": "doc", + "id": "version-1.0.0/components/networktransform" + }, + { + "type": "doc", + "id": "version-1.0.0/components/networkanimator" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Objects", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/basics/object-spawning" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/object-pooling" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Messaging System", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/ways-synchronize" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/messaging-system" + }, + { + "collapsed": true, + "type": "category", + "label": "RPC Remote Procedure Call", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/message-system/clientrpc" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/message-system/serverrpc" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/message-system/reliability" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/message-system/execution-table" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/message-system/rpc-params" + }, + { + "collapsed": true, + "type": "category", + "label": "RPCs vs NetworkVariables", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/learn/rpcvnetvar" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/rpcnetvarexamples" + } + ] + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/message-system/rpc-compatibility" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Network Update Loop", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/network-update-loop-system/about-network-update-loop" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/network-update-loop-system/network-update-loop-reference" + } + ] + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/message-system/custom-messages" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Serialization", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/serialization/serialization-intro" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/serialization/cprimitives" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/serialization/unity-primitives" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/serialization/enum_types" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/serialization/arrays" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/serialization/inetworkserializable" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/custom-serialization" + }, + { + "type": "doc", + "id": "version-1.0.0/advanced-topics/serialization/networkobject-serialization" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Scene Management", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/basics/scenemanagement/scene-management-overview" + }, + { + "collapsed": true, + "type": "category", + "label": "Integrated Management", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/basics/scenemanagement/using-networkscenemanager" + }, + { + "type": "doc", + "id": "version-1.0.0/basics/scenemanagement/scene-events" + }, + { + "type": "doc", + "id": "version-1.0.0/basics/scenemanagement/timing-considerations" + }, + { + "type": "doc", + "id": "version-1.0.0/basics/scenemanagement/inscene-placed-networkobjects" + } + ] + }, + { + "type": "doc", + "id": "version-1.0.0/basics/scenemanagement/custom-management" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Testing ", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/tutorials/testing/testing_locally" + }, + { + "type": "doc", + "id": "version-1.0.0/tutorials/testing/testing_with_artificial_conditions" + }, + { + "type": "doc", + "id": "version-1.0.0/tutorials/testing/testing_client_connection_management" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Debugging", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/basics/logging" + }, + { + "type": "doc", + "id": "version-1.0.0/tutorials/testing/techniques_and_tricks_for_debugging_multiplayer_games" + }, + { + "type": "doc", + "id": "version-1.0.0/troubleshooting/troubleshooting" + }, + { + "type": "doc", + "id": "version-1.0.0/troubleshooting/errormessages" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Walk-Throughs", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/tutorials/helloworld" + }, + { + "collapsed": true, + "type": "category", + "label": "Learning Netcode with Goldenpath", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/tutorials/goldenpath_series/gp_intro" + }, + { + "type": "doc", + "id": "version-1.0.0/tutorials/goldenpath_series/goldenpath_one" + }, + { + "type": "doc", + "id": "version-1.0.0/tutorials/goldenpath_series/goldenpath_two" + } + ] + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Educational Samples", + "items": [ + { + "collapsed": true, + "type": "category", + "label": "Boss Room", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/learn/bossroom/bossroom" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/bossroom/bossroom-actions" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/bossroom/networkobject-parenting" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/bossroom/networkrigidbody" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/bossroom/spawn-networkobjects" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Bitesize Samples", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/learn/bitesize/bitesize-introduction" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/bitesize/bitesize-invaders" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/bitesize/bitesize-spaceshooter" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/bitesize/bitesize-clientdriven" + } + ] + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Community Contributions", + "items": [ + { + "collapsed": true, + "type": "category", + "label": "Code Monkey Tutorials", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/learn/codemonkey/codemonkey-video" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/codemonkey/codemonkey-complete" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Dilmer Tutorials", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/learn/dilmer/dilmer-video" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/dilmer/project-setup" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/dilmer/corefeatures" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/dilmer/networkanimator" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/dilmer/relay-service-setup" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Dapper Tutorials", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/learn/dapper/dapper-video" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/dapper/dapper-upgrade" + } + ] + } + ] + } + ], + "version-1.0.0/Multiplayer": [ + { + "type": "doc", + "id": "version-1.0.0/reference/glossary/high-level-terminology" + }, + { + "collapsed": true, + "type": "category", + "label": "Lag", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/reference/glossary/ticks-and-update-rates" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/lagandpacketloss" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/clientside_interpolation" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/dealing-with-latency" + } + ] + }, + { + "type": "doc", + "id": "version-1.0.0/reference/glossary/network-terms" + }, + { + "type": "doc", + "id": "version-1.0.0/reference/glossary/prioritization" + }, + { + "type": "doc", + "id": "version-1.0.0/reference/glossary/relevancy" + }, + { + "collapsed": true, + "type": "category", + "label": "Multiplayer Game Architecture", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/learn/multiplayer-game-arhitecture" + }, + { + "type": "doc", + "id": "version-1.0.0/reference/glossary/network-topologies" + }, + { + "type": "doc", + "id": "version-1.0.0/learn/listen-server-host-architecture" + } + ] + }, + { + "type": "doc", + "id": "version-1.0.0/learn/faq" + } + ], + "version-1.0.0/api": [ + { + "type": "doc", + "id": "version-1.0.0/api/introduction" + }, + { + "collapsed": true, + "type": "category", + "label": "Netcode", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.INetworkUpdateSystem" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkBehaviour" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkBehaviourUpdater" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkObjectReference" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkObject.SpawnDelegate" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkObject.VisibilityDelegate" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkTickSystem" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkUpdateLoop" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkUpdateStage" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.INetworkPrefabInstanceHandler" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkDelivery" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkEvent" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkPrefabHandler" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.BitCounter" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.BitReader" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.BitWriter" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.BufferSerializer-1" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.BytePacker" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.ByteUnpacker" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.FastBufferReader" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForEnums" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForFixedStrings" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForNetworkSerializable" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForPrimitives" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.FastBufferWriter.ForStructs" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.FastBufferWriter" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.INetworkSerializeByMemcpy" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.ForceNetworkSerializeByMemcpy-1" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkVariableWritePermission" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Time", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkTime" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkTimeSystem" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Configuration", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.HashSize" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkConfig" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Connection", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkClient" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.PendingClient" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.PendingClient.State" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Exceptions", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.InvalidChannelException" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.InvalidParentException" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkConfigurationException" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NotListeningException" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NotServerException" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.SpawnStateException" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.VisibilityChangeException" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Logging", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.LogLevel" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkLog" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Messaging", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.ClientRpcAttribute" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.ClientRpcParams" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.ClientRpcReceiveParams" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.ClientRpcSendParams" + }, + { + "collapsed": true, + "type": "category", + "label": "CustomMessagingManager", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.CustomMessagingManager" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.CustomMessagingManager.HandleNamedMessageDelegate" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.CustomMessagingManager.UnnamedMessageDelegate" + } + ] + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.RpcAttribute" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.RpcDelivery" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.ServerRpcAttribute" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.ServerRpcParams" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.ServerRpcReceiveParams" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.ServerRpcSendParams" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "NetworkManager", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkManager" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkManager.ConnectionApprovalRequest" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkManager.ConnectionApprovalResponse" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "NetworkVariable", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkVariableBase" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkVariable-1" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkVariable-1.OnValueChangedDelegate" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkVariableReadPermission" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.UserNetworkVariableSerialization-1" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "NetworkList-1", + "items": [ + { + "collapsed": true, + "type": "category", + "label": "NetworkList-1", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkList-1" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkList-1.OnListChangedDelegate" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "NetworkListEvent-1", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkListEvent-1" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkListEvent-1.EventType" + } + ] + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "SceneEvent", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.SceneEvent" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.SceneEventProgressStatus" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.SceneEventType" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "SceneManagement", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkSceneManager" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkSceneManager.SceneEventDelegate" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkSceneManager.VerifySceneBeforeLoadingDelegateHandler" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnEventCompletedDelegateHandler" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnLoadCompleteDelegateHandler" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnLoadDelegateHandler" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnSynchronizeCompleteDelegateHandler" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnSynchronizeDelegateHandler" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnUnloadCompleteDelegateHandler" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkSceneManager.OnUnloadDelegateHandler" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Serialization", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.Arithmetic" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.INetworkSerializable" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Spawning", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkSpawnManager" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "NetworkTransport", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.NetworkTransport" + } + ] + }, + { + "collapsed": true, + "type": "category", + "label": "Transports.UTP", + "items": [ + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.Transports.UTP.ErrorUtilities" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.Transports.UTP.INetworkStreamDriverConstructor" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.Transports.UTP" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.Transports.UTP.NetworkMetricsContext" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.ConnectionAddressData" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.ProtocolType" + }, + { + "type": "doc", + "id": "version-1.0.0/api/Unity.Netcode.Transports.UTP.UnityTransport.SimulatorParameters" + } + ] + } + ] +} diff --git a/versions.json b/versions.json index c48634a53..46cfea4ac 100644 --- a/versions.json +++ b/versions.json @@ -1,4 +1,5 @@ [ + "1.0.0", "current", "0.1.0" ]