unity3d - Have different Source Image in Unity 4.6 UI Image prefab depending on script bool property state -
i'd have 1 prefab of image. image , features same, come in 2 colors - i'll need set source image 1 of 2 images depending on actual value of bool in script attached prefab. of course, instead of using 2 images, change color of original image, or draw other way guess method largely same - done inside unity , not in code.
using unity 4.6 final release.
btw inheritance not possible prefabs right?
i assuming refer image component in new ui , want change sprite.
either assign 2 sprites in 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 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); (int = 0; < originalpixels.length; i++) { // example invert 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 instantiates new objects , have clean them when dont need them anymore.
Comments
Post a Comment