- Home /
Change Unity 4.6 UI Image element's sprite via script?
Hi there! I'm using the following code to generate a series of buttons with images on top of them, which for the most part is working fine:
function RedefineScrollbar()
{
for(var i=0;i<curComponents.length;i++)
{
var newButton = Instantiate(componentButton,Vector3(0,0,0),Quaternion.identity);
newButton.parent=shipComponentHolder;
var thumb : RectTransform = newButton.Find("Thumbnail");
thumb.GetComponent(UnityEngine.UI.Image).sprite = curComponents[i].thumbnail;
}
}
This compiles fine, but the last line causes the following error on every frame:
MissingReferenceException: The object of type 'Sprite' has been destroyed but you are still trying to access it.
Here's what the image I'm accessing looks like as a prefab:
http://i.imgur.com/CLbrQJv.jpg
And here is the jumbled mess it looks like as it actually gets instantiated:
http://i.imgur.com/hnkCpjM.jpg
Any insight as to why this is happening would be greatly appreciated!
I'm not really sure but it looks like a bug. Remember Unity 4.6 is a beta release. You should probably tell them if it doesn't get fixed.
Answer by _dns_ · Oct 13, 2014 at 03:19 PM
Hi, I'm modifying Image.overrideSprite and it works well.
This has restored the prefab to working order in the inspector, and all looks well, but the error persists and it is still not rendering correctly. Thank you, this is a step in the right direction.
So this must be that the "curComponents[i].thumbnail" sprites are already destroyed. Where do they come from ?
They come from a class within the same script, and are defined in the inspector, as in this screenshot.
http://i.imgur.com/lwlAi4C.jpg
They still look normal at runtime, as well.
Got it! I had changed the import settings of the sprite to sprite, but hadn't reassigned this to the class component, meaning they were still trying to accept it as a texture2D! So I had two problems I suppose! Thanks for your help!
Answer by Raynoko · Feb 02, 2015 at 01:32 PM
here is solution
public Sprite mySprites;
public void Start()
{
GetComponent<UnityEngine.UI.Image>().sprite = mySprites;
}