- Home /
Defining an Item type in C#
I want to word this so it makes the most sense. I want to have a custom variable type that I can define a bunch of things for, like itemID and quantity and so on, but I also want to be able to define a ... void?
I want to make it so that if the player is holding an Item heldItem, the code can call heldItem.invicon to get the icon for the held item, call heldItem.quantity to find out how many are in the stack in the hand, call heldItem.rightclickAction to find what should happen for that Item when the right mouse button is pressed, AND all of those pieces of information are defined beforehand when the script for those items are being coded.
I code the main script then go through for each item I have in my game and define them such that they have all of the specifications for what an Item is
Also in the script I use to manage the inventory for the character I just have a list of items defined by something like
public static int capacity = 4; //how big is the inventory
public Item[] inv = new Item[capacity]; //define the inventory
I think I read about this in Java before and I think it might be something like implements or extends? Er, might be interface? I dont know what the equivalent would be in C#
I am sure this is a thing in C#, I just dont know the name of it or the exact syntax of it.
My gosh this is the worst brainfart I have had this entire year. I can SEE the kind of code I am talking about, I am sure minecraft even uses it in some of its code (forget that it is Java for a moment) Gah!
Answer by Kiwasi · Aug 15, 2014 at 04:50 AM
Two main ways to accomplish this
Inheritance. Each sword is a weapon.
public class Weapon{
public float damage;
}
public class Sword : Weapon {
// Sword automatically has a float called damage
}
The other option is interfaces
public interface ILife {
public float health;
}
public class Enemy : Monobehaviour, ILife {
// This script must declare a public float health
}
Its possible to do both of the following
List<Weapon> listOfAllWeapons;
List<ILife> listOfAllThingsWithHealth;
As always the official tutorial is excellent
Interfaces cannot contain variables though, only functions.
$$anonymous$$SDN has a different opinion. Interface properties.
$$anonymous$$y code may not function exactly as written, but the idea is sound. Will admit that I have never tried to implement properties in an interface in Unity. I tend to use components in place of interfaces.
Yes, properties can be included too as long as they do not have a definition. The idea is sound I agree, an interface would work in this situation.