- Home /
adding an inherited class to a list of the derived class, while accessing the inherited classes changed functions
I am trying to make an item system, in which I have a base item class, and I am planning to make items which inherits from that. Then I will add that item to a list of items, so that I can call the functions within it. It might be more useful with the code, so here is is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class items : MonoBehaviour
{
public interface iitem // item interface
{
string qname(string name); //name
void OnEquip(); //what happens when you equip it (eg stat boosts that you want one time only)
void OnUse(); //every frame use
}
public class item : iitem // class for organizing and for ease of use - aka not neccesary
{
public string iname;
public string qname(string name)
{
return name;
}
public void OnEquip()
{
}
public void OnUse()
{
}
public void set()
{
qname(iname);
}
}
public List<item> curitems = new List<item>();
class speedpotion : item
{
new string iname = "";
public new void OnEquip()
{
print("speed has been increased by 10"); // specific item use
}
public speedpotion() // allowing for it to be created
{
set();
}
}
public List<iitem> itemlist = new List<iitem>()
{
new speedpotion() // adding it to the list of iitem (the interface)
};
// Start is called before the first frame update
void Start()
{
itemlist[0].OnEquip(); // calls the first frame function
itemlist[0].OnUse(); // calls the every frame function
}
// Update is called once per frame
void Update()
{
}
}
However when I do that, it just runs the OnEquip for the interface iitem, (or the class item when I try to make the list of that type). I tested it by giving the class a print statement. Is there any way of putting all the inherited items into the list of common derived type while being able to use the OnUse, OnEquip and qname of the item class inheriting from iitem and item interface and class?
I can do a standard instantating item system, where I instantate an item with it's own monobehaviour item script, but I want to try not doing that for now
Your answer
Follow this Question
Related Questions
Making sound names error resistant in an AudioManager 0 Answers
Does increasing framerate to 5 has a negative impact on simulation? 0 Answers
Warning with Unity 2018.1.3 and Visual Studio 2017 1 Answer
Unity 2017 not giving option for latest target API level 26 or higher. 3 Answers
Networking - Unity stuck by pressing play button in editor 2018 2 1 Answer