U
U
Uncle Bogdan2021-07-11 19:52:05
Unity
Uncle Bogdan, 2021-07-11 19:52:05

How do you add an item without knowing exactly what class it is?

There are several classes denoting what kind of item it is, for example:

using UnityEngine;

[CreateAssetMenu(fileName = "Weapon name", menuName = "Items/Weapon")]
public class Weapon : ScriptableObject
{
    public ItemProp MainProp;

    public int Damage;
    public int Firerate;

    public int Strength;
}

ИЛИ

using UnityEngine;

[CreateAssetMenu(fileName = "Resource name", menuName = "Items/Resource")]
public class CraftResources : ScriptableObject
{
    public ItemProp MainProp;
}


There is an Items class:

public class Items 
{
    public static List<Weapon> Weapons = new List<Weapon>();
    public static List<CraftResources> Resources = new List<CraftResources>();
    public static List<Tool> Tools = new List<Tool>();
    public static List<Armor> Armors = new List<Armor>();

    public static int MaxItemsCount;

    public void AddItem()
    {
    }
}


I added the AddItem method and I have a problem, how to add an item to the right category? I generally thought at first instead of a bunch of classes to create one Item, but then how to configure it in a Scriptable object, and you can’t stuff it into a sheet like that. Can I change something smartly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
ReyGrau, 2021-07-12
@ReyGrau

Make the base class inherit from ScriptableObject, inherit items from it, then use switch in the Items class:

switch (Базов класс предмета)
{
   case Weapon weapon:
      Weapons.Add(weapon); 
      break;
   case CraftResources craftResources :
      Resources.Add(craftResources);
      break;
   ...
}

Maybe there is a better way, but I'm only a jun myself, so like this :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question