📅  最后修改于: 2023-12-03 15:20:51.561000             🧑  作者: Mango
Unity Addressables is a Unity plugin that allows developers to manage assets at runtime. It provides features to organize your game assets, such as scenes, prefabs, textures, and other resources, using the concept of addressables. Addressables are a way to refer to assets that are outside of the main Unity project, such as assets downloaded from a server or stored on a remote device.
This tutorial will cover how to add Addressables to a Unity project using C# scripts.
To follow this tutorial, you need the following:
In the Unity Editor, create a new folder under the Assets folder and name it "Addressables".
Drag an asset into the Addressables folder (such as a prefab or texture).
Right click on the asset and select "Addressables > Mark Asset > Asset Reference". This will mark the asset as an Addressable asset and give it an address in the "Addressables" window.
Example:
Addressables/MyPrefab
Open the "Window > Asset Management > Addressables" window.
In the "Asset Groups" section, click the "+" button to create a new asset group.
In the new asset group, set the "Schema Type" to "Local" and the "Bundle Mode" to "Pack Together".
Drag the Addressable asset from the Project window to the asset group.
Press the "Build" button to build the Addressables bundles.
In Visual Studio, create a new C# script named "AddressableLoader".
Add the following using statements to the top of the script:
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
Create a variable to store the Addressable asset reference:
public AssetReference myPrefabReference;
Use the "LoadAssetAsync" method to asynchronously load the Addressable asset into a GameObject:
private async void Start()
{
GameObject myPrefab = await myPrefabReference.LoadAssetAsync<GameObject>().Task;
Instantiate(myPrefab);
}
Save the script and attach it to a GameObject in the Unity Editor.
In the Inspector window, set the "myPrefabReference" variable to the Addressable asset reference.
Example:
Addressables/MyPrefab
Play the scene to see the Addressable asset loaded at runtime.
This tutorial covered the basics of using Unity Addressables in a C# script. You learned how to add an asset to Addressables, create an asset group, build the Addressables bundles, and use the LoadAssetAsync method to asynchronously load an Addressable asset at runtime.
For more information on Unity Addressables, see the official Unity Addressables documentation.