MRが楽しい

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

HoloLens2でホロモンアプリを作る その122(アイテムの初期設定をAddComponent時に実行する)

本日はアプリ作成枠です。
HoloLens2でホロモンアプリを作る進捗を書き留めていきます。
今回はアイテムの初期設定を AddComponent 時に実行するようにしました。

AddComponent 時の処理

MonoBehaviour の継承クラスで Reset 関数を実装することで AddComponent 時の処理を定義できます。
docs.unity3d.com

例えばホロモンの遊具アイテムの基底クラスに以下のように Reset 関数を定義しました。

using HoloMonApp.Content.Character.Model.ObjectInteractions.HoldItem;
using UniRx;
using UnityEngine;
using UnityEngine.Serialization;

namespace HoloMonApp.Content.SupportItem.Objects.Artifacts
{
    [RequireComponent(typeof(Collider))]
    [RequireComponent(typeof(Rigidbody))]
    public abstract class ItemArtifactAccessAPI : BItemAccessAPI, IHoloMonItemHoldAccess
    {
        [Header("Artifact")]
        [Header("コントローラ")]
        /// <summary>
        /// 状態コントローラ
        /// </summary>
        [SerializeField] private ArtifactStatusControl _artifactStatusControl;
        
        /// <summary>
        /// 物理コントローラ
        /// </summary>
        [SerializeField] private ArtifactPhysicsControl _artifactPhysicsControl;

        /// <summary>
        /// AddComponentまたはリセット時処理
        /// </summary>
        protected override void Reset()
        {
            _artifactStatusControl = new ArtifactStatusControl(this);
            _artifactPhysicsControl = new ArtifactPhysicsControl(this);
            base.Reset();
        }
        // 略
    }
}

例えば物理コントローラは物理演算系の処理を行うため、インスタンス生成時にコライダーとリジッドボディの参照を取得するようにしています。
・ArtifactPhysicsControl.cs

using System;
using HoloMonApp.Content.Character.Model.ObjectInteractions.HoldItem;
using UnityEngine;

namespace HoloMonApp.Content.SupportItem.Objects.Artifacts
{
    [Serializable]
    public class ArtifactPhysicsControl
    {
        [Header("設定")]
        
        [SerializeField] private Collider itemCollider;

        [SerializeField] private Rigidbody itemRigidbody;

        public ArtifactPhysicsControl(Component component)
        {
            itemCollider = component.GetComponent<Collider>();
            itemRigidbody = component.GetComponent<Rigidbody>();
        }
        // 略
    }
}

これでコライダーとリジッドボディを設定したゲームオブジェクトに本スクリプトを AddComponent で設定するだけで必要な参照を取得してくれるようになりました。