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();
	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?

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.

I found the answer myself on this page

The code that works is:

gameObject.GetComponent(SpriteRenderer).sprite = Resources.Load("Sprites/Stars/redStar", typeof(Sprite));

Still, thanks for the help