[英]Add a script to a new game object during run time
I am making a game in unity... my script cuts a mesh body into 2 other mesh bodies.我正在统一制作游戏……我的脚本将一个网状体切割成另外 2 个网状体。 How can I add a script to the new body during run time?
如何在运行时向新主体添加脚本?
Each chunk needs to add a script of name XRGrabInteractable.每个块都需要添加一个名为 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
}
}
Use GameObject.AddComponent<ScriptName>()
:使用
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.