Unity-利用反射动态给对象添加脚本

it2023-11-13  70

using System.Collections; using System.Collections.Generic; using UnityEngine; public interface ILoader { GameObject LoadPrefab(string path, Transform parent = null); } using System.Collections; using System.Collections.Generic; using UnityEngine; public class ResLoader : ILoader { public GameObject LoadPrefab(string path,Transform parent = null) { GameObject prefab = Resources.Load<GameObject>(path); GameObject temp = Object.Instantiate(prefab, parent); return temp; } } using System; using System.Collections; using System.Collections.Generic; using UnityEngine; //此处单例请参考 DesinModel 中的单例模式 public class LoadMgr : NormalSingleton<LoadMgr> { //当前使用的加载器 private ILoader _loader; public LoadMgr() { //指定加载器 _loader = new ResLoader(); } public GameObject LoadPrefab(string path,Transform parent = null) { GameObject temp = _loader.LoadPrefab(path, parent); Type type = Type.GetType(temp.name.Remove(temp.name.Length - 7)); temp.AddComponent(type); return temp; } } using System.Collections; using System.Collections.Generic; using UnityEngine; public class LaunchGame : MonoBehaviour { void Start () { LoadMgr.Instance.LoadPrefab("Prefab/StartView", transform); } }
最新回复(0)