Skip to content

Instantly share code, notes, and snippets.

@charlieamat
Last active September 30, 2021 20:18
Show Gist options
  • Save charlieamat/cbd98c96602b0b805c9955cbea5ad9f1 to your computer and use it in GitHub Desktop.
Save charlieamat/cbd98c96602b0b805c9955cbea5ad9f1 to your computer and use it in GitHub Desktop.
[ta-edu-course-survival-game] Chapter 2 — ScriptableObjects
  • Create ItemType.cs
  • Make ItemType derive from ScriptableObject
  • Add a string field called "DisplayName"
    • We could add more meta information (e.g., stats, description, icon, etc.), but we don’t need to at the moment
    • Each instance of ItemType will represent a type of item and will be referenced in our code instead of strings
    • But how do we create item types?
  • Add the CreateAssetMenu attribute
    • Like components that derive from MonoBehaviour, scriptable objects don't support constructors and can't be instantiated with new
    • You can use ScriptableObject.CreateInstance
    • But the CreateAssetMenu allows you to create your scriptable object assets right from the Unity editor, which is what we want
  • Change the string array in Inventory to an ItemType array
  • Change the string field in InteractionHandler to ItemType
  • Switch to Unity
  • Create a folder called “Content”
  • Create a new instance of ItemType for each item (Sword, Potion, Scroll)
  • Update the scene and verify the behavior
public class Inventory : MonoBehaviour
{
[SerializeField] private ItemType[] items;
}
[CreateAssetMenu(menuName = "Game/Item Type")]
public class ItemType : ScriptableObject
{
public string DisplayName;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment