MRが楽しい

MRやVRについて学習したことを書き残す

HoloLens2でEnvironment.UserNameでのユーザ名の取得を試す

本日は HoloLens2 の小ネタ枠です。
HoloLens2 で Environment.UserName でのユーザ名の取得を試した結果を記事にします。

Environment.UserName

現在のスレッドに関連付けられているユーザー名を取得する API です。
通常 Windows PC 上で本 API を実行すると、現在実行中の PC のユーザ名が表示されます。
docs.microsoft.com

合わせて、Environment.UserDomainName の取得値も確認してみました。
こちらは実行中の PC のコンピュータ名が表示されます。
docs.microsoft.com

試験アプリの作成

Text コンポーネントに結果を表示する試験アプリを作成しました。
f:id:bluebirdofoz:20210510232950j:plain

以下の通り、スクリプトから API を叩いて取得した文字列を Text に反映します。
・ConfirmUsername.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ConfirmUsername : MonoBehaviour
{
    [SerializeField, Tooltip("表示コンポーネント")]
    private ShowText p_ShowText;

    // Start is called before the first frame update
    void Start()
    {
        List<string> messageTextList = new List<string>();

        // ユーザ名を追加
        messageTextList.Add(System.Environment.UserName);

        // ドメイン名を追加
        messageTextList.Add(System.Environment.UserDomainName);
        
        p_ShowText.SetText(messageTextList.ToArray());
    }
}

・ShowText.cs

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

public class ShowText : MonoBehaviour
{
    /// 表示テキスト
    /// </summary>
    private Text p_Text;

    // Start is called before the first frame update
    void Awake()
    {
        p_Text = this.GetComponent<Text>();
    }

    /// <summary>
    /// テキストの設定
    /// </summary>
    /// <param name="a_messageTextList"></param>
    public void SetText(string[] a_messageTextList)
    {
        p_Text.text = "";
        foreach (string messageText in a_messageTextList)
        {
            p_Text.text += messageText + Environment.NewLine;
        }
    }
}

HoloLens2上での動作結果

HoloLens2上での動作させた結果、ユーザ名は Unknown が返り、コンピュータ名は取得できました。
f:id:bluebirdofoz:20210510233003j:plain