Is there any way to remove component from Gameobject using script?
For example:
I add FixedJoint
to player by script, connect object to it (for grabbing), and when I drop it I want to remove the FixedJoint (because, I can't just "disable" joint). How can I do it?
Yes, you use the Destroy function to destroy/remove a component from a GameObject. It can be used to remove Component or GameObject.
If you know you won't be using that component again, however, you can either right-click on the name of the component or click the cog icon at the top-right corner of the component to open a menu. Click Remove Component.
Yes, you use the Destroy
function to destroy/remove a component from a GameObject. It can be used to remove Component or GameObject.
Add Component:
gameObject.AddComponent<FixedJoint>();
Remove Component:
FixedJoint fixedJoint = GetComponent<FixedJoint>();
Destroy(fixedJoint);
To experiment with Programmers correct answer, I created an extension-method so you can use gameObject.RemoveComponent(/* true if immediate */) because I felt there should a method like this.
If you'd want to use it you'd create a new class anywhere with the following code:
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);
}
}
}
}
and then to use it like you'd do with AddComponent<>()
gameObject.RemoveComponent<FixedJoint>();
It will be accessible in any method that extends MonoBehaviour. You can also add more methods to this static extension class, just use the "this"-syntax as parameter to extend a certain Unity type. For instance if you add following method (from the 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);
}
you would use transform.ResetTransformation();
in any of your scripts to invoke it. (Making the class look like:)
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With