Unity(ver:2020.3.12f1)で、ScrollViewを使ってテキストを表示します。
Scroll Viewの作成
プロジェクト「ScrollViewTest」を作成し、メニュー「GameObject」から「UI」→「Scroll View」を選択します。
Hierarchyから「Canvas」以下に配置された「Scrollbar Horizontal」を削除します。
Hierarchyには次のように表示されます。
Scroll Viewの設定
Hierarchyで「Scroll View」を選択し、Inspectorから次のように設定します。
- Rect Transform
- Scroll Rect
「Width」:200
「Height」:200
「Anchor Presets」アイコン(十字シンボル)クリック:center・middle
「Horizontal」:チェックを外す
「Horizontal Scrollbar」:「None」
設定した結果を次に示します。
Contentの設定
Hierarchyで「Content」を選択し、Inspectorから次のように設定します。
- 「Add Component」ボタンをクリックして、次のコンポーネントの追加
- Rect Transform
- Content Size Fitter
UI → Text
Layout → Content Size Fitter
「Text」:「1」~「18」
「Color」:黒
「Vertical Fit」:「Preferred Size」
設定した結果を次に示します。
スクリプトの作成
ログを保存するスクリプトを作成します。ログの最大保存数を「100」とし、超えると古いログから捨てます。
Unityのスクリプトテンプレートを次のように作成します。
作成したスクリプトを次に示します。作成したスクリプト「NewBehaviourScript.cs」は、HierarchyのMainCameraにドラッグ&ドロップします。
- 47行目でGameObject「Content」のComponent「Text」をアクセスし、48行目でテキストをブランクに設定します。
NewBehaviourScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
using UnityEngine.UI;
using System;
public class NewBehaviourScript : MonoBehaviour
{
private Text logText;
private List<string> allLogs;
private int allLogDataNum = 100;
private StringBuilder logTextStringBuilder;
int num = 0;
// ログテキストの追加
void AddLogText(string logdata)
{
// ログテキストの追加
allLogs.Add(logdata);
// ログの最大保存数を超えたら古いログを削除
if (allLogs.Count > allLogDataNum)
{
allLogs.RemoveRange(0, allLogs.Count - allLogDataNum);
}
// ログテキストの表示
logTextStringBuilder.Clear();
List<string> selectedLogs = new List<string>();
selectedLogs = allLogs;
foreach (var log in selectedLogs)
{
logTextStringBuilder.Insert(0, log + Environment.NewLine);
}
logText.text = logTextStringBuilder.ToString().TrimEnd();
}
// Start is called before the first frame update
void Start()
{
Debug.Log("Start!!");
allLogs = new List<string>();
logTextStringBuilder = new StringBuilder();
logText = GameObject.Find("Content").GetComponent<Text>();
logText.text = "";
AddLogText("Start!!");
}
// Update is called once per frame
void Update()
{
Debug.Log("Update!!");
AddLogText("Update!! : " + num);
num++;
}
}
Unityの実行
ゲームをプレーすると書き込んだログが次のように表示され、ConsoleにDebug.Logで出力した文字列が表示されます。





