[英]Add a script to a new game object during run time
我正在統一制作游戲……我的腳本將一個網狀體切割成另外 2 個網狀體。 如何在運行時向新主體添加腳本?
每個塊都需要添加一個名為 XRGrabInteractable 的腳本。
foreach(GameObject chunk in pieces){
if(chunk.GetComponent<BoxCollider>()){//change to collider type of first object
Destroy(chunk.GetComponent<BoxCollider>());
}
//Add rigid body if not alread
if(!chunk.GetComponent<Rigidbody>()){//Add Rigid body if not true
chunk.AddComponent<Rigidbody>();
}
//Add Mesh Colider(might interere with xr script that requires collider)
if(!chunk.GetComponent<MeshCollider>()){//If no mesh colider mesh colider for new chunk
chunk.AddComponent<MeshCollider>();//Add Mesh colider if it doesn't exist
chunk.GetComponent<MeshCollider>().convex = true;//Change To Convex Mesh so that it doesn't fall through floor
}
}
使用GameObject.AddComponent<ScriptName>()
:
foreach(GameObject chunk in pieces){
chunk.AddComponent<XRGrabInteractable>();
if(chunk.GetComponent<BoxCollider>()){//change to collider type of first object
Destroy(chunk.GetComponent<BoxCollider>());
}
//Add rigid body if not alread
if(!chunk.GetComponent<Rigidbody>()){//Add Rigid body if not true
chunk.AddComponent<Rigidbody>();
}
//Add Mesh Colider(might interere with xr script that requires collider)
if(!chunk.GetComponent<MeshCollider>()){//If no mesh colider mesh colider for new chunk
chunk.AddComponent<MeshCollider>();//Add Mesh colider if it doesn't exist
chunk.GetComponent<MeshCollider>().convex = true;//Change To Convex Mesh so that it doesn't fall through floor
}
}
原來我只需要使用...
using UnityEngine.XR.Interaction.Toolkit;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.