LoginSignup
34
31

More than 5 years have passed since last update.

C#上でCanvasからUIオブジェクトを取り出す方法

Posted at

Unity上でcreateから作れるから、TextとかButtonとかUI下にあるオブジェクトはGameObjectの亜種だと勘違いしてました...

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

public class Initialize : MonoBehaviour {

    public Canvas canvas;

    // Use this for initialization
    void Start () {
        Text target = null;
        foreach (Transform child in canvas.transform){
            if(child.name == "Main Title"){
                target = child.gameObject;
                target.text = "AAAAAAA";
            } else if (child.name == "Sub Title") {
                target = child.gameObject;
                target.text = "BBBBBBB";
            }
        }
    }

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

    }
}

と書いたら華麗にエラーが起きたので、どうした物かと悩んでいたんですが、TextのInspectorをよく見た所、
kobito.1410434614.075755.png
(Script)なる文言が...

という事は、UIオブジェクト群って コンポーネント だったんですね...恥ずかしい...

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

public class Initialize : MonoBehaviour {

    public Canvas canvas;

    // Use this for initialization
    void Start () {
        Text target = null;
        foreach (Transform child in canvas.transform){
            if(child.name == "Main Title"){
                target = child.gameObject.GetComponent<Text>();
                target.text = "AAAAAAA";
            } else if (child.name == "Sub Title") {
                target = child.gameObject.GetComponent<Text>();
                target.text = "BBBBBBB";
            }
        }
    }

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

    }
}

kobito.1410434887.363529.pngkobito.1410434928.686063.png

無事"Main Title"と"Sub Title" Textの文言の変更出来た!

34
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
34
31