Unity 实例化物体并赋予父物体操作如下:
- public class ExampleScript : MonoBehaviour
- {
- public GameObject prefab; // 引用预制体
- public Transform parentTran; // 引用父物体的 Transform
-
- void Update()
- {
- if (Input.GetKeyDown(KeyCode.Space))
- {
- // 在当前物体的位置和旋转下实例化一个新的物体
- GameObject Obj = Instantiate(prefab, transform.position, transform.rotation);
-
- // 将新物体设置为父物体的子对象
- Obj .transform.SetParent(parentTran);
- }
- }
- }
1、实例化使用方法:Instantiate函数。
public static void Instantiate(GameObject toInstantiate, Vector3 position = new Vector3(), Quaternion rotation = new Quaternion());
使用 Instantiate 方法有两种主要方式:
此外,还可以使用 Instantiate 方法来实例化预制体(Prefab)。在这种情况下,需要传递一个 Prefab 对象和一个 Vector3 参数来指定物体的位置。例如,Instantiate(prefab, new Vector3(1, 2, 3)) 将实例化一个位于 (1, 2, 3) 位置的预制体。如果预制体有父对象,新实例化的对象将自动成为其子对象。
2、设置父物体的方法是SetParent。