08. FluentAPI 链式 API

FluentAPI 简介

FluentAPI 是 笔者积累的 Unity API 的一些链式封装。

基本使用非常简单,如下:

// traditional stylevar playerPrefab = Resources.Load<GameObject>("no prefab don't run");
var playerObj = Instantiate(playerPrefab);

playerObj.transform.SetParent(null);
playerObj.transform.localRotation = Quaternion.identity;
playerObj.transform.localPosition = Vector3.left;
playerObj.transform.localScale = Vector3.one;
playerObj.layer = 1;
playerObj.layer = LayerMask.GetMask("Default");

Debug.Log("playerPrefab instantiated");

// Extension's Style,same as above 
Resources.Load<GameObject>("playerPrefab")
    .Instantiate()
    .transform
    .Parent(null)
    .LocalRotationIdentity()
    .LocalPosition(Vector3.left)
    .LocalScaleIdentity()
    .Layer(1)
    .Layer("Default")
    .ApplySelfTo(_ => { Debug.Log("playerPrefab instantiated"); });

代码很简单。

FluentAPI 包含 100 多个常用 API 的链式封装,具体可以参考编辑器内文档。

另外 链式 API 可以与 QFramework 的其他模块配合使用事半功倍,比如 ResKit 与 FluentAPI 结合,参考代码如下:

mResLoader.LoadSync<GameObject>("mygameobj")
  .InstantiateWithParent(parent)
  .transform
  .LocalIdentity()
  .Name("MyGameObj")
  .Show();

链式 API 就介绍到这里。