Unityを学ぼう【第6回】

前回を続きまして、
テキストを表示します*1

概要

  • 回収したアイテム数表示
  • 目標達成表示

以上項目を画面に表示します

回収したアイテム数表示

GUIText配置
 1.[ツールバー] -> [GameObject] -> [Create Other] -> [GUI Text]
   名前:Count Text
 2.画面の左上に設定
   [Inspector] -> [Transform] -> Position(0,1,0)
    参考:GUIの座標
    f:id:kou_yeung:20131023225904p:plain
 3.オフセット設定
   [Inspector] -> [GUIText] -> Pixel Offset(10,-10)
スクリプト拡張
// Player Controller.cs
public class PlayerController : MonoBehaviour
{
    public float speed;
    public GUIText countText; // 追加:[Count Text]保存用変数
    private int count;        // 追加:取得数保存用変数

    //==========================
    // 追加:スクリプト開始時に呼ばれます
    void Start()
    {
        count = 0;       // 取得数を0に初期化
        SetCountText();  // 取得数テキスト設定
    }
    // ここまで
    //==========================
    ...
    void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.tag == "PickUp") {
            other.gameObject.SetActive(false);
            count = count + 1;  // 追加:アイテム衝突したらカウンター+1
            SetCountText();     // 追加:取得数保存用変数
        }
    }
    //==========================
    // 追加:取得数テキスト設定
    void SetCountText()
    {
        countText.text = "Count : " + count.ToString();
    }
    // ここまで
    //==========================
}
Count Textとスクリプトを関連付ける
 1.[Hierarchy] -> [Player] を選択
 2.[Count Text] を [Player Controller]に設定
  f:id:kou_yeung:20131023232740p:plain
実行&テスト

プレイヤーがアイテム回収したら
ウンターが正しく動作するかどうかを確認する

目標達成表示

GUIText配置
 1.[ツールバー] -> [GameObject] -> [Create Other] -> [GUI Text]
   名前:Win Text
 2.画面の左上に設定
   [Inspector] -> [Transform] -> Position(0,0.75,0)
 3.テキストの表示設定
   [Inspector] -> [GUIText] -> Anchor(middle center) Alignment(center)
スクリプト拡張
// Player Controller.cs
public class PlayerController : MonoBehaviour
{
    public float speed;
    public GUIText countText;
    public GUIText winText;   // 追加:[Win Text]保存用変数
    private int count;

    void Start()
    {
        count = 0;
        SetCountText();
        winText.text = "";  // 空白文字列に初期化
    }
    ...
    void SetCountText()
    {
        countText.text = "Count : " + count.ToString();
        // 追加:アイテムが12個配置されたため、
        //       カウンターが12以上なら[真]になる
        if(count >= 12) {
            winText.text = "You Win!";  // 追加:"You Win!"文字列表示
        }
    }
}
Count Textとスクリプトを関連付ける
 1.[Hierarchy] -> [Player] を選択
 2.[Count Text] を [Player Controller]に設定
  f:id:kou_yeung:20131023234849p:plain
実行&テスト

アイテムを全部回収したら
"You Win!"が表示されることを確認する

GUITextをグループ化

管理しやすいように、作成したGUITextをグループにまとめる

 1.[ツールバー] -> [GameObject] -> [Create Empty]
   名前:Display Text
 2.[Count Text] と [Win Text] を [Display Text] に ドラッグ&ドロップ

これで、一通りUnityの基本要素を使ってみた

次回予告:WebPlayerで公開する

*1:http://unity3d.com/learn/tutorials/projects/roll-a-ball/displaying-text