unity2020 webgl 加载配置文件 ScriptableObject 和StreamingAssets

一、使用ScriptableObject:(优点:unity自带无需配置,缺点:打包后无法在进行修改)
建议项目初期,配置项目数据相关的数值参数。便于新项目或策划修改。
1.创建配置文件相关的类型

using System;
using System.Collections.Generic;
using UnityEngine;

public class Student : ScriptableObject
{
    public List<StudentInfo> Clients=new List<StudentInfo>();
}


[Serializable]
public class StudentInfo
{
    public int age;
    public string tag;
}

2.通过Editor创建ScriptableObject文件

using UnityEditor;
using UnityEngine;

public class Tools 
{
    [MenuItem("Tools/CreateExcel")]
    public static void Create()
    {
        Student student = ScriptableObject.CreateInstance<Student>();
        student.Clients.Add(new StudentInfo{age = 10,tag = "李四"});
        string path= "Assets/Resources/cardMessage.asset";
        AssetDatabase.CreateAsset(student,path);
        AssetDatabase.Refresh();
    }
}

3.通过Resources读取ScriptableObject文件

var student = Resources.Load<Student>("cardMessage");
Debug.Log("年龄"+student.Clients[0].age);
FindObjectOfType<Text>().text = "年龄" + student.Clients[0].age;

二、通过StreamingAssets加载
使用场景:可以在StreamingAssets下创建所需要的Ip等以后需要修改的内容(json、xml;其他格式可以自行尝试),可以不用多次打包。

环境设置:
1.在iis下找见目录浏览
unity2020 webgl 加载配置文件 ScriptableObject 和StreamingAssets_第1张图片
2.进入“目录浏览”后,在操作点击启用unity2020 webgl 加载配置文件 ScriptableObject 和StreamingAssets_第2张图片
3.查看StreamingAssets路径下的web.config文件,是否有以下代码生成。没有则添加上
unity2020 webgl 加载配置文件 ScriptableObject 和StreamingAssets_第3张图片
unity2020 webgl 加载配置文件 ScriptableObject 和StreamingAssets_第4张图片

 	<system.webServer>
        <directoryBrowse enabled="true" />
    system.webServer>

4.代码中相关注意
通过Uri将Application.streamingAssetsPath转为不同平台的路径;
通过UnityWebRequest 进行加载。

void Start()
{
    #region ReadJson
    StartCoroutine(GetData());
    #endregion
}

IEnumerator GetData()
{
    //Uri将Application.streamingAssetsPath,转成http的相关路径
    var  uri = new  System.Uri(Path.Combine(Application.streamingAssetsPath,"json.json"));
    Debug.Log(uri);
    UnityWebRequest www = UnityWebRequest.Get(uri);
    yield return www.SendWebRequest();

    if(www.isNetworkError || www.isHttpError) {
        Debug.Log(www.error);
    }
    else
    {
        Debug.Log(www.downloadHandler.text);
        string jsonStr  = www.downloadHandler.text;

        var data = JsonUtility.FromJson<StudentInfo>(jsonStr);
        
        Debug.Log("姓名:" + data.tag + "\n年龄:" + data.age);
        FindObjectOfType<Text>().text = "姓名:" + data.tag + "\n年龄:" + data.age;
    }
}

你可能感兴趣的:(unity,2020,webgl,unity,webgl配置环境,unity,webgl,json)