How to use structs in C#

Hey Guys,
I have a little problem. Recentlx I’m trying to create an inventory system for my Unity Game. Therefore I need something like an Array, that can store multiple variables of different types. For example for slot1 I want to save:
bool isFree;
string name;
I searched around in the internet and I fount the structs for C#. But as I am trying it, it doesnt work.
Can anyone tell me, how structs work and how I can declare a variable in a struct?

Thx for your help!

Ok, I got the answear right a few moments later. I use a class now!

1 Like

you can use a struct, and if you need help, check out my intermediate/advanced c# unity videos. I cover structs and classes.

Typically for an Item, you’ll probably want to use a class due to the load weight of the item attributes. Typically, if you have more than 5 fields, switch to a class.

2 Likes

I see you solved the problem by using classes instead of structs, which is perfectly fine, but I thought I’d try to help you out on getting structs to work since they may sometimes be a better option for smaller data structures. Structs are generally a good idea for small data structures that are meant to just hold groups of data. You don’t need to deal with the overhead of “objects” since the struct stores the actual values, not references to the data.

You should be able to accomplish the structure you mentioned with something like this:

struct InventorySlot {
    //Variable declaration
    //Note: I'm explicitly declaring them as public, but they are public by default. You can use private if you choose.
    public bool IsFree;
    public string Name;
   
    //Constructor (not necessary, but helpful)
    public InventorySlot(bool isFree, string name) {
        this.IsFree = isFree;
        this.Name = name;
    }
}

With this code, you can create a new inventory slot by simply calling the constructor:

InventorySlot slot1 = new InventorySlot(false, "Slot 1");
20 Likes

With structs, you don’t have to use the constructor. You can, but it’s not required.

1 Like

Which is why I wrote in the comment above the constructor “Constructor (not necessary, but helpful)”

:slight_smile:

8 Likes