I am trying to create an item system in Unity3d. The system relies on saving items as both Prefabs and Scriptable Objects.
Whenever I want to load data from a Item Scriptable Object, I have to create use Item C# script and attach it to a GameObject. Doing this forces me to copy and paste the same fields as the ones in the Item Scriptable Object.
This is a problem because whenever I update the Item Scriptable Object with a new field, I have to make sure I update the Item C# script with the same field.
I have tried looking into a design pattern that might solve the issue of having to copy and paste fields to be in two script files but have not found anything yet. I have looked into using JSON files to replace Scriptable Objects but since Scriptable Object is built into Unity, I would prefer to use it over JSON.
public class ItemBase : MonoBehaviour
{
[SerializeField] private string itemID;
[SerializeField] private string itemName;
[SerializeField] private string itemFlavorText;
[SerializeField] private float itemLevel;
[SerializeField] private Sprite itemSprite;
#region Getters and Setters
public string ItemID { get => itemID; set => itemID = value; }
public string ItemName { get => itemName; set => itemName = value; }
public string ItemFlavorText { get => itemFlavorText; set => itemFlavorText = value; }
public float ItemLevel { get => itemLevel; set => itemLevel = value; }
public Sprite ItemSprite { get => itemSprite; set => itemSprite = value; }
#endregion
/// <summary>
/// Obtains references from the ItemSO on the ItemPrefab class.
/// </summary>
[ContextMenu("Add References")]
public void AddReferences()
{
ItemSO item = gameObject.GetComponent<ItemPrefab>().Item;
ItemID = item.ItemBase.ItemID;
ItemName = item.ItemBase.ItemName;
ItemFlavorText = item.ItemBase.ItemFlavorText;
ItemLevel = item.ItemBase.ItemLevel;
ItemSprite = item.ItemBase.ItemSprite;
}
}
[System.Serializable]
public class ItemBaseSO
{
[SerializeField] private string itemID;
[SerializeField] private string itemName;
[SerializeField] private string itemFlavorText;
[SerializeField] private float itemLevel;
[SerializeField] private Sprite itemSprite;
#region Getters and Setters
public string ItemID { get => itemID; set => itemID = value; }
public string ItemName { get => itemName; set => itemName = value; }
public string ItemFlavorText { get => itemFlavorText; set => itemFlavorText = value; }
public float ItemLevel { get => itemLevel; set => itemLevel = value; }
public Sprite ItemSprite { get => itemSprite; set => itemSprite = value; }
#endregion
}
I place the ItemBase script on an Item Prefab and keep ItemBaseSO in a Resources folder for easier loading.
I would like to keep being able to use Scriptable Objects without having to copy and paste fields.
Aucun commentaire:
Enregistrer un commentaire