Home > Mobile >  Unity/C# one function to set any int?
Unity/C# one function to set any int?

Time:11-06

I've got a small project where I would like to avoid creating a setter for each integer. So I'm thinking if it's even possible.

So I would like to set an amount of
player.setResource(player.money, 100);,
player.setResource(player.coal, 20);,
etc.

I'm not sure first of all if it's possible, and second of all how to write a function itself.

public void setResource(int resource, int amount)
{
        ???
}

CodePudding user response:

Use an enum for this. Define an enum in your project like so

public enum ResourceType { Coal = 0, Money = 1, Health = 2 }

Now, you can add a switch case in your setResource function to check what enum you've passed, and set the corresponding value. This is however assuming all your values are integers. you can make a separate one for floats, or just use floats for everything, upto you.

This will be your new SetResource Function, assuming you have a reference to your player.

public void setResource(ResourceType resource, int amount)
{
    switch(resource)
    {
         case ResourceType.Money:
                 player.money = amount;
                 break;

        case ResourceType.Coal:
                player.coal = amount;
                break;


    }
}

CodePudding user response:

If you really want to avoid setter and getter why not use public properties? See here

CodePudding user response:

You can use an Enum to define the resources types and a Dictionary to store the values of each resource. Here's an example:

public enum ResourceType
{
    Coal,
    Money
}

private Dictionary<ResourceType, int> _resources = new Dictionary<ResourceType, int>();

public void SetResource(ResourceType resourceType, int value)
{
    _resources[resourceType] = value;
}

public int GetResource(ResourceType resourceType, int defaultValue = 0)
{
    if (_resources.TryGetValue(resourceType, out var value))
        return value;
    else
        return defaultValue;
}

CodePudding user response:

public class Player
{
    public int money { get; set; }
    public int coal { get; set; }

    public void setResource(string resource, int amount)
    {
        this.GetType().GetProperty(resource).SetValue(this, amount);
    }
}

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        Player player = new Player();
        player.setResource(nameof(player.coal), 4);
    }
}
  • Related