从脚本中删除组件
有没有办法使用脚本从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); } }
- Silverlight中附加和非附加依赖属性的区别
- 无法将数据列从一个数据表复制到另一个数据表
- 如何返回SaveFileDialog的完整路径?
- 在传递带有已修改行的DataRow集合时,Update需要有效的UpdateCommand
- 在IQueryable上调用ProjectTo ()时,AutoMapper抛出StackOverflowException
- c#已启用CORS的Web Api和所请求资源上存在可怕的“Access-Control-Allow-Origin”标头
- C#Count()扩展方法性能
- 使用Entity Framework Code First时创建外键属性有什么意义?
- 从升级过程开始非升级过程