Unity Instantiate Prefabs

mac2024-05-23  27

教程地址(观看视频需翻墙):

https://learn.unity.com/tutorial/destructible-crate?language=en&courseId=5cf06bd1edbc2a58d7fc3209&projectId=5ce68f0bedbc2a060d4a348f#5ce68826edbc2a0491575325

实现功能:

1. 初始化预制物体;

2. 使用数组调用子物体组件;

3. 使用foreach遍历添加属性;

public GameObject fracturedCrat;

    void Update()     {         if (Input.GetKeyDown(KeyCode.Space))         {

//初始化预制物体 Instantiate(fracturedCrat, transform.position, Quaternion.identity),后面这句是为了调用每个子物体组件而演变的             GameObject fracturedCrateObj=Instantiate(fracturedCrat, transform.position, Quaternion.identity)as GameObject;

//使用数组储存子物体的组件信息             Rigidbody[] allrigidBodies = fracturedCrateObj.GetComponentsInChildren<Rigidbody>();             if (allrigidBodies.Length > 0)    //只要数组中有rigidbody的信息就会执行下面的代码             {                 foreach (var body in allrigidBodies)    //遍历所有元素,然后给每天元素添加爆炸力属性                 {                     body.AddExplosionForce(500, transform.position, 1);                 }             }             Destroy(this.gameObject);         }     }

最后效果如下图所示:fracturedCrat就是小球预设

最新回复(0)