Help Attaching Sprites to SpriteRenderer at runtime.

I have a fairly large group of projectile sprites, named and ordered so that the code can chose which sprite to use. I am having some problems attaching the sprite to the Prefab on spawn. The problem lies in the code syntax almost certainly, but after hunting I’ve been unable to find a solution.

Here is a screenshot of the projectiles and a copy of the code, if anyone could help me out I would be very grateful.

The problem lies with the 19th line, spriteRenderer.sprite is asking for a gameObject for some reason, but I’m linking it to a group of sprites. How can I give the Sprite Renderer component a sprite and have it attach and change sprite on spawn?

using UnityEngine;
using System.Collections;

public class Laser : MonoBehaviour {

    // Colour B=Blue, G=Green, R=Red
    // Height T=Tall, S=Short
    // Filling E=Empty, M=Medium, F=Full
    // Laser Width T=Thin, W=Wide

    public string colour = "B";
    public string height = "T";
    public string filling = "E";
    public string laserWidth = "T";

    void Awake () {
        string spriteName = "Lasers/laser" + colour + "_" + height + filling + laserWidth;
        SpriteRenderer spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
        spriteRenderer.sprite = Resources.Load(spriteName);
    }
}

I suspect the error is more likely complaining that Resources.Load is returning an Object, which is something completely different from a GameObject.

https://docs.unity3d.com/ScriptReference/Resources.Load.html

there is nothing in that which says “hey this is going to be a sprite”.

have a look at the API page for Resources.Load (linked above) and it’ll show you that you need to cast the returned object to the relevant type.

2 Likes

Just do this:

Resources.Load<Sprite>(spriteName);
1 Like