How do i change any variables inside of a enum element?

Viewed 82

This is my code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
     
public class Item
{
    public Inventory inventory;
    public enum ItemType
    {
        Blocks,
        Potions,
        Weapons,
    }

    public ItemType itemType
    public bool stackable;
     
}

and what I am trying to do is to change only the enum ItemType Blocks to stackable so that I can just use the add the item to the list, and if the item is blocked, it will be set to stackable by default.

how can I achieve this?

I tried ItemTypes.Blocks.stackable = true; But it won't work.

2 Answers

Your question is quite poorly-worded so it is rather confusing. I'm going to make my best guess as to what you mean and recommend based on that. Firstly, get the enum out of the class. Nesting types is generally not a good idea.

 public enum ItemType
 {
     Blocks,
     Potions,
     Weapons
 }

Next, use properties to expose public data rather than fields. You can then provide additional implementation details:

 public class Item
 {
     public Inventory Inventory { get; set; }
     public ItemType ItemType { get; set; }
     public bool IsStackable => ItemType == ItemType.Blocks;
 }

The IsStackable property is read-only and its value is generated on the fly based on the value of the ItemType property.

Option 1:

Use an extension method to determine what is stackable.

public class Item
{
    public Inventory inventory;
    public enum ItemType
    {
        Blocks,
        Potions,
        Weapons,
    }

    public ItemType itemType; // Defaults to Blocks
}

public static class ItemTypeExtensions
{
    public static bool IsStackable(this Item.ItemType type)
    {
        return type == Item.ItemType.Blocks;
    }
}

Usage

var item = new Item();
bool isStackable = item.itemType.IsStackable(); // true

item.itemType = Item.ItemType.Potions;
bool isStackable = item.itemType.IsStackable(); // false

Option 2:

When you declare an enum value, it automatically uses the default element as the value. For any enum, that is the one that has the value 0. If you don't give them values (as in this case), the compiler will assign the first element with value 0. Therefore, the way you have constructed the enum ItemTypes.Blocks is the default value. You can rely on this default when your Item object is constructed.

public class Item
{
    public Inventory inventory;
    public enum ItemType
    {
        Blocks,
        Potions,
        Weapons,
    }

    public ItemType itemType; // Defaults to Blocks
    public bool stackable = true; // Set default explicitly (which matches up with blocks)
}

However, if you want the boolean value to stay in sync with your enum value, you either need to set them at the same time or create a method on the Item class to set them both together.

Related