【发布时间】:2017-02-09 19:32:37
【问题描述】:
有没有办法使用脚本从游戏对象中删除组件?
例如:
我通过脚本将FixedJoint 添加到玩家,将对象连接到它(用于抓取),当我放下它时,我想移除 FixedJoint(因为我不能只是“禁用”关节)。我该怎么做?
【问题讨论】:
有没有办法使用脚本从游戏对象中删除组件?
例如:
我通过脚本将FixedJoint 添加到玩家,将对象连接到它(用于抓取),当我放下它时,我想移除 FixedJoint(因为我不能只是“禁用”关节)。我该怎么做?
【问题讨论】:
是的,您使用Destroy 函数从游戏对象中销毁/移除组件。可用于移除组件或游戏对象。
添加组件:
gameObject.AddComponent<FixedJoint>();
移除组件:
FixedJoint fixedJoint = GetComponent<FixedJoint>();
Destroy(fixedJoint);
【讨论】:
DestroyImmediate 是另一种方法。建议不要使用它,因为它会立即销毁,而Destroy 将在下一帧中销毁。不过,它的存在对 OP 来说是件好事。
You are strongly recommended to use Object.Destroy always. Destroy is executed at a safe time. DestroyImmediate happens immediately.
DestroyImmediate。
为了试验程序员的正确答案,我创建了一个扩展方法,以便您可以使用 gameObject.RemoveComponent(/* true if immediate */) 因为我觉得应该有这样的方法。
如果您想使用它,您可以使用以下代码在任何地方创建一个新类:
using UnityEngine;
public static class ExtensionMethods
{
public static void RemoveComponent<Component>(this GameObject obj, bool immediate = false)
{
Component component = obj.GetComponent<Component>();
if (component != null)
{
if (immediate)
{
Object.DestroyImmediate(component as Object, true);
}
else
{
Object.Destroy(component as Object);
}
}
}
}
然后像使用 AddComponent()
一样使用它gameObject.RemoveComponent<FixedJoint>();
它可以在任何扩展 MonoBehaviour 的方法中访问。您还可以为这个静态扩展类添加更多方法,只需使用“this”-syntax 作为参数来扩展某个 Unity 类型。例如,如果您添加以下方法(来自extension method tutorial)
public static void ResetTransformation(this Transform trans)
{
trans.position = Vector3.zero;
trans.localRotation = Quaternion.identity;
trans.localScale = new Vector3(1, 1, 1);
}
您可以在任何脚本中使用transform.ResetTransformation(); 来调用它。 (让类看起来像:)
using UnityEngine;
public static class ExtensionMethods
{
public static void RemoveComponent<Component>(this GameObject obj, bool immediate = false)
{
Component component = obj.GetComponent<Component>();
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);
}
}
【讨论】: