Simply
Simply

Reputation: 25

How to select a class object by using one of its attributes

I am coding with C# in Unity using Visual studio. I am trying to select an object that is made from a class by using a "position" value. I'm struggling to explain it, but essentially I have a canvas called Counties and inside are a couple of UI objects, such as Leinster and Connacht:

Screenshot

I run through all the children of that canvas Counties to select them all one by one.

for (int i = 0; i < Counties.transform.childCount; i++)
{
    Transform t = Counties.transform.GetChild(i);
    Current = t.name;
}

However, I also need to change some values of each those children as they each have an object in my script which corresponds to each one. For example in the code below that is the object that corresponds to Leinster.

public County Leinster = new County(2630000, "NorthernIreland", "Connacht", "Munster", "Wales", 0);

The thing I don't know how to do is to actually connect those two. I have put in a "position" value in the object, which is the last number. For Leinster it is 0 because that is the first child in the canvas Counties and the next one (Connacht) would be 1 and so on. My question is basically how would I use that number to select the corresponding class object that has the same number as its "position"? Thank you for any suggestions.

Upvotes: 2

Views: 564

Answers (1)

Dave
Dave

Reputation: 2842

If I understand right you want to access your script component assigned to children of your parent. You can use the GetComponent method:

for (int i = 0; i < Counties.transform.childCount; i++)
{
    Transform t = Counties.transform.GetChild(i);
    Current = t.name;
    County county = t.GetComponent<County>();

    //do something with county object...
}

You can also add the component to your object first if there is none:

for (int i = 0; i < Counties.transform.childCount; i++)
{
    Transform t = Counties.transform.GetChild(i);
    Current = t.name;
    County county = t.GetComponent<County>();
    if (county == null)
       county = t.gameObject.AddComponent<County>();

    //do something with county object...
    county.name = t.name;
}

If you are looking for an easy way to access your Counties you can also use Dictionary:

using System.Collections.Generic;

Dictionary<string, County> Counties = new Dictionary<string, County>();

//add County to dictionary
Counties.Add("NorthernIreland", new County(2630000, "NorthernIreland", "Connacht", "Munster", "Wales", 0));

//get County from dictionary
Counties["NorthernIreland"] //and do something with it...

Upvotes: 2

Related Questions