Unity业务抽象套路一、SCP ScriptableObject-Component-Prefab

发布时间 2023-09-03 00:22:50作者: bakabird1998

[CreateAssetMenu(menuName = "ScriptObjectItem/FooStat")]
public class FooStat : ScriptableObject {
	public string name;
}
public class BaseCom : MonoBehaviour {
	public FooStat stat;
	public virtual void Apply()
	{
		Debug.Log("stat name is " + stat.name);
	}
}
public class BarCom : BaseCom {
	public int tick;
	public override void Apply() 
	{
		Debug.Log(
			"BarCom will print sum of tick and len of name:" 
			+ (stat.name.Length + tick) );
	}
}
  • 对于具体的 BarPrefab 身上会挂有 BarCom,并且会有对应的用 FooStat 创建出来 BarStat 作为其参数。
  • 除此之外还会有具体的脚本去执行 Apply,大概如下。
public void Deal()
{
	var gameobject = Instantiate(prefab);
	gameobject.getComponent(BaseCom).Apply();
}