C# Calling an object from a string

Asked

Viewed 438 times

1

I wonder if there’s 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 am working on Unityengine but should not differentiate much from c# "pure", because it is what I will actually use in this script, and not functions of Unity. What I would like to do is 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, ie,

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

and so on.

The problem is I have 60 different objects and it wouldn’t do to see one by one, then automate the process.

  • If id equals "Bar1". You cannot create a property Id and assign "Bar1" to her?

  • 1

    That’s what I ended up doing, joining the code with Thiago Lunardi’s

1 answer

4


You can use it Collections for that reason.

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

And then wear it like 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 that:

Butaos["Bar1"].Price = 10;
  • Where the variable Price is specified and Price?

  • Should I add my code to yours or just replace it?

  • Join, your Butao class remains the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.