动态加载Animator和AnimatorController

在unity5.0之前大家在打包人物模型和动作时都是用animation,但是在5.0之后animator变的越来越强大,比如在Unity 5中,可以在某些状态中添加StateMachineBehaviour脚本。某些状态出现时,将出现以下几种回调。
• OnStateEnter
• OnStateUpdate
• OnStateExit
• OnStateMove

• OnStateIK

其实不光是动作状态,其他的逻辑状态你都可以用以上方法来控制,非常的方便,所以我计划把人物的动作用animator来控制加载,你可以将animator直接关联到模型上一起打包是没有问题的,但是animatorController那只能是分开打包,并在运行时动态的赋值给animator,人物打包方法参考官方提供的换装Demo里人物的打包方法,这里我只给出AnimatorController的打包和加载方法。

打包方法,可以将其当成普通的prefab来打包

    [MenuItem("Character Generator/Build-NoteAssetBundle")]
    static void ExportResourceForAssetBundle() //用与单个资源的打包
    {
        // Bring up save panel
        string path = EditorUtility.SaveFilePanel("Save Resource", "", "NewResource", "assetbundle");
        if (path.Length != 0)
        {
            //Build the resource file from the active selection.
            Object[] selection = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
            BuildPipeline.BuildAssetBundle(Selection.activeObject, selection, path,
                BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets,
                BuildTarget.StandaloneWindows);
            Selection.objects = selection;
        }
        Debug.Log("Export asset bundles successfully!");
        
    }

加载方法:

    IEnumerator DownloadAnimarot()
    {
        WWW www = new WWW(animatorUrl);
        yield return www;
        runtimeAnimatorController = www.assetBundle.LoadAsset(www.assetBundle.mainAsset.name) as UnityEngine.Object;
        character.GetComponent().runtimeAnimatorController = (RuntimeAnimatorController)runtimeAnimatorController;

    }

这里有一点要特别提示, 生成出来的AnimatorController不能直接Instantiate,万恶的RuntimeAnimatorController.Instantiate()...只有在Resources.Load时有用。 RuntimeAnimatorController不支持Instantiate,那如果多个模型共用一个AnimatorController的时候,直接指向同一个即可。

千万不要写成 

character.GetComponent().runtimeAnimatorController = (RuntimeAnimatorController)RuntimeAnimatorController.Instantiate(obj);

你可能感兴趣的:(Unity3d)