1

I have a public Image[] to get many Image UI that exist on scene from Unity Editor .

Now i wanna deactivate one or more of them from scene by it's name.

But i can't access this array items by string name of Images .only i can access by int number for index like Images[0]

I tried before Dictionary Class and other solutions on forums but i can't find a way .

How can i do this ?

1
  • 1
    Well, using Dictionary<string, Image> does sound like the way forward. Where did you get stuck with that? Creating the dictionary, or using it? Are you able to use LINQ? If so, just var dictionary = Images.ToDictionary(image => image.Name); or similar should work... Commented Sep 21, 2016 at 10:26

1 Answer 1

3

For Array:

Use a for loop to loop over the image array then compare the name. If they match, deactivate them.

public Image[] image;

void activateImage(string imageName, bool enable)
{
    for (int i = 0; i < image.Length; i++)
    {
        if (image[i].name == imageName)
        {
            image[i].enabled = enable;//Good for performace
            // OR
            //image[i].gameObject.SetActive(enable);
        }
    }
}

Usage:

Activate

activateImage("nextImage", true);

Deactivate

activateImage("nextImage", false);

For Dictionary:

Dictionary<string, Image> image = new Dictionary<string, Image>();

void activateImage(string imageName, bool enable)
{
    if (image.ContainsKey(imageName))
    {
        image[imageName].enabled = enable;//Good for performace
        // OR
        //image[imageName].gameObject.SetActive(enable);
    }
}

To add Image to Dictionary:

public Image myImage;
image.Add(myImage.name, myImage);

or

image.Add("myImageName", myImage);
Sign up to request clarification or add additional context in comments.

1 Comment

@LumbusterTick Thanks and you are right. It is just that I avoid using linq when it is not the only solution in Unity. I use linq a-lot in a normal Windows form App but not in Unity unless if really really required. The reason is performance and memory allocation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.