Как заспавнить объект в unity
Unity spawn prefab at position tutorial
In this tutorial we going to cover how to use unity to spawn a prefab at a position, first we will be placing them at a fixed point and spawning them randomly later in the tutorial. For the purpose of this tutorial we going to use a very practical example where we will spawn terrain assets and both friendly npcs and enemy npcs. At the end of this tutorial you should have something that looks like this.
Unity spawn prefab at position tutorial
In order to get started create a new unity 3d project. Call it whatever you like the naming of the project isn’t important. Start off with a empty game object and rename it to game. We are in a later tutorial going to refer back to this project for a saving tutorial. For now create the structure as below in your inspector.
Parent main camera and light to the empty game object.
Create a flat terrain to spawn on
For this we will need to create two things. Create a empty game object call it level. Child it to the empty game object. Next create a plane game object and call it terrain and parent it to the level game object. Like below:
Level and terrain setup
Ground plane for our prefab spawner
Copy these settings for your ground panel transform.
plane transform settings unity spawn prefab
Create materials for our objects
We are going to create 3 materials for our 3 different objects. Namely a terrain object, a friend object and a enemy object. Start off by creating a material by right clicking in your assets folder.
Create materials for our prefabs
Create 4 of them and name them as per below:
You can assigned your own colors to your materials as you like. You can assign colors to your materials by clicking on each one and setting the albedo on your material like below.
Create our spawn prefabs
First create a prefabs folder in your assets folder. Like below:
Unity spawn prefab at position folder
In our hierarchy we want to create a few game objects. We will create a cube, cylinder and capsule. You can use whatever 3d object you like for your scene all will work for this tutorial because our c# scripting will determine the size of the 3d objects and place them correctly.
Rename your objects like below:
Make sure to add your materials so we can see our objects properly. So to do that select your object and just drag your mater onto their inspector. You should see something similar to this.
Now drag all your objects to the prefabs folder from the inspector this will then create your prefabs. You can now delete your objects from the hierarchy. Our prefabs are now created. Let us start with some scripting in the next section to start placing a prefab on our terrain.
Unity spawn prefab at position with c# script
Let’s start off by creating a Level Generator script. In order to do that click on your Level object in the hierarchy head over to the inspector and click on add component and type LevelGenerator and click add script. Open that up in visual studio and let’s start off with the code.
In our code what we going to do firstly is spawn a enemy prefab. To do this we just going to first setup some of our first bits of code. Then we will do more code around the variables we going to create.
So for our variables we want to define, a few game objects where we can assign our prefabs, we want to have a count for how many of each we want to spawn and a reference to our terrain object for later doing some calculations.
Lets add our variables.
To spawn a basic object add this to your script in the start method.
Before you will see anything spawn you will need to add your prefab to the inspector under your Level object like so. You can also add your terrain, friend and terrainAsset prefabs and objects as well. Add some amounts to the number of items you want to spawn.
This should give you one enemy spawned. On your terrain. So wow this is a great feeling we can now spawn something. Let’s expand this. Let’s create a method which can spawn any object for us. Create a method called GenerateObjects. Our code is going to look like this.
Explaining the spawn code
Let’s quickly explain this. The method will take in a gameobject and a count of the number we want to spawn. So we will first of all check if we have a valid gameobject so if it is null we don’t want to generate anything. Otherwise we loop until the amount of objects we want to create. Next we instantiate the game object and assign it to a temporary one. We then assign it a new vector3 which assigns it to 0.0 and 0.0 on the x and z axis we assign the y to its y position so its on top of our terrain. Let’s expand this by adding some randomness. For that we will build a GetRandomPoint function. This will get a random point on our terrain where we can spawn a object.
Coding our random point method
For our random point method we want to get the bounds of our terrain and use that to determine points which will fit one our terrain.
So here is the code.
For the bounds we use the collider of our terrain. So in order to use this we need to add the following line in our start method.
So back to our random point code. We get the minimum and maximum bounds of the z and x axis for our terrain. We need randomize between the min and max for both then return a vector3 with the random values. Don’t worry about the y axis as we will be replacing that in the GenerateObject method. I explain in more detail on the youtube video how you can avoid spawning objects in the same place as another object. So be sure to check out the video. To use our random method we need to change our GenerateObject method a bit. We going to change it to.
We simply get our random point and add it to our tmp game object transform. Great in our start method we can now call our GenerateObject method a few times.
This will generate your objects. We haven’t covered the UI elements and how to generate a bunch of friends, enemies and terrainObjects on the fly. If you want to see how that is done please watch the video tutorial on youtube.
Want to check out some other tutorials I have written here is a good one on unity 2d top down character controllers
Spawning GameObjects
Note: UNet is deprecated, and will be removed from Unity in the future. A new system is under development. For more information and next steps see this blog post and the FAQ. |
Once the GameObject is spawned using this system, state updates are sent to clients whenever the GameObject changes on the server. When Unity destroys the GameObject on the server, it also destroys it on the clients. The server manages spawned GameObjects alongside all other networked GameObjects, so that if another client joins the game later, the server can spawn the GameObjects on that client. These spawned GameObjects have a unique network instance ID called “netId” that is the same on the server and clients for each GameObject. The unique network instance ID is used to route messages set across the network to GameObjects, and to identify GameObjects.
When the server spawns a GameObject with a Network Identity** **component, the GameObject spawned on the client has the same “state”. This means it is identical to the GameObject on the server; it has the same Transform, movement state, and (if NetworkTransform and SyncVars are used) synchronized variables. Therefore, client GameObjects are always up-to-date when Unity creates them. This avoids issues such as GameObjects spawning at the wrong initial location, then reappearing at their correct position when a state update arrives.
The Network Manager can only spawn and synchronize GameObjects from registered Prefabs, so you must register the specific GameObject Prefabs with the Network Manager that you want to be able to spawn during your game. The Network Manager will only accept GameObject Prefabs which have a Network Identity component attached, so you must make sure you add a Network Identity component to your Prefab before trying to register it with the Network Manager.
To register a Prefab with the Network Manager in the Editor, select the Network Manager GameObject, and in the Inspector, navigate to the Network Manager component. Click the triangle next to Spawn Info to open the settings, then under Registered Spawnable Prefabs, click the plus (+) button. Drag and drop Prefabs into the empty field to assign them to the list.
The Network Manager Inspector with the Spawn Info* foldout expanded, displaying three assigned Prefabs under Registered Spawnable Prefabs
Spawning without the Network Manager
For more advanced users, you may find that you want to register Prefabs and spawn GameObjects without using the NetworkManager component.
To spawn GameObjects without using the Network Manager, you can handle the Prefab registration yourself via script. Use the ClientScene.RegisterPrefab method to register Prefabs to the Network Manager.
Example: MyNetworkManager
In this example, you create an empty GameObject to act as the Network Manager, then create and attach the MyNetworkManager script (above) to that GameObject. Create a Prefab that has a Network Identity component attached to it, and drag that onto the treePrefab slot on the MyNetworkManager component in the Inspector. This ensures that when the server spawns the tree GameObject, it also creates the same kind of GameObject on the clients.
Registering Prefabs ensures that the Asset is loaded with the Scene, so that there is no stalling or loading time for creating the Asset.
However, for the script to work, you also need to add code for the server. Add this to the MyNetworkManager script:
The server does not need to register anything, as it knows what GameObject is being spawned (and the asset ID is sent in the spawn message). The client needs to be able to look up the GameObject, so it must be registered on the client.
When writing your own network manager, it’s important to make the client ready to receive state updates before calling the spawn command on the server, otherwise they won’t be sent. If you’re using Unity’s built-in Network Manager component, this happens automatically.
For more advanced uses, such as object pools or dynamically created Assets, you can use the ClientScene.RegisterSpawnHandler method, which allows callback functions to be registered for client-side spawning. See documentation on Custom Spawn Functions for an example of this.
If the GameObject has a network state like synchronized variables, then that state is synchronized with the spawn message. In the following example, this script is attached to the tree Prefab:
With this script attached, you can change the numLeaves variable and modify the SpawnTrees function to see it accurately reflected on the client:
Attach the Tree script to the treePrefab script created earlier to see this in action.
Constraints
A NetworkIdentity must be on the root GameObject of a spawnable Prefab. Without this, the Network Manager can’t register the Prefab.
NetworkBehaviour scripts must be on the same GameObject as the NetworkIdentity, not on child GameObjects
GameObject creation flow
The actual flow of internal operations that takes place for spawning GameObjects is:
Prefab with Network Identity component is registered as spawnable.
GameObject is instantiated from the Prefab on the server.
Game code sets initial values on the instance (note that 3D physics forces applied here do not take effect immediately).
NetworkServer.Spawn() is called with the instance.
The state of the SyncVars on the instance on the server are collected by calling OnSerialize() on Network Behaviour components.
A network message of type MsgType.ObjectSpawn is sent to connected clients that includes the SyncVar data.
OnStartServer() is called on the instance on the server, and isServer is set to true
Clients receive the ObjectSpawn message and create a new instance from the registered Prefab.
The SyncVar data is applied to the new instance on the client by calling OnDeserialize() on Network Behaviour components.
OnStartClient() is called on the instance on each client, and isClient is set to true
As gameplay progresses, changes to SyncVar values are automatically synchronized to clients. This continues until game ends.
NetworkServer.Destroy() is called on the instance on the server.
A network message of type MsgType.ObjectDestroy is sent to clients.
OnNetworkDestroy() is called on the instance on clients, then the instance is destroyed.
Player GameObjects
Player GameObjects in the HLAPI work slightly differently to non-player GameObjects. The flow for spawning player GameObjects with the Network Manager is:
Prefab with NetworkIdentity is registered as the PlayerPrefab
Client connects to the server
Server receives message and calls NetworkManager.OnServerAddPlayer()
GameObject is instantiated from the PlayerPrefab on the server
NetworkManager.AddPlayerForConnection() is called with the new player instance on the server
A network message of type MsgType.Owner is sent to the client that added the player (only that client!)
The original client receives the network message
OnStartLocalPlayer() is called on the player instance on the original client, and isLocalPlayer is set to true
Because OnStartLocalPlayer is only called for the client’s local player GameObject, it is a good place to perform initialization that should only be done for the local player. This could include enabling input processing, and enabling camera tracking for the player GameObject.
Spawning GameObjects with client authority
To spawn GameObjects and assign authority of those GameObjects to a particular client, use NetworkServer.SpawnWithClientAuthority, which takes as an argument the NetworkConnection of the client that is to be made the authority.
For these GameObjects, the property hasAuthority is true on the client with authority, and OnStartAuthority() is called on the client with authority. That client can issue commands for that GameObject. On other clients (and on the host), hasAuthority is false.
For example, the tree spawn example above can be modified to allow the tree to have client authority like this (note that we now need to pass in a NetworkConnection GameObject for the owning client’s connection):
The Tree script can now be modified to send a command to the server:
Spawning GameObjects
Important: UNet is a deprecated solution, and a new Multiplayer and Networking The Unity system that enables multiplayer gaming across a computer network. More info See in Glossary Solution (Netcode for GameObjects) is under development. For more information and next steps see the information on the Unity Netcode for GameObjects website. |
Once the GameObject is spawned using this system, state updates are sent to clients whenever the GameObject changes on the server. When Unity destroys the GameObject on the server, it also destroys it on the clients. The server manages spawned GameObjects alongside all other networked GameObjects, so that if another client joins the game later, the server can spawn the GameObjects on that client. These spawned GameObjects have a unique network instance ID called “ netId A unique identifier given to an object instance to track it between networked clients and the server. More info
See in Glossary ” that is the same on the server and clients for each GameObject. The unique network instance ID is used to route messages set across the network to GameObjects, and to identify GameObjects.
When the server spawns a GameObject with a Network Identity** **component, the GameObject spawned on the client has the same “state”. This means it is identical to the GameObject on the server; it has the same Transform, movement state, and (if NetworkTransform A Networking component that allows you to synchronize the movements of GameObjects across the network. More info
See in Glossary and SyncVars are used) synchronized variables. Therefore, client GameObjects are always up-to-date when Unity creates them. This avoids issues such as GameObjects spawning at the wrong initial location, then reappearing at their correct position when a state update arrives.
The Network Manager A Networking component that manages the network state of a project. More info
See in Glossary can only spawn and synchronize GameObjects from registered Prefabs, so you must register the specific GameObject Prefabs with the Network Manager that you want to be able to spawn during your game. The Network Manager will only accept GameObject Prefabs which have a Network Identity component attached, so you must make sure you add a Network Identity component to your Prefab An asset type that allows you to store a GameObject complete with components and properties. The prefab acts as a template from which you can create new object instances in the scene. More info
See in Glossary before trying to register it with the Network Manager.
The Network Manager Inspector with the Spawn Info* foldout expanded, displaying three assigned Prefabs under Registered Spawnable Prefabs
Spawning without the Network Manager
For more advanced users, you may find that you want to register Prefabs and spawn GameObjects without using the NetworkManager component.
To spawn GameObjects without using the Network Manager, you can handle the Prefab registration yourself via script. Use the ClientScene.RegisterPrefab method to register Prefabs to the Network Manager.
Example: MyNetworkManager
In this example, you create an empty GameObject to act as the Network Manager, then create and attach the MyNetworkManager script (above) to that GameObject. Create a Prefab that has a Network Identity component attached to it, and drag that onto the treePrefab slot on the MyNetworkManager component in the Inspector. This ensures that when the server spawns the tree GameObject, it also creates the same kind of GameObject on the clients.
However, for the script to work, you also need to add code for the server. Add this to the MyNetworkManager script:
The server does not need to register anything, as it knows what GameObject is being spawned (and the asset ID is sent in the spawn message). The client needs to be able to look up the GameObject, so it must be registered on the client.
When writing your own network manager, it’s important to make the client ready to receive state updates before calling the spawn command on the server, otherwise they won’t be sent. If you’re using Unity’s built-in Network Manager component, this happens automatically.
For more advanced uses, such as object pools or dynamically created Assets, you can use the ClientScene.RegisterSpawnHandler method, which allows callback functions to be registered for client-side spawning. See documentation on Custom Spawn Functions for an example of this.
If the GameObject has a network state like synchronized variables, then that state is synchronized with the spawn message. In the following example, this script is attached to the tree Prefab:
With this script attached, you can change the numLeaves variable and modify the SpawnTrees function to see it accurately reflected on the client:
Attach the Tree script to the treePrefab script created earlier to see this in action.
Constraints
A NetworkIdentity A Networking component that allows you to assign an identity to your GameObject for the network to recognize it as a Local Player GameObject or a Server Only GameObject. More info
See in Glossary must be on the root GameObject of a spawnable Prefab. Without this, the Network Manager can’t register the Prefab.
NetworkBehaviour scripts A piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary must be on the same GameObject as the NetworkIdentity, not on child GameObjects
GameObject creation flow
The actual flow of internal operations that takes place for spawning GameObjects is:
Prefab with Network Identity component is registered as spawnable.
GameObject is instantiated from the Prefab on the server.
Game code sets initial values on the instance (note that 3D physics forces applied here do not take effect immediately).
NetworkServer.Spawn() is called with the instance.
The state of the SyncVars on the instance on the server are collected by calling OnSerialize() on Network Behaviour components.
A network message of type MsgType.ObjectSpawn is sent to connected clients that includes the SyncVar data.
OnStartServer() is called on the instance on the server, and isServer is set to true
Clients receive the ObjectSpawn message and create a new instance from the registered Prefab.
The SyncVar data is applied to the new instance on the client by calling OnDeserialize() on Network Behaviour components.
OnStartClient() is called on the instance on each client, and isClient is set to true
As gameplay progresses, changes to SyncVar values are automatically synchronized to clients. This continues until game ends.
NetworkServer.Destroy() is called on the instance on the server.
A network message of type MsgType.ObjectDestroy is sent to clients.
OnNetworkDestroy() is called on the instance on clients, then the instance is destroyed.
Player GameObjects
Player GameObjects in the HLAPI work slightly differently to non-player GameObjects. The flow for spawning player GameObjects with the Network Manager is:
Prefab with NetworkIdentity is registered as the PlayerPrefab
Client connects to the server
Server receives message and calls NetworkManager.OnServerAddPlayer()
GameObject is instantiated from the PlayerPrefab on the server
NetworkManager.AddPlayerForConnection() is called with the new player instance on the server
A network message of type MsgType.Owner is sent to the client that added the player (only that client!)
The original client receives the network message
OnStartLocalPlayer() is called on the player instance on the original client, and isLocalPlayer is set to true
Because OnStartLocalPlayer is only called for the client’s local player GameObject, it is a good place to perform initialization that should only be done for the local player. This could include enabling input processing, and enabling camera A component which creates an image of a particular viewpoint in your scene. The output is either drawn to the screen or captured as a texture. More info
See in Glossary tracking for the player GameObject.
Spawning GameObjects with client authority
To spawn GameObjects and assign authority of those GameObjects to a particular client, use NetworkServer.SpawnWithClientAuthority, which takes as an argument the NetworkConnection of the client that is to be made the authority.
For these GameObjects, the property hasAuthority is true on the client with authority, and OnStartAuthority() is called on the client with authority. That client can issue commands for that GameObject. On other clients (and on the host), hasAuthority is false.
For example, the tree spawn example above can be modified to allow the tree to have client authority like this (note that we now need to pass in a NetworkConnection GameObject for the owning client’s connection):
The Tree script can now be modified to send a command to the server: