C # Calling an object from a string

1

I would like to know if there is a way to call an object from a string.

Here is an example:

public class Butao
{
    public string _Name_;
    public float _Price_;

    public Butao(string name, float price)
    {
        _Name_ = name;
        _Price_ = price;
    }
}

public class DataBase : MonoBehaviour
{    
    string id;

    private void Start()
    {
        var bar1 = new Butao("", 0);
        var bar2 = new Butao("", 0);
        var bar3 = new Butao("", 0);
    }
}

I'm working on UnityEngine but it should not differentiate much from "pure" C #, because that's what I'll actually use in this script, not Unity functions. What I would like to do was through a string, the string id, and pass it directly and call the object with that name. For example:

If id equals "Bar1", I wanted to edit the properties of Bar1, that is,

Bar1.Name = "Alterado";
Bar1.Price = 2

and so on.

The problem is that I have 60 different objects and could not see one by one, hence automating the process.

    
asked by anonymous 06.07.2017 / 11:43

1 answer

4

You can use Collections for this .

public class ButaoCollection : List<Butao>
{
    public Butao this[string name]
    {
        get
        {
            return this.SingleOrDefault(butao => butao.Name == name);
        }
    }
}

And then use this:

public class DataBase : MonoBehaviour
{    
    string id;
    public ButaoCollection Butaos { get; set; }

    private void Start()
    {
        Butaos = new ButaoCollection();

        Butaos.Add(new Butao("Bar1", 0));
        Butaos.Add(new Butao("Bar2", 0));
        Butaos.Add(new Butao("Bar3", 0));
    }
}

And call it like this:

Butaos["Bar1"].Price = 10;
    
06.07.2017 / 11:53