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);
}
}