しっぽを追いかけて

ぐるぐるしながら考えています

Unity と猫の話題が中心   掲載内容は個人の私見であり、所属組織の見解ではありません

Unity の UI Toolkit で動的にスタイルを変更してみる

※ これは 2021/09/10 時点の Unity 2021.2.0b11 の情報です

最新版では動作が異なる可能性がありますのでご注意ください

引き続き Unity の UI Toolkit を試す

データバインディング的なものがないか探してみたけど残念ながらバイディングは UnityEditor 限定みたいなのでとりあえず保留

今回は追加したボタンのラベルをプログラマブルに変更してみたい

ラベルのスタイル切り替え

例によってボタンを押したら赤字・太字・斜体文字に切り替わるように

さくっとやる場合は MainView.cs を下記のように書き換えれば良さげ

using UnityEngine;
using UnityEngine.AI;
using UnityEngine.InputSystem;
using UnityEngine.UIElements;

public class MainView : MonoBehaviour
{
    [SerializeField]
    private GameObject tapEffect = null;

    [SerializeField]
    private GameObject agentPrefab = null;

    [SerializeField]
    private Cat cat = null;

    [SerializeField]
    private Cat chaser = null;

    [SerializeField]
    private UIDocument uIDocument = null;

    private NavMeshAgent catAgent = null;
    private NavMeshAgent chaserAgent = null;
    private Button button = null;

    public void Start()
    {
        // NavMeshAgent を生成し、ねこキャラと連携させる
        this.catAgent = Instantiate(this.agentPrefab, this.cat.transform.position, Quaternion.identity, this.transform)
            .GetComponent<NavMeshAgent>();
        this.chaserAgent = Instantiate(this.agentPrefab, this.chaser.transform.position, Quaternion.identity, this.transform)
            .GetComponent<NavMeshAgent>();

        // 白ねこは速く
        this.catAgent.speed = 3.5f;
        this.catAgent.angularSpeed = 120f;
        this.catAgent.acceleration = 8f;

        // トラねこは遅く
        this.chaserAgent.speed = 2f;
        this.chaserAgent.angularSpeed = 60f;
        this.chaserAgent.acceleration = 4f;

        this.cat.Agent = this.catAgent;
        this.chaser.Agent = this.chaserAgent;

        // UIDocument から Button を取得してイベントハンドラを設定
        this.button = this.uIDocument.rootVisualElement.Query<Button>().First();
        this.button.clicked += OnButtonClicked;
        this.button.text = "Not clicked";
    }

    private void OnButtonClicked()
    {
        this.button.text = "Clicked";
        this.button.style.color = new StyleColor(Color.red);
        this.button.style.unityFontStyleAndWeight = FontStyle.BoldAndItalic;
    }

    public void Update()
    {
        // ねこキャラを追いかけさせる
        this.chaser.Agent.SetDestination(this.cat.transform.position);
    }

    public void OnFire(InputAction.CallbackContext context)
    {
        var target = Camera.main.ScreenToWorldPoint(Mouse.current.position.ReadValue());
        this.cat.Agent.SetDestination(target);

        // タップ跡を表示
        var effect = Instantiate(this.tapEffect, (Vector2)target, Quaternion.identity, this.transform);

        // 1秒後に消滅
        Destroy(effect, 1f);
    }
}

赤字・太字・斜体にしているのはこのあたり

    private void OnButtonClicked()
    {
        this.button.text = "Clicked";
        this.button.style.color = new StyleColor(Color.red);
        this.button.style.unityFontStyleAndWeight = FontStyle.BoldAndItalic;
    }

さっそくお試し実行

スタイル切り替え

なるほどできた