Have different Source Image in Unity 4.6 UI Image prefab depending on script bool property state

3.4k views Asked by At

I'd like to have one prefab of an image. The image and its features would be exactly the same, but come in two colors - specifically I'll need to set the Source Image to one of two images depending on the actual value of the bool in the script attached to the prefab. Of course, instead of using two images, I could probably change the color of the original Image, or draw it some other way but I guess the method would be largely the same - all done inside Unity and not in code.

Using Unity 4.6 final release.

Btw inheritance is not possible with prefabs right?

1

There are 1 answers

0
Richard Knol On

I am assuming you refer to the Image component in the new UI and you want to change the sprite.

Either assign 2 sprites in the prefab:

public Sprite spriteOn;
public Sprite spriteOff;
public bool onOff;

void Start() {
    Image imageComponent gameObject.GetComponent<Image>();
    if(imageComponent != null) onOff ? imageComponent.sprite = spriteOn : imageComponent.spriteOff;
}

Or change the original sprite:

public bool onOff;

void Start() {
    Image imageComponent gameObject.GetComponent<Image>();
    if(imageComponent != null) {
        if(onOff) {
            Sprite baseSprite;
            Texture2D tex = baseSprite.texture;
            Texture2D newTex = (Texture2D)Texture2D.Instantiate(tex);

            Color[] originalPixels = tex.GetPixels(0);
            Color[] newPixels = newTex.GetPixels(0);
            for (int i = 0; i < originalPixels.Length; i++) {
                // As an example we invert the colors
                newPixels[i].r = 1f - originalPixels[i].r; 
                newPixels[i].g = 1f - originalPixels[i].g; 
                newPixels[i].b = 1f - originalPixels[i].b; 
            }
            newTex.SetPixels(newPixels, 0);
            newTex.Apply();
            imageComponent.sprite = Sprite.Create(newTex, baseSprite.rect, baseSprite.bounds.center, baseSprite.pixelsPerUnit);
        }
    }
}

Beware that this instantiates new objects and you have to clean them up when you dont need them anymore.