Unity 简单的特效管理

在战斗场景中,角色的战斗通常需要加载许多特效,重复加载特效会影响运行效率,可以写一些简单的代码来管理。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class EffectManager
{
	public static Dictionary<int, GameObject> effectMap = new Dictionary<int, GameObject>();
	//entry是特效的唯一标识
	private static GameObject GetEffectPrefab(int entry)
	{
		GameObject found = null;
		effectMap.TryGetValue(entry, out found);
		return found;
	}
	//加载了一个特效,就放到map里
	public static void AddEffectPrefab(int entry, GameObject objEffect)
	{
		if (effectMap.ContainsKey(entry))
		{
			return;
		}            

		effectMap[entry] = objEffect;
	}
	//切换场景时调用
	public static void Clear()
	{
		effectMap.Clear();
	}
	//可以预先加载一些特效资源
	public static void PreLoadPrefab(Dictionary<int, GameObject> prefabs)
	{
		foreach(var item in prefabs)
		{
			AddEffectPrefab(item.Key, item.Value);
		}
	}
	//获取特效接口,onCreated为回调方法
	public static void CreateEffect(int entry,Vector3 pos, Quaternion rot,System.Action<GameObject> onCreated)
	{
		GameObject objEffect = GetEffectPrefab(entry);
		//如果在map中存在的话,直接获取并实例化
		if(objEffect != null)
		{
			GameObject objCreated = GameObject.Instantiate(objEffect, pos, rot) as GameObject;
			if(onCreated != null)
			{
				onCreated(objEffect)
			}
			return;
		}

		//否则先加载,并添加到map中,最后实例化
		//EffectLoader.Load 是伪函数,用于加载资源,并执行回调
		EffectLoader.Load(entry, (UnityEngine.Object objPrefab) => 
		{ 
			if(objPrefab !=null)
			{
				AddEffectPrefab(template.entry, objPrefab as GameObject);
				GameObject objCreated = GameObject.Instantiate(objEffect, pos, rot) as GameObject;
				if(onCreated != null)
				{
					onCreated(objEffect)
				}
			}
		});
	}
}

加载场景时,先执行Clear,有需要的话执行PreLoadPrefab,这两步都放在loading界面还未关闭的情况下执行。这样可以避免一些卡顿。

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页