2016-09-22 9 views
-1

enter image description hereボタンのテキストをUnityでクリックして変更したいと思います。私はC#の初心者です。親切に私を助けて!ボタンのテキストをUNITYでクリックして変更するにはどうすればいいですか?

私は私のbutton要素

using UnityEngine; 
using System.Collections; 
using UnityEngine.UI; 

public class Buttontextchange : MonoBehaviour { 

Text Buy; 


    // Use this for initialization 
    void Start() { 
    Buy = transform.FindChild("Text").GetComponent<Text>(); 
    } 

    // Update is called once per frame 
    void Update() { 

    } 

public void clicked() 
{ 
Debug.Log("Button Buy Clicked!"); 
Buy.text = "i am a button!"; 

} 
} 

に追加したスクリプトは、私は答えの多くを試してみましたが、そのは私のために出て働いていません!キャンバスの中にボタンがあります。あなたの助けは非常に高く評価されています! enter image description here

+0

これを行うあなたは、任意のエラーを取得していますか? –

+0

ボタンコンポーネントを見つける必要があります。クリックセクションで+をクリックし、スクリプトをスロットにドラッグします。次にドロップダウンでメソッドを見つけることができます。あなたはそれを見逃していたと思います。 – Everts

+0

私は既に@Evertsについて言及したことを試しましたが、変更されていません。 –

答えて

1

あなたの問題は、テキストとボタンの設定から発生します。

ButtontextchangeコンポーネントはButtontextオブジェクト上にあります。私は、オブジェクトには子供がいないことを画像上で見ることができます。しかし、実行する:

void Start() { 
    Buy = transform.FindChild("Text").GetComponent<Text>(); 
} 

これはおそらくエラーが発生しています。 TextオブジェクトはButtonオブジェクトの下にあり、onClick呼び出しで渡すことができます。

public class Buttontextchange : MonoBehaviour 
{ 
    public void clicked(Text textRef) 
    { 
     Debug.Log("Button Buy Clicked!"); 
     textRef.text = "i am a button!"; 
    } 
} 

次に、インスペクタで、テキストオブジェクトをパラメータスロットにドラッグします。

EDIT:ユーザーがクリックしたときにボタンの色を変更したい:

public class Buttontextchange : MonoBehaviour 
{ 
    public void clicked(Gameobject buttonObj) 
    { 
     Debug.Log("Button Buy Clicked!"); 
     Text text = buttonObj.GetComponentInChildren<Text>(true); 
     if(text != null){ 
      textRef.text = "i am a button!";´ 
     } 
     Image image = buttonObj.GetComponent<Image>(); 
     if(image != null){ 
      image.color = newColor; 
     } 
    } 
} 
+0

ありがとう!あなたは私の一日を救った!あなたは常にソリューションを見つけるのを手伝っています:)おかげでたくさん! –

+0

色を変更しました。パラメータはもはやTextコンポーネントではなく、親GameObjectであることに注意してください。あなたのケースでは、画像上で強調表示されたボタンオブジェクト。 – Everts

+0

お返事ありがとう! –

0

あなたはTextプロパティに公共 C#のキーワードが欠落しています。私はスクリプトを少し変更して、Unity Editorからテキストとボタンの参照を割り当てることができます。

public class Buttontextchange : MonoBehaviour 
{ 

    public Button BuyButton; 
    public Text BuyText; 

    void Start() 
    { 
     BuyButton.onClick.AddListener(OnButtonClicked); 
     if (BuyText == null) 
      BuyText = BuyButton.GetComponentInChildren<Text>(); 
    } 

    public void OnButtonClicked() 
    { 
     Debug.Log("Button Buy Clicked!"); 
     BuyText.text = "i am a button!"; 
    } 

} 
+0

ありがとうございます。しかし、以下のエラーが発生しています。NullReferenceException:オブジェクト参照がオブジェクトのインスタンスに設定されていません。 Buttontextchange.clicked()(Assets/Buttontextchange.cs:17)@Paradox Forge –

+0

これは、 "BuyText "検査官の変数。私はあなたがする必要がないようにスクリプトを適応させました。 –

+0

ありがとうございました!それは今働いています:) –

0

ちょうどクリックイベント後 Button.GetComponentInChildren(Text).text = "Button Clicked";