Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

How to use structs in C#

Discussion in 'Scripting' started by Nick4711, Jun 15, 2015.

  1. Nick4711

    Nick4711

    Joined:
    Jun 5, 2015
    Posts:
    2
    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!
     
  2. Nick4711

    Nick4711

    Joined:
    Jun 5, 2015
    Posts:
    2
    Ok, I got the answear right a few moments later. I use a class now!
     
  3. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    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.
     
  4. Limeoats

    Limeoats

    Joined:
    Aug 6, 2014
    Posts:
    104
    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:

    Code (CSharp):
    1. struct InventorySlot {
    2.     //Variable declaration
    3.     //Note: I'm explicitly declaring them as public, but they are public by default. You can use private if you choose.
    4.     public bool IsFree;
    5.     public string Name;
    6.    
    7.     //Constructor (not necessary, but helpful)
    8.     public InventorySlot(bool isFree, string name) {
    9.         this.IsFree = isFree;
    10.         this.Name = name;
    11.     }
    12. }
    With this code, you can create a new inventory slot by simply calling the constructor:

    Code (CSharp):
    1. InventorySlot slot1 = new InventorySlot(false, "Slot 1");
     
  5. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008

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

    Limeoats

    Joined:
    Aug 6, 2014
    Posts:
    104
    Which is why I wrote in the comment above the constructor "Constructor (not necessary, but helpful)"

    :)