Как сделать спавн объектов unity
Вступление:
Понадобится несколько картинок для туториала. Я набросал заготовку в пэинте. Скачать можно тут.*
*возможно некотрые браузеры просто откроют картинку вместо скачивания, сделайте правый клик на картинку и выберите сохранить. Или правый клик на линке и выбрать сохранить цель.
1. Шаг
— Запускаете Юнити. В стартовом окошке выбираете New
— Даёте название проекту
— Выбираете локацию для записи
— Выбираете 2D
— Нажимаете Create Project
Через некоторое время откроется редактор. Важные части для нас будут:
1. Сцена окно, где будет делаться игровая сцена
2. Камера эта область показывает видимую область сцены через камеру
3. Иерархия окно со списком игровых объектов в сцене
4. Инспектор настройка выбранного игрового объекта
5. Проект корневая система папок
6. Ассеты папки, модели, звуки, спрайты, скрипты и тд., то из чего делаете игру
7. Сцена ярлык окошка сцены
8. Игра ярлык игровой камеры
9. Play/Pause/StepPlay кнопки запуска и остановки игры
Вид редактораа можно настроить по своему вкусу. Я пока оставлю стандартный вид.
2. Шаг
Для игры понадобится 4 картинки («земля», «сачок», «плохой предмет», «хороший предмет»).
1. Возможность
Как я уже и говорил, можете скачать мою картинку( Картинка). Надо будет импортировать картинку в Юнити. Правый клик Assets и выбираете Import New Asset... Идете в папку куда скачали картинку, выбираете её catch2DImage и нажимаете Import.
Картинка должна появится в окошке Assets. Но нам надо 4 картинки для этого туториала («земля», «сачок», «плохой предмет», «хороший предмет»). Мы можем указать Юнити, что это multiple (многочисленная) картинка и мы сможем выделить с неё 4 картинки. Выберите catch2DImage в Assets. Потом идете в Inspector и ставите Sprite Mode на Multiple. Кликаете на Apply.
Теперь можно выделить 4 нужные картинки. Картинка должна быть выделенна. Идете опять в Inspector и кликаете на Sprite Editor.
Откроется новое окошко Sprite Editor. Кликаете на Slice. Оставляете все как стоит и кликаете на Slice кнопку. Кликаете на Apply.Над каждой картинкой должен появится четырехугольник. Временами приходится поправить его размер. Закрываете окошко Sprite Editor.
Теперь можно развернуть картинку в Assets. Если все получилось, то вы должны увидеть 4 картинки в развернутом виде.
2. Возможность
Можно использовать и свои картинки. Просто импортируете 4 своих картинки в Юнити. Правый клик в окошко Assets и выбираете Import New Asset... Идёте в вашу папку, выбираете нужные картинки и нажимаете Import.
3. Возможность
Другой путь для импорта объектов в Юнити это просто перетаскивание файлов (drag&drop) в окошко Assets.
3. Шаг
Order in Layer:
Нажимаете Play старта сцены. Нажимаете Play повторно для возвращения назад к Scene.
Collider:
4. Шаг
Rigidbody:
— Order in Layer можно оставить равным 0.
Запустите сцену. сачок должен начать падать и потом остановиться на земле. Нажмите на старт повторно и вернитесь к сцене.
В окошке Assets будет теперь 2 файла (ну или больше, если используете свои картинки).
Откройте playerMove C# скрипт (двойной клик, или правый клик и выбрать open). Откроется C# редактор. Там будет уже стоять заготовка для вашего скрипта. Выглядит примерно так:
Может быть небольшая разница в стиле, если используется другой редактор. Это не важно.
Input Manager:
Теперь мы можем получить три значения из Input Manager (-1 or 0 or 1), в зависимости от нажатых кнопок. И в зависимости от полученного значения из Input Manager мы можем менять velocity (скорость) нашего Player в его Rigidbody2D.
Velocity:
Теперь можем сделать C# скрипт для движения. Надеюсь вы знакомы с основой С#.
— Нам нужна float переменная для скорости. Сделайте её public, так у нас будет доступ к ней через Inspector и сможем выставлять её значение не открывая скрипт. Ещё понадобится float переменная значения Horizontal оси. И переменная Vector2 установки скорости и направления движения в Rigibody2D.
using UnityEngine;
using System.Collections;
public class playerMove : MonoBehaviour <
//видимая из редактора Юнити, float переменная для скорости (лево/право) Player
public float speed;
//переменная для ссылки на компонент Rigibody2D от Player
Rigidbody2D rb;
//float переменная для оси Horizontal из Input Manager
float x;
//Vector2 переменная для просчитанного вектора движения, используется для изменения velocity
Vector2 move;
//функция выполняется 1 раз при старте скрипта
void Start () <
//делаем линк на Rigidbody2D компонент
rb = GetComponent Rigidbody2D > ();
>
5. Шаг
Collider is Trigger:
using UnityEngine;
using System.Collections;
public class timeDestroyer : MonoBehaviour <
//время жизни объекта
public float aliveTimer;
//исполняется 1 раз при запуске скрипта
void Start () <
//уничтожит текущий объект через заданное время
Destroy (gameObject, aliveTimer);
>
>
Выделите Fish в Hierarchy. Перейдите в Inspector и добавьте timeDestroyer скрипт. Поменяйте Alive Timer на 5.
Пока у нас только один объект Fish в Scene. Позже нам понадобится большее количество. Мы можем сделать заготовку для клонирования Fish. В Юнити для этого используется Prefab.
Prefab:
6. Шаг
После того как сделали Prefab от Bomb, выделите Bomb в Hierarchy и удалите этот объект.
7. Шаг
Нам нужна переменная для игрового объекта RightSide (мы сможем получить нужную позицию Transform для спавна с этого объекта).
2Д и Z-ось:
Transform:
using UnityEngine;
using System.Collections;
public class ItemSpawn : MonoBehaviour <
//объект, из которого мы будем считать правую границу спавна
public GameObject RightSide;
//массив с объектами для спавна
public GameObject [] items;
//float переменные: задержка первого спавна и его период
public float startDelay, repeatRate;
Выделите Spawner в Hierarchy. Добавьте скрипт спавна к нему. Перетащите RightSide из Hierarchy на RightSideполе в скрипте. Разверните массив для предметов (кликните на Items). Заполните его образцами предметов (переташите Fish и Bomb из Assets на Items). Размер массива должен стать 2. Измените delay и rate на 2 каждую (можете настроить потом по желанию).
Можете запустить сцену для теста.
8. Step
OnTrigger. вызовы:
using UnityEngine;
using System.Collections;
public class itemChecker : MonoBehaviour <
//переменная для результата
public int score;
Выделите Player в Hierarchy. Добавьте itemChecker к нему в Inspector.
Сохраните сцену как catchGame. Выделите Player и запустите сцену. Вы должны увидеть как меняется Score (в Inspector у Player).
скачать готовый проект этого туториала.
Object Spawning
In Unity, creating new game objects with Instantiate() is sometimes called “spawning”. In the network HLAPI the word “spawn” is used to mean something more specific. In the server authoritative model of the network HLAPI, to “spawn” an object on the server means that the object should be created on clients connected to the server, and the object will be managed by the spawning system. Once in the spawning system, state updates are sent to clients when the object changes on the server, and the object will be destroyed on clients when it is destroyed on the server. Spawned objects are also added to the set of networked objects that the server is managing, so that if another client joins the game later, the objects will also be spawned on that client. These objects have a unique network instance Id called “netId” that is the same on the server and clients for each object. This is used to route messages to objects and to identify objects.
When NetworkIdentity objects are spawned on clients, they are created with the current state of the object on the server. This applies to the object’s transform, movement state and synchronized variables. So client objects will always be up-to-date when they are created. This avoids issues such as objects being spawned at a wrong initial location, then popping to their correct position when a state update packet arrives.
This sounds great, but there are some immediate questions that this brings up. How is the object created on the clients? And, what if the objects changes in between the time when it is spawned and another client connects? Which version of the object is spawned for the new client then?
Spawning of objects on clients instantiates the client object from the prefab of the object that was passed to NetworkServer.Spawn on the server. The NetworkIdentity inspector preview panel shows the Asset ID of the NetworkIdentity, it is this value that identifies the prefab so that the client can create the objects. For this to work efficiently, there is a registration step that clients have to perform; they must call ClientScene.RegisterPrefab to tell the system about the asset that the client object will be created from.
Registration of spawn prefabs is most conveniently done by the NetworkManager in the editor. The “Spawn Info” section of the NetworkManager allows you to register prefabs without writing any code. This can also be done through code when a NetworkClient is created. To do it in code:
In this example, the user would drag a prefab asset onto the alienPrefab slot on the MyNetworkManager script. So that when a alien object is spawned on the server, the same kind of object will be created on the clients. This registration of assets ensures that the asset is loaded with the scene, so that there is no stall to load the asset when it is created. For more advanced use cases such as object pools or dynamically created assets, there is ClientScene.RegisterSpawnHandler which allows callback functions to be registered for client side spawning.
Below is a simple example of a spawner that creates a tree with a random number of leaves.
When this code runs, the tree objects created on clients will have the correct value for numLeaves from the server.
Constraints
Object Creation Flow
The actual flow of operations that takes place for spawning is:
Player Objects
Player objects in the network HLAPI are special in some ways. The flow for spawning player objects with the NetworkManager is:
Note that OnStartLocalPlayer() is called after OnStartClient(), as it only happens when the ownership messages arrives from the server after the player object is spawned. So isLocalPlayer will not be set in OnStartClient().
Since OnStartLocalPlayer is only called for YOUR player, 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 object. Typically only the local player has an active camera.
Spawning Object with Client Authority
It is possible to spawn objects and assign authority of the objects to a particular client. This is done with NetworkServer.SpawnWithClientAuthority, which takes the NetworkConnection of the client that will be made the authority as an argument.
For these objects, the property hasAuthority will be true on the client with authority and OnStartAuthority() will be called on the client with authority. That client will be able to issue commands for that object. On other clients (and on the host), hasAuthority will be false.
Objects spawned with client authority must have LocalPlayerAuthority set in their NetworkIdentity.
For example, to allow a player to spawn and control an object:
Object Spawning
In Unity, creating new game objects with Instantiate() is sometimes called “spawning”. In the network HLAPI the word “spawn” is used to mean something more specific. In the server authoritative model of the network HLAPI, to “spawn” an object on the server means that the object should be created on clients connected to the server, and the object will be managed by the spawning system. Once in the spawning system, state updates are sent to clients when the object changes on the server, and the object will be destroyed on clients when it is destroyed on the server. Spawned objects are also added to the set of networked objects that the server is managing, so that if another client joins the game later, the objects will also be spawned on that client. These objects have a unique network instance Id called “netId” that is the same on the server and clients for each object. This is used to route messages to objects and to identify objects.
When NetworkIdentity objects are spawned on clients, they are created with the current state of the object on the server. This applies to the object’s transform, movement state and synchronized variables. So client objects will always be up-to-date when they are created. This avoids issues such as objects being spawned at a wrong initial location, then popping to their correct position when a state update packet arrives.
This sounds great, but there are some immediate questions that this brings up. How is the object created on the clients? And, what if the objects changes in between the time when it is spawned and another client connects? Which version of the object is spawned for the new client then?
Spawning of objects on clients instantiates the client object from the prefab of the object that was passed to NetworkServer.Spawn on the server. The NetworkIdentity inspector preview panel shows the Asset ID of the NetworkIdentity, it is this value that identifies the prefab so that the client can create the objects. For this to work efficiently, there is a registration step that clients have to perform; they must call ClientScene.RegisterPrefab to tell the system about the asset that the client object will be created from.
Registration of spawn prefabs is most conveniently done by the NetworkManager in the editor. The “Spawn Info” section of the NetworkManager allows you to register prefabs without writing any code. This can also be done through code when a NetworkClient is created. To do it in code:
In this example, the user would drag a prefab asset onto the alienPrefab slot on the MyNetworkManager script. So that when a alien object is spawned on the server, the same kind of object will be created on the clients. This registration of assets ensures that the asset is loaded with the scene, so that there is no stall to load the asset when it is created. For more advanced use cases such as object pools or dynamically created assets, there is ClientScene.RegisterSpawnHandler which allows callback functions to be registered for client side spawning.
Below is a simple example of a spawner that creates a tree with a random number of leaves.
When this code runs, the tree objects created on clients will have the correct value for numLeaves from the server.
Constraints
Object Creation Flow
The actual flow of operations that takes place for spawning is:
Player Objects
Player objects in the network HLAPI are special in some ways. The flow for spawning player objects with the NetworkManager is:
Note that OnStartLocalPlayer() is called after OnStartClient(), as it only happens when the ownership messages arrives from the server after the player object is spawned. So isLocalPlayer will not be set in OnStartClient().
Since OnStartLocalPlayer is only called for YOUR player, 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 object. Typically only the local player has an active camera.
Spawning Object with Client Authority
It is possible to spawn objects and assign authority of the objects to a particular client. This is done with NetworkServer.SpawnWithClientAuthority, which takes the NetworkConnection of the client that will be made the authority as an argument.
For these objects, the property hasAuthority will be true on the client with authority and OnStartAuthority() will be called on the client with authority. That client will be able to issue commands for that object. On other clients (and on the host), hasAuthority will be false.
Objects spawned with client authority must have LocalPlayerAuthority set in their NetworkIdentity.
For example, to allow a player to spawn and control an object:
Did you find this page useful? Please give it a rating:
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