Unity Addressables study notes (1)---Create a remote server to load resources

Preface

Unity Addressables study notes—summary

Example 1: Load an image

1. First create a UI Image, a blank picture, and select the resource packaging method for deployment.

Insert image description here
Insert image description here

2. Modify remote publishing and loading configuration

Bulid PathSelect RemoteBuildPath

I chose custom for Load Path, and the address is http://localhost:8080/WebGL/

Insert image description here

Pitfall 1: The Build Path I chose at first was LocalBuildPath. When the Load Path was custom, the error was reported as follows:

BuildPath for group '***' is set to the dynamic-lookup version of StreamingAssets, but LoadPath is not. 

Solution: Change the Build Path to RemoteBuildPath. I don’t know why you can’t put local resources on remote resources. Maybe there is a difference. It is easy to understand that remote resources must be packaged on the remote server.

3. Package and put it on the server

Select RemoteBuildPath for Bulid Path. The packaged files will appear in the ServerData folder. This folder cannot be loaded in Unity. It corresponds to the type of program you want to package. Mine is a web page, so it is WebGL. The package file name is: remote_assets_all_9cd0b0249adf18fa843683539bbac8b9.bundle.
After that, I copied it to a local server. I used Spring Boot because I am working on Java. I only have
one pom.xml dependency.

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.12.RELEASE</version>
        </dependency>
    </dependencies>

Start function

@SpringBootApplication
public class CDNBackend {
    
    
    private static ApplicationContext context;

    public static void main(String[] args) {
    
    
        context = SpringApplication.run(CDNBackend.class, args);
    }

    public static ApplicationContext getApplicationContext() {
    
    
        return context;
   

Pitfall 1. The spring boot static resources placed on the server cannot be accessed.

Insert image description here

I created a WebGL directory under static. Of course, it doesn’t matter. This path should correspond to the Load Path above. The main reason is that the .bundle file cannot be downloaded, so I added a configuration class to solve the problem of inaccessibility.

@Configuration
public class ShowImage extends WebMvcConfigurerAdapter {
    
    

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
        //注:addResourceHandler("/WebGL/**")这个是配置你的URL
        //addResourceLocations("classpath:/static/WebGL/")这个是你的文件目录
        registry.addResourceHandler("/WebGL/**").addResourceLocations("classpath:/static/WebGL/");
        super.addResourceHandlers(registry);
    }
}

4. Unity C# loads remote images

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.UI;

public class GameController : MonoBehaviour
{
    
    
    private Sprite sprite;
    public Image img;
    void Start()
    {
    
    
        //Addressables.InstantiateAsync("Play Button");
        PlayerPrefs.DeleteKey(Addressables.kAddressablesRuntimeDataPath);
        Addressables.LoadAssetAsync<Sprite>("Play Button Img").Completed += SpriteLoaded;
    }

    private void SpriteLoaded(AsyncOperationHandle<Sprite> obj)
    {
    
    
        switch (obj.Status)
        {
    
    
            case AsyncOperationStatus.Succeeded:
                sprite = obj.Result;
                #加载完成的时候给img设置sprite
                img.sprite = sprite;
                break;
            case AsyncOperationStatus.Failed:
                Debug.LogError("Sprite load failed.");
                break;
            default:
                //case AsyncOperationStatus.None:
                break;
        }
    }
}

Pitfalls 1. Because it is a WebGL game, so the WEB accesses the WEB, and there is a cross-domain problem. WebGL game error:

from origin ‘http://localhost:57545’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

p://localhost:8080/WebGL/remote_assets_all_9cd0b0249adf18fa843683539bbac8b9.bundle' from origin 'http://localhost:57545' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Solution:

Add a cross-domain whitelist class on the server side of Spring Boot

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    
    

    public void addCorsMappings(CorsRegistry registry) {
    
    
        //CorsRegistration addMapping(String pathPattern): 添加路径映射,如 /admin/info,或者 /admin/**
        registry.addMapping("/**")
                //是否发送Cookie
                .allowCredentials(true)
                //放行哪些原始域, * 表示所有
                .allowedOrigins(new String[]{
    
    "http://127.0.0.1:57545", "http://localhost:57545"})
                //放行哪些请求方式
                .allowedMethods(new String[]{
    
    "GET", "POST", "PUT", "DELETE"})
                //放行哪些原始请求头部信息
                .allowedHeaders("*");
        //暴露哪些头部信息,不能设置为 * : .exposedHeaders();
    }
}

The final effect is that the picture is loaded successfully

Insert image description here

Guess you like

Origin blog.csdn.net/lwb314/article/details/130790176