An article to learn the initialization of YooAsset resource hot update

Zero, import YooAsset

0. Pay attention to read it together with the official documents, he wrote very clearly

official document

1. UPM import

Find this in ProjectSetting, fill in like this
insert image description here

package.openupm.cn
https://package.openupm.cn
com.tuyoogame.yooasset

Then in PackageManager, select MyRegistry and import YooAsset

1. Editor

0. Create YooAsset settings file

insert image description here
Before using these things, we need to right click on the Project panel, select YooAsset/Create Setting to create this file
and then MainfestFileName is the name of our resource list file, (it’s okay if you don’t change it, it doesn’t affect the use, it’s just the name)insert image description hereinsert image description here

1.AssetBundle Collector

insert image description here
The first is whether to display the package, the second is whether to use Chinese, the third is whether to enable addressing, and the fourth is to add something in front of the package name to ensure that the package name is unique.
Next we tick the first three and press the plus sign below to create something.
insert image description here
Among them, Package is the package, Group is the grouping, and Collector is the collector.
We can write custom collection rules. When the Collector selects a directory, we can use our own scripts to control what resources are selected.

We simply select a few resources
insert image description here

2. Builder

insert image description here
The second is to build the pipeline, the default is the default, otherwise it can be changed to programmable (not introduced).
The third is the build mode, ForceRebuild will delete the original AB and create a new one .
Incremental is an incremental build, that is, the typed package is an extra resource, which will not be removed or generated before, so when updating to the CDN, it can be directly overwritten on the original package , or the difference analysis can be uploaded
Then there is DryRun, which will only generate some Mainfest files, not packaged, for drills, .
Next is Simulate, which requires a special initialization method to simulate the build. It is only valid in the editorinsert image description here
and then the version number, which is automatically generated over time and does not need to be processed.
, LZMA guarantees the maximum compression rate. In fact, the gap is not big. If it is too big, it will not be placed here, and the instructions are available.
Encryption is an encryption method. You need to write one yourself. It seems to implement an interface. The last thing in the YooAsset official document
is whether to copy to StreamingAsset.
insert image description here
We can distinguish it according to the Group label.

3.Reporter

insert image description here
In the directory, Bundles is the packaging output path, and SandBox is the path for AB to download the cache from the server. We enter Reporter, select Import, and select a file
under the package named after the time that is typed.
insert image description here
insert image description here
insert image description here
The compiler, this is to detect whether there is a circular reference problem directly in the resource at runtime, and the scheme based on reference counting is most afraid of this.

Two, the code

0. Initialization for each mode

// 初始化资源系统
YooAssets.Initialize();
// 创建默认的资源包,这里是需要先在Collector里创建同名Package的
var package = YooAssets.CreatePackage("DefaultPackage");
// 设置该资源包为默认的资源包,可以使用YooAssets相关加载接口加载该资源包内容。
YooAssets.SetDefaultPackage(package);

0.1 Select an operating mode

 public EPlayMode PlayMode = EPlayMode.EditorSimulateMode;
switch (PlayMode)
        {
    
    
            case EPlayMode.EditorSimulateMode:
                {
    
    
                   //开启协程
                    break;
                }
            case EPlayMode.OfflinePlayMode:
                {
    
    
                //开启协程
                    break;
                }
            case EPlayMode.HostPlayMode:
                {
    
    
                           //开启协程
                    break;
                }
        }

1. Editor simulation run

After executing this coroutine, you can load it arbitrarily, but note that it can only be used in the editor , and the incoming package is the DefaultPackage created above

  private IEnumerator EditorInitializeYooAsset(ResourcePackage package)
    {
    
    
        var initParameters = new EditorSimulateModeParameters();
        initParameters.SimulateManifestFilePath = EditorSimulateModeHelper.SimulateBuild("DefaultPackage");
        yield return package.InitializeAsync(initParameters);
    }

2. Run in stand-alone mode

This operation mode requires that when building the AB package, adjust the last setting option and copy the AB package to streamingAsset/buildIn , otherwise loading resources will fail! ! Be careful not to copy manually

 private IEnumerator SingleInitializeYooAsset(ResourcePackage package)
    {
    
    
        var initParameters = new OfflinePlayModeParameters();
        yield return package.InitializeAsync(initParameters);
    }

3. Network mode operation

(0) Local test environment

First of all, we find a software called HFS, Http File Server from the Internet, just search for it.
insert image description here
Drag the FTP folder on the right into it. We can access this address
insert image description here
and throw our AB package in

(1) Initialize the resource package

public string netPath = "http://127.0.0.1:9999/FTP/2023-04-20-1108";


 private IEnumerator NetInitializeYooAsset(ResourcePackage package)
    {
    
    
        var initParameters = new HostPlayModeParameters();
        
        initParameters.QueryServices = new QueryStreamingAssetsFileServices();
        
        //主资源服务器地址
        initParameters.DefaultHostServer = netPath;
        //备用资源服务器地址
        initParameters.FallbackHostServer = netPath;
        
        yield return package.InitializeAsync(initParameters);
    }
    
 // 内置文件查询服务类,这个类只需要返回ApplicationstreamingAsset下面的文件存在性就好
    private class QueryStreamingAssetsFileServices : IQueryServices
    {
    
    
        public bool QueryStreamingAssets(string fileName)
        {
    
    
            // StreamingAssetsHelper.cs是太空战机里提供的一个查询脚本。
            string buildinFolderName = YooAssets.GetStreamingAssetBuildinFolderName();
            return File.Exists($"{
      
      Application.streamingAssetsPath}/{
      
      buildinFolderName}/{
      
      fileName}");
        }
    }

(2) Update resource version


string packageVersion = "2023-4-20-1108";
 IEnumerator UpdatePack(ResourcePackage package)
 {
    
    
        //2.获取资源版本
        var operation = package.UpdatePackageVersionAsync();
        yield return operation;
        if(operation.Status!=EOperationStatus.Succeed)
        {
    
    
            Debug.LogError("版本号更新失败,可能是找不到服务器");
            yield break;
        }
        //这是获取到的版本号,在下一个步骤要用
        packageVersion = operation.PackageVersion;
}

(3) Update patch list

 IEnumerator UpdatePack(ResourcePackage package)
    {
    
    
        //3.获取补丁清单
        var op=  package.UpdatePackageManifestAsync(packageVersion);
        yield return op;
        if(op.Status!=EOperationStatus.Succeed)
        {
    
    
            Debug.LogError("Mainfest更新失败!");
        }
    }

(4) Download the patch package


int downloadingMaxNum = 10;
int failedTryAgain = 3;
int timeout = 60;
        
 IEnumerator Download()
    {
    
    
        var package = YooAssets.GetPackage("DefaultPackage");
        var downloader = package.CreateResourceDownloader(downloadingMaxNum, failedTryAgain, timeout);
        //下载数量是0,直接就完成了
        if(downloader.TotalDownloadCount==0)
        {
    
    
            yield break;
        }

		//注册一些回调
        downloader.OnDownloadErrorCallback += OnError;
        downloader.OnDownloadProgressCallback += OnProcess;
        downloader.OnDownloadOverCallback += OnOver;
        downloader.OnStartDownloadFileCallback += OnStartDownOne;

		//开始下载
        downloader.BeginDownload();
        //等待下载完成
        yield return downloader;
		//检查状态
        if(downloader.Status==EOperationStatus.Succeed)
        {
    
    
            Debug.Log("下载完成");
        }
        else
        {
    
    
            Debug.Log("下载失败");
        }
    }

When these steps are executed, the initialization is complete. Use yooasset as you like.

3. Solutions for each platform

1. Editor simulation

In order to load faster, we can specifically run according to the above editor simulation initialization method to save development time.

2. Pure stand-alone without networking

You only need to adjust the last option when playing AB, copy it to streamingAsset/BuiltIn
and follow the stand-alone initialization method given above.

3. Stand-alone weak connection

First follow the initialization steps of the networking mode, and then at the step of obtaining the version number, if successful, continue to follow the networking steps, otherwise directly press

private IEnumerator Start()
{
    
    
//先获取包
    var package = YooAssets.GetPackage("DefaultPackage");
    //更新版本号
    var operation = package.UpdatePackageVersionAsync(60);
    yield return operation;

    if (operation.Status == EOperationStatus.Succeed)
    {
    
    
        // 如果获取远端资源版本成功,说明当前网络连接通畅,可以走正常更新流程。继续从服务器按照联网模式更新
    }
    else
    {
    
    
        // 如果获取远端资源版本失败,说明当前网络无连接。
        // 在正常开始游戏之前,需要验证本地清单内容的完整性。
        //如果清单都没了,那就不用继续了,请联网进行清单的补全
        string packageVersion = package.GetPackageVersion();
        var operation = package.PreDownloadContentAsync(packageVersion);
        yield return operation;
        if (operation.Status != EOperationStatus.Succeed)
        {
    
    
             ShowMessageBox("请检查本地网络,有新的游戏内容需要更新!");
            yield break;
        }

		//注意这里没真的开始下载,只是用本地清单看看需要下载数量有几个
        int downloadingMaxNum = 10;
        int failedTryAgain = 3;
        int timeout = 60;
        var downloader = operation.CreateResourceDownloader(downloadingMaxNum, failedTryAgain, timeout);
        if (downloader.TotalDownloadCount > 0)   
        {
    
    
            // 资源内容本地并不完整,需要提示玩家联网更新。
            ShowMessageBox("请检查本地网络,有新的游戏内容需要更新!");
            yield break;
        }
       
        // 开始游戏
        StartGame();
    }
}

4. Networking

Just follow the network mode, and if one step fails, the player will not be allowed to enter

Guess you like

Origin blog.csdn.net/qq_46273241/article/details/130276442