懶得創建GameObject,懶得創建Tag,懶得設定Tag,懶得添加腳本,懶得每次都要獲取參考的懶癌患者福音
老規矩,不想看博客的直接下載,傳送門
MVC簡介:MVC
小專案就不建議用框架,避免過度設計,
上代碼:
Model塊:(資料、邏輯層)
using UnityEngine;
public class Model : MonoBehaviour
{
}
View塊:(視圖層)
using UnityEngine;
public class View : MonoBehaviour
{
void Awake()
{
}
void Start()
{
}
}
Control塊:(控制中轉層)
using UnityEngine;
public class Control : MonoBehaviour
{
private Model _model;
internal Model Model
{
get
{
if (_model != null)
{
return _model;
}
else
{
_model = GameObject.FindWithTag("Model").GetComponent<Model>();
return _model;
}
}
set
{
if (_model != null)
{
_model = value;
}
else
{
_model = GameObject.FindWithTag("Model").GetComponent<Model>();
_model = value;
}
}
}
private View _view;
internal View View
{
get
{
if (_view != null)
{
return _view;
}
else
{
_view = GameObject.FindWithTag("View").GetComponent<View>();
return _view;
}
}
set
{
if (_view != null)
{
_view = value;
}
else
{
_view = GameObject.FindWithTag("View").GetComponent<View>();
_view = value;
}
}
}
}
BaseControl:(父類,省去控制器每次都要獲取中轉控制層Control的麻煩,相關控制器只需繼承即可)
using UnityEngine;
public class BaseControl : MonoBehaviour
{
private Control _ctrl;
internal Control Ctrl
{
get
{
if (_ctrl != null)
{
return _ctrl;
}
else
{
_ctrl = GameObject.FindWithTag("Control").GetComponent<Control>();
return _ctrl;
}
}
set
{
if (_ctrl != null)
{
_ctrl = value;
}
else
{
_ctrl = GameObject.FindWithTag("Control").GetComponent<Control>();
_ctrl = value;
}
}
}
}
GameManager層:(游戲控制層)
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
public class GameManager : BaseControl
{
void Awake()
{
}
void Update()
{
}
#region 動態創建tag、物體、掛載腳本
[ContextMenu("添加設定標簽")]
void Add()
{
#if UNITY_EDITOR
AddTag<Model>("Model");
AddTag<View>("View");
AddTag<Control>("Control");
#endif
}
void AddTag<T>(string tag) where T : Component
{
if (!isHasTag(tag))
{
GameObject obj = new GameObject(tag);
obj.AddComponent<T>();
SerializedObject tagManager = new SerializedObject(obj);//序列化物體
SerializedProperty it = tagManager.GetIterator();//序列化屬性
while (it.NextVisible(true))//下一屬性的可見性
{
if (it.name == "m_TagString")
{
//Debug.Log(it.stringValue);
it.stringValue = tag;
tagManager.ApplyModifiedProperties();
}
}
}
}
bool isHasTag(string tag)
{
foreach (var t in UnityEditorInternal.InternalEditorUtility.tags)
{
if (t.Equals(tag))
return true;
}
return false;
}
#endregion
}
主要做了什么:
匯入GameManager預制體,點擊一下即可一鍵生成、掛載、設定物體,
看圖


懶癌患者請收下
創建的時候只做了 沒有tag的判斷再創建,已有tag沒做判斷,想完善你們自己搞吧,搞完發我一份,謝謝
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/77133.html
標籤:其他
下一篇:飛機游戲代碼(JAVA)
