什么是ScriptableObject?
ScriptableObject是一个数据容器,可用于保存大量数据,与类实例无关。ScriptableObjects的一个主要用例是避免使用值副本来减少Project的内存使用量。如果您的项目具有预制(Prefab),在附加的MonoBehaviour 脚本(Scripts)中存储不变数据。每次实例化Prefab时,它都会获得自己的数据副本。您可以使用ScriptableObject存储数据,然后通过所有预制件的引用访问它,而不是使用该方法并存储重复数据。这意味着内存中有一个数据副本。
就像MonoBehaviours一样,ScriptableObjects派生自基础Unity对象,但与MonoBehaviours不同,您无法将ScriptableObject附加到GameObject。而是将它们保存为项目中的资产。
使用编辑器时,您可以在编辑时和运行时将数据保存到ScriptableObjects,因为ScriptableObjects使用Editor命名空间和Editor脚本。但是,在部署的构建中,您不能使用ScriptableObjects来保存数据,但可以使用在开发期间设置的ScriptableObject Assets中保存的数据。从编辑器工具保存为ScriptableObjects作为资产的数据将写入磁盘,因此在会话之间保持不变。
使用ScriptableObject
ScriptableObjects的主要用例是:
- 在编辑器会话期间保存和存储数据
- 将数据保存为项目中的资产,以便在运行时使用
要使用ScriptableObject,您需要在Assets中创建一个脚本文件夹并使其继承自ScriptableObject
该类。您可以使用CreateAssetMenu属性轻松地使用您的类创建自定义资产。例如:
using UnityEngine;
[CreateAssetMenu(fileName = "Data", menuName = "ScriptableObjects/SpawnManagerScriptableObject", order = 1)]
public class SpawnManagerScriptableObject : ScriptableObject
{
public string prefabName;
public int numberOfPrefabsToCreate;
public Vector3[] spawnPoints;
}
使用Assets文件夹中的上述脚本,您可以通过导航到Assets> Create> ScriptableObjects> SpawnManagerScriptableObject来创建ScriptableObject的实例。为新的ScriptableObject实例提供有意义的名称并更改值。要使用这些值,您需要创建一个引用ScriptableObject的新脚本,在本例中为a SpawnManagerScriptableObject
。例如:
using UnityEngine;
public class Spawner : MonoBehaviour
{
// The GameObject to instantiate.
public GameObject entityToSpawn;
// An instance of the ScriptableObject defined above.上面定义的ScriptableObject的实例。
public SpawnManagerScriptableObject spawnManagerValues;
// This will be appended to the name of the created entities and increment when each is created.
//这将附加到创建的实体的名称中,并在创建每个实体时递增。
int instanceNumber = 1;
void Start()
{
SpawnEntities();
}
void SpawnEntities()
{
int currentSpawnPointIndex = 0;
for (int i = 0; i < spawnManagerValues.numberOfPrefabsToCreate; i++)
{
// Creates an instance of the prefab at the current spawn point.
GameObject currentEntity = Instantiate(entityToSpawn, spawnManagerValues.spawnPoints[currentSpawnPointIndex], Quaternion.identity);
// Sets the name of the instantiated entity to be the string defined in the ScriptableObject and then appends it with a unique number.
currentEntity.name = spawnManagerValues.prefabName + instanceNumber;
// Moves to the next spawn point index. If it goes out of range, it wraps back to the start.
currentSpawnPointIndex = (currentSpawnPointIndex + 1) % spawnManagerValues.spawnPoints.Length;
instanceNumber++;
}
}
}
将上述脚本附加到场景中的GameObject 。然后,在Inspector,将“ Spawn Manager Values”字段设置为SpawnManagerScriptableObject
您设置的新字段。将Entity设置为Spawn字段是Assets文件夹中的任何预制件,然后单击编辑器中的“ Play ”。您将在Spawner
使用您在中设置的设置实例化中看到您引用的预制件SpawnManagerScriptableObject
。ableObject派生类,您可以使用CreateAssetMenu属性,以便使用您的类轻松创建自定义资产。
提示:在检查器中使用ScriptableObject引用时,可以双击引用字段以打开ScriptableObject的检查器。您还可以创建自定义编辑器,以定义类型的检查器外观,以帮助管理它所代表的数据。