How to use Unity’s Instantiate

I. Introduction

When I first started learning game development, I was always ambiguous about the method of instantiation. Looking at other people's examples, I sometimes used new and sometimes used Instantiate. A familiar usage of new is to create an object, generally used for instantiation of a class; Instantiate is a method in Unity, generally used for instantiation of Prefab (prefab) . The following mainly introduces the usage of Instantiate

2. Usage of Instantiate

When using Instantiate, its properties are consistent with the original object. Since it is instantiating a prefab, you can think of the parameters it contains: ① What is the prefab? ② What is the position and direction? ③ Where is it mounted?

So there are several ways to apply Instantiate:

Instantiate (Object original): Clone the object original, and its Position and Rotation take the default values. What are the default values? It is the position of the prefabricated body. The position here is the world coordinate. There is no parent object.
Instantiate(Object original, Transform parent): The clone object original has a parent object. Its Position and Rotation take the default values. The position here is the local position, which is relative. Based on the coordinates of the parent object, the parent object is the origin of the coordinates.
Instantiate(Object original, Transform parent, bool instantiateInWorldSpace):
If instantiateInWorldSpace=false, it means that the coordinates of the cloned object are localposition, and the result is the same as Instantiate(Object original, Transform parent) .
If instantiateInWorldSpace=true, it means that the coordinates of the cloned object are world coordinates.
Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent): This is easier to understand. The cloned object original has a parent object, and its Position and Rotation are artificially determined. Setting, and the coordinates set here are world coordinates, not localposition

reference:

A rough explanation of (Unity)Instantiate icon-default.png?t=N658https://blog.csdn.net/weixin_43913272/article/details/90246161

 

Guess you like

Origin blog.csdn.net/weixin_43195011/article/details/131628726