Version: 2021.3
言語: 日本語
ViewData の永続性

Manage UI asset references from C# scripts

Unity represents UXML files as VisualTreeAsset objects in C# and represents USS files as StyleSheet objects in C#. Since VisualTreeAsset and StyleSheet are regular Unity assets, you can use Unity’s standard workflows to manage them.

シリアル化参照を使用する

Unity automatically detect fields from your C# scripts which are of type VisualTreeAsset or StyleSheet. You can use the Inspector to set references to specific UXML or USS files imported in your project. Such references remain valid even when the location of your assets change in your project.

スクリプトでこれを使用するには 3 つの方法があります。

説明 How to display the Inspector Where is the reference saved?
カスタムスクリプトのインスタンス (MonoBehaviour など) スクリプトのインスタンスを保持しているゲームオブジェクトを選択します。 シーン内
EditorWindow または Editor から派生したスクリプトのデフォルトの参照 Project ブラウザーで実際の C# ファイルを選択します。 スクリプトに関連するメタファイル内
ScriptableObject から派生した、プロジェクト内のカスタムアセット Project ブラウザーのアセットを選択します。 アセット本体のシリアル化されたデータ内

Note: The default references works for all scripts that derive from MonoBehaviour or ScriptableObject. It provides a way to populate default values for serialized fields of scripts.

以下の例の MonoBehaviour クラスは、Inspector から UXML ファイルのリストと USS ファイルを受け取ります。

using UnityEngine;
using UnityEngine.UIElements;

public class MyBehaviour : MonoBehaviour
{
  // Note that public fields are automatically exposed in the Inspector
  public VisualTreeAsset mainUI;
  [Reorderable]
  public StyleSheet[] seasonalThemes;
}

以下の例の EditorWindow クラスは、Inspector からデフォルトの参照を受け取ります。

using UnityEditor;
using UnityEngine.UIElements;

public class MyWindow : EditorWindow
{
  [SerializeField]
  private VisualTreeAsset uxml;
  [SerializeField]
  private StyleSheet uss;
}

アセットデータベースを使用する (エディターのみ)

AssetDatabase クラスを使用すると、パスまたは GUID で UI Asset をロードできます。

以下の例は、アセットをパスで検索する方法を示しています。

VisualTreeAsset asset = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/Editor/main_window.uxml");
StyleSheet asset = AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/Editor/main_styles.uss");

Use Addressables

Addressables システムは、アプリケーションのコンテンツを整理してパッケージ化するためのツールやスクリプト、およびランタイムにアセットをロードして解放するための API を提供します。

UXML と USS アセットを Addressable システムで使用できます。

Unityで任意のアセットに Addressables を設定する方法については、Getting started with Addressables を参照してください。

Resources フォルダーを使用する

If you add a Resources folder in your project and place your UI assets in it, you can use the Resources.Load method to load your assets.

The following examples shows how to load an asset in the Resource folder:

VisualTreeAsset uxml = Resources.Load<VisualTreeAsset>("main_window");
StyleSheet uss = Resources.Load<StyleSheet>("main_styles");

Note: This method comes with significant downsides in terms of workflows and final build size. Unity recommends you to use the Addressables system instead.

ViewData の永続性