从脚本中删除组件

有没有办法使用脚本从Gameobject中删除组件?

例如:

我通过脚本将FixedJoint添加到播放器,将对象连接到它(用于抓取),当我放下它时我想删除FixedJoint(因为,我不能只是“禁用”关节)。 我该怎么做?

是的,您使用Destroy函数来销毁/删除GameObject中的组件。 它可用于删除Component或GameObject。

添加组件:

 gameObject.AddComponent(); 

删除组件:

 FixedJoint fixedJoint = GetComponent(); Destroy(fixedJoint); 

为了试验程序员的正确答案,我创建了一个扩展方法,这样你就可以使用gameObject.RemoveComponent(/ *如果是立即* /,则为true),因为我觉得应该有这样的方法。

如果你想使用它,你可以使用以下代码在任何地方创建一个新类:

 using UnityEngine; public static class ExtensionMethods { public static void RemoveComponent(this GameObject obj, bool immediate = false) { Component component = obj.GetComponent(); if (component != null) { if (immediate) { Object.DestroyImmediate(component as Object, true); } else { Object.Destroy(component as Object); } } } } 

然后像使用AddComponent <>()一样使用它

 gameObject.RemoveComponent(); 

它可以通过任何扩展MonoBehaviour的方法访问。 您还可以向此静态扩展类添加更多方法,只需使用“this”-syntax作为参数来扩展某个Unity类型。 例如,如果你添加以下方法(来自扩展方法教程 )

 public static void ResetTransformation(this Transform trans) { trans.position = Vector3.zero; trans.localRotation = Quaternion.identity; trans.localScale = new Vector3(1, 1, 1); } 

你会使用transform.ResetTransformation(); 在任何脚本中调用它。 (让class级看起来像:)

 using UnityEngine; public static class ExtensionMethods { public static void RemoveComponent(this GameObject obj, bool immediate = false) { Component component = obj.GetComponent(); if (component != null) { if (immediate) { Object.DestroyImmediate(component as Object, true); } else { Object.Destroy(component as Object); } } } public static void ResetTransformation(this Transform trans) { trans.position = Vector3.zero; trans.localRotation = Quaternion.identity; trans.localScale = new Vector3(1, 1, 1); } }