【Unity3D】Resource Management

1 Introduction

        The main resource management solutions in Unity include Resources, TextAsset, ScriptableObject, AssetDatabase, PlayerPrefs, Addressables, AssetBundle , and SQLite. This article will introduce most of them.

2 Resources

        Resources are mainly used to load resources. The loaded resources need to be placed in the Resources directory. You can create a Resources directory in any subdirectory of Assets, and Unity will automatically retrieve these Resources directories.

        Test_Resources.cs

using UnityEngine;

public class Test_Resources : MonoBehaviour {
    private void Awake() {
        GameObject cube = Resources.Load<GameObject>("CubePrefab");
        Material cubeMat = Resources.Load<Material>("CubeMat");
        cube.GetComponent<Renderer>().material = cubeMat;
        Instantiate(cube);
    }
}

3 TextAsset

        TextAsset is mainly used to load text and table files. For the official introduction, see → TextAsset .

        Test_TextAsset.cs

using UnityEngine;

public class Test_TextAsset : MonoBehaviour {
    [SerializeField]
    private TextAsset heightDatas;

    private void Awake() {
        string[] textInLines = heightDatas.text.Split('\n');
        for (int i = 1; i < textInLines.Length; i++) {
            string[] values = textInLines[i].Split(",");
            string name = values[0];
            int age = int.Parse(values[1]);
            float height = float.Parse(values[2]);
            Debug.Log("name=" + name + ", age=" + age + ", height=" + height);
        }
    }
}

        Print below.

4 ScriptableObject

        ScriptableObject is mainly used for persistent data, project parameter configuration, role parameter configuration, etc. For the official introduction, see → ScriptableObject . The main callback functions are as follows. After inheriting ScriptableObject, override the following method to automatically call back in the corresponding state.

        SOData .cs

using UnityEngine;

public class SOData : ScriptableObject {
    [SerializeField]
    private string _name; // 姓名
    [SerializeField]
    private int _age; // 年龄
    [SerializeField, Range(1f, 2.3f)]
    private float _height; // 身高

    public string Name => _name;
    public int Age => _age;
    public float Height => _height;
}

        After compilation, right-click in the Assets window, select [Create→SOData], create the object, and rename it to SOData_1. After selecting the SOData_1 object, you can adjust the properties in the Inspector window, as follows.

5 AssetDatabase

        AssetDatabase is used to load resources and is only used in Unity editor mode. For official introduction, see → AssetDatabase , Batching with the AssetDatabase .

AssetDatabase.CopyAsset("Assets/Asset1.txt", "Assets/Text/Asset1.txt"); // 复制资源
AssetDatabase.MoveAsset("Assets/Asset2.txt", "Assets/Text/Asset2.txt"); // 移动资源
AssetDatabase.DeleteAsset("Assets/Asset3.txt"); // 删除资源
AssetDatabase.ImportAsset(path1, ImportAssetOptions.Default); // 导入资源
GameObject cube = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Loader/CubePrefab.prefab"); // 加载资源

        Test_AssetDatabase.cs

using UnityEditor;
using UnityEngine;

public class Test_AssetDatabase {

    [MenuItem("Custom/Import Cube")]
    public static void ImportImage() {
        // 导入Cube预设体
        string path1 = "Assets/Loader/CubePrefab.prefab";
        AssetDatabase.ImportAsset(path1, ImportAssetOptions.Default);
        GameObject cube = AssetDatabase.LoadAssetAtPath<GameObject>(path1);
        // 导入Cube材质
        string path2 = "Assets/Loader/CubeMat.mat";
        AssetDatabase.ImportAsset(path2, ImportAssetOptions.Default);
        Material mat = AssetDatabase.LoadAssetAtPath<Material>(path2);
        // 实例化Cube
        cube.GetComponent<Renderer>().material = mat;
        GameObject.Instantiate(cube);
    }
}

        Note: The Test_AssetDatabase script file needs to be placed under the Editor directory. After compilation, click [Custom→Import Cube] in the menu bar to create a Cube object.

6 PlayerPrefs

        PlayerPrefs is a class that stores player preferences between game sessions. It can store string, float, and integer values ​​into the user's platform registry. Unity stores PlayerPrefs in the local registry without encryption, do not use PlayerPrefs data to store sensitive data. For the official introduction of PlayerPrefs, see → PlayerPrefs .

        The static methods of PlayerPrefs are as follows.

        Test_PlayerPrefs.cs

using UnityEngine;

public class Test_PlayerPrefs : MonoBehaviour {

    private void Awake() {
        PlayerPrefs.SetString("name", "Zhang san");
        PlayerPrefs.SetInt("age", 25);
        PlayerPrefs.SetFloat("height", 1.75f);
        Debug.Log("name=" + PlayerPrefs.GetString("name")
            + ", age=" + PlayerPrefs.GetInt("age")
            + ", height=" + PlayerPrefs.GetFloat("height"));
    }
}

        The print log is as follows.

7 Addressables

        The Addressables package provides tools and scripts for organizing and packaging application content, and can load and release resources at runtime. For the official introduction, see → Addressables .

        1) Install Addressables

        Select [Window→Package Manager] in the menu bar, open the package manager, and follow the steps below to install Addressables.

        2) Set the resource to Addressable

        Select the resource in the Assets window, check Addressable in the Inspector window, and modify the resource Key as follows.

        3) Group management Addressables

        Select [Window→Asset Management→Addressables→Groups] in the menu bar to open the Addressables Groups window, as shown below.

        You can drag the Addressables Groups window to dock it next to the Game window, as shown below. You can see that the resources in the Resources directory are automatically added to Addressables.

        Click [New→Packed Assets] in order to create a new package and rename it to facilitate group management of resources, as follows.

        4) Load resources

        Test_Addressables.cs

using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

public class Test_Addressables : MonoBehaviour {
    private GameObject cube;

    private void Awake() {
        Addressables.InstantiateAsync("CubePrefab2").Completed += OnInstantiate;
    }

    private void OnInstantiate(AsyncOperationHandle<GameObject> operationHandle) { // 游戏对象加载成功回调函数
        cube = operationHandle.Result;
        Addressables.LoadAssetAsync<Material>("CubeMat2").Completed += OnLoadAsset;
    }

    private void OnLoadAsset(AsyncOperationHandle<Material> operationHandle) { // 材质加载成功回调函数
        cube.GetComponent<Renderer>().material = operationHandle.Result;
    }
}

        Note: When introducing the two namespaces UnityEngine.AddressableAssets and UnityEngine.ResourceManagement.AsyncOperations, an error may be reported in VSCode, but no error will be reported in Unity and the program will not be affected. If you want to eliminate this error in VSCode, you can restart Unity and VSCode, and the error will not be reported.

Guess you like

Origin blog.csdn.net/m0_37602827/article/details/132863051