- Home /
Help with changing spririterenderer's sprite
I am making a 2d map of stars. All the stars get random parameters like color. I want to change the star's sprite according to it's color variable. Right now this is my code (JS) in the star objects, i change the sprite in the start function:
function Start(){
starColor = GenStarColor();
starSpectrum = GenStarSpectrum();
starTemperature = GenStarTemperature();
starLuminosity = GenStarLuminosity();
Debug.Log(starColor);
Debug.Log(starSpectrum);
Debug.Log(starTemperature);
Debug.Log(starLuminosity);
var starSprite = Resources.Load("redStar");
GetComponent(SpriteRenderer).sprite = starSprite;
}
The game compiles, but i get the error: InvalidCastException: Cannot cast from source type to destination type. starControler.Start () (at Assets/Scripts/starControler.js:33)
Also no sprite is attached to the star's spriterenderer.
I know that you could attach the sprite manualy in the inspector, but i am creating the star objects at runtime.
Anyone got an idea what i am doing wrong?
Answer by Avanak · Sep 28, 2014 at 01:29 PM
I found the answer myself on this page http://forum.unity3d.com/threads/how-to-change-sprite-image-from-script.212307/
The code that works is:
gameObject.GetComponent(SpriteRenderer).sprite = Resources.Load("Sprites/Stars/redStar", typeof(Sprite));
Still, thanks for the help
Answer by grrlgglglr · Sep 28, 2014 at 12:16 PM
My guess is you're trying to assign a regular Texture
directly to SpriteRenderer.sprite
. You need to create a Sprite
first. Try
var starTexture = Resources.Load("redStar", typeof(Texture2D));
var starSprite = Sprite.create(starTexture, ... ) // Add your import parameters here
to get a sprite object which you should be able to assign to the Sprite Renderer. Hope that helps.
Your answer
Follow this Question
Related Questions
Sprite creation problem 1 Answer
Change gameobject sprite with button 1 Answer
Unknown Error. 3 Answers
runtime: script variable not processed as demanded 1 Answer
Rendering sprites as meshes 1 Answer