我对游戏开发还比较陌生,但我花了十几个小时研究如何使用脚本对象(so)。
项目数据.cs
public class ItemData : ScriptableObject
{
public int itemID;
new public string name;
public Sprite sprite = null;
}
接下来,我有一个游戏对象,在唤醒时将所有itemData加载到字典中:
private Dictionary<int, ItemData> itemDB = new Dictionary<int, ItemData>();
void Awake()
{
LoadItems();
}
private void LoadItems()
{
//Load all itemData
ItemData[] itemData = Resources.LoadAll<ItemData>(itemDirectoryPath);
for(int i = 0; i < itemData.Length; i++)
{
//Set sprite of itemData, to avoid doing it manually
itemData[i] = SetSprite(itemData[i]);
//Add itemData to dataBase
itemDB[itemData[i].itemID] = itemData[i];
}
}
最后,我有一个函数,用于在运行时创建指定itemID的游戏对象:
//Create new gameobject at location
public void SpawnItem(int itemID, float x, float y)
{
//Get itemData
ItemData itemData = getItemData(itemID);
//Create new gameObject
GameObject gameObject = new GameObject();
//Set name of gameObject, add Item Script, and set position
gameObject.name = itemData.name;
gameObject.AddComponent<Item>().itemData = itemData;
gameObject.transform.position = new Vector3(x, y, 0);
}
问题:
-
-
如果使用“资源”被认为是不好的做法,除了手动拖动,还有更好的解决方案吗
每个
要将项添加到ItemDatabase脚本中吗?