Unityの道具管理に関するいくつかのテクニック

2048 ワード

Unityにおける道具管理に関する設計モデル
ゲーム开発では多くのアイテムを统一管理する必要がある场合に简単な工场+単例を使って実现します.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Prop:MonoBehaviour {
    //       
    private string name;
    private bool IsOwn;
    private int allNum;
    
    public virtual void Use() { }
    public virtual void Add() { }
    public virtual void Dele() { }
    public virtual int GetAllNum() { return allNum;}

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

public class PropMgr : MonoBehaviour {

    public static PropMgr instance;    //        
    public Dictionary OwnProp;  //    ,         
    public Dictionary AllProp;  //     

    private void Awake()
    {
        instance = this;
        AllProp = new Dictionary();  //     
        OwnProp = new Dictionary(); //     
    }

    public void Use(string propName) { }     //       ,     ,      ,    
    public void Add(string propName) { }
    public void Dele(string propName) { }
    public void GetAllNum(string propName){ }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test1 : Prop {
    private string name = "Test1";
    private bool IsOwn = false;
    private int allNum = 0;
    
    private void Start()
    {
        PropMgr.instance.AllProp.Add(name, this); //              
    }

    public override void Use() {
        Debug.Log("Test1    .");
    }
    public override void Add() {

        Debug.Log("Test1    .");
    }
    public override void Dele() {
        Debug.Log("Test1    .");
    }

    public override int GetAllNum(){
        return allNum;
    }
}

アイデアは、すべてのアイテムのベースクラスを作成し、このクラスから継承するのはすべてアイテムで、シーンがロードされたとき、あるいはアイテムが新しく作成されたとき、それをアイテム管理クラスのすべてのアイテム辞書にロードし、キャラクタが持つアイテムに追加するときに、アイテム名を適切な方法に渡すことです.それから辞書で遍歴して直接道具の中の方法を呼び出します.