- Home /
script with individual function for each gameObject or public script variable to solve inventory system problem
Hi. I am making inventory system where when you pick up item in inventory creates slot with sprite, name, etc. of item (GetComponent<>()). But i want slot to get script with OnUse function, that depends on item that you pick up. And i want all items to has individual OnUse function to be in one Item script, because if i will make scripts with unique function for each item i wouldn't be able to get script components of items that i pick up because it has different names. I could use a bunch of if statement, but it would be very laggy for a lot of items and i would need to write there each item i added.
So i want script with individual function for each item that has it, and that i can edit this function for each item (like public string, float, bool, ... variables).And i want to be able to translate this function to slot script.
Or i want public script variable where i can drop script like public gameObject variable, so this script contains OnUse function. And i want to be able to translate this script variable to slot script.
Or you can suggest your solution for this problem
(All scripts on c#) Maybe I spell something wrong, sorry for bad English.
Answer by xxmariofer · Oct 22, 2019 at 08:23 AM
First of all, using multiple foreach is not laggy, thats a really fast opperation but what you are asking for is basically how to implement child/parents
public abstract class Parent : MonoBehaviour
{
public abstract void OnUse();
}
public class ChildClassOne : Parent
{
public override void OnUse()
{
Debug.Log("I am onuse of first class");
}
}
public class ChildClassTwo : Parent
{
public override void OnUse()
{
Debug.Log("I am onuse of second class");
}
}
for using it now
GetComponent<Parent>().OnUse();
and will call the necesary method depending on the class
Your answer
Follow this Question
Related Questions
Variables from one script to another. 3 Answers
What is this C# code in javascript 0 Answers
Get variable from Script in list and , set direct link to other script 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers