Cod*_*ing 0 c# button unity-game-engine destroy unityscript
我很难尝试在C#中添加和删除js脚本作为游戏对象的组件,因为我是Unity和编码的新手.
我有一个需要在运行时在MainCamera中添加的js,点击GUI.Button.稍后必须使用相同的GUI销毁此脚本.单击按钮.
我已设法在运行时使用以下代码片段在MainCamera上添加js脚本:
public Bearing addBearing; // "Bearing" is the js script and "addBearing the variable to reference this
//some other codding
.
.
// Add and remove Bearing with this button
public bool addBearing;
void OnGUI(){
if(GUI.Button(new Rect(10,10, 100, 100), "Bearing"))
addBearing= !addBearing;
if(addBearing){
addBearing = GameObject.FindGameObjectWithTag("MainCamera").gameObject.AddComponent<Bearing>();
}else{
GameObject.FindGameObjectWithTag("MainCamera").gameObject.GetComponent<Bearing>();
Destroy(GetComponent<Bearing>());
Run Code Online (Sandbox Code Playgroud)
问题是,当我点击"Bearing"GUI.Button时,js脚本"Bearing"不会被破坏.
这段代码逻辑中缺少一些东西,但我在编写C#以找到解决方案方面没有经验.那么,有人可以帮助我帮忙解决这个问题吗?非常感谢.谢谢大家的答案.
小智 5
而不是添加和销毁,你为什么不使用
GetComponent(Bearing).enabled = false; 禁用和
GetComponent(Bearing).enabled = true; 启用