2017-02-09 20 views
3

スクリプトを使用してGameObjectからコンポーネントを削除する方法はありますか?例えばスクリプトからコンポーネントを削除する

:私はスクリプトによってプレイヤーにFixedJointを追加

、(つかむために)それにオブジェクトを接続し、私はそれをドロップすると、私はちょうど「無効」ことができない、ので、私はFixedJointを(削除したいですジョイント)。どうしたらいいですか?

答えて

5

はい、Destroy関数を使用して、ゲームオブジェクトからコンポーネントを破棄/削除します。コンポーネントやゲームオブジェクトを削除するのに使用できます。

は、コンポーネントを追加します。

gameObject.AddComponent<FixedJoint>(); 

をコンポーネントを削除します。

FixedJoint fixedJoint = GetComponent<FixedJoint>(); 
Destroy(fixedJoint); 
+0

大歓迎です! – Programmer

+1

@AlexandrKölnあなたは質問のタイトルを「解決済み」に変更しません。あなたは答えを受け入れると(http://meta.stackexchange.com/a/5235)、システムはそれを解決済みとマークします。 – Programmer

+1

ああ、もう一度感謝します。 :)初回はSO –

2

プログラマ正しい答えを試してみるために、あなたがgameObject.RemoveComponentを使用できるように即時の場合、私は真(/ *拡張メソッドを作成しました* /)このような方法があるはずです。

あなたがそれを使用したいと思います場合は、任意の場所に次のコードを使用して新しいクラスを作成したい:あなたはAddComponent <をどうしたいようにそれを使用して、その後

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

     } 
    } 
} 

をして>()

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); 
    } 
} 
関連する問題