Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Help Attaching Sprites to SpriteRenderer at runtime.

Discussion in 'Scripting' started by QuinnDP, Jan 30, 2017.

  1. QuinnDP

    QuinnDP

    Joined:
    Dec 12, 2016
    Posts:
    22
    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?

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Laser : MonoBehaviour {
    5.  
    6.     // Colour B=Blue, G=Green, R=Red
    7.     // Height T=Tall, S=Short
    8.     // Filling E=Empty, M=Medium, F=Full
    9.     // Laser Width T=Thin, W=Wide
    10.  
    11.     public string colour = "B";
    12.     public string height = "T";
    13.     public string filling = "E";
    14.     public string laserWidth = "T";
    15.  
    16.     void Awake () {
    17.         string spriteName = "Lasers/laser" + colour + "_" + height + filling + laserWidth;
    18.         SpriteRenderer spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
    19.         spriteRenderer.sprite = Resources.Load(spriteName);
    20.     }
    21. }
    sprites.png
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    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.
     
    Smuggler20 and QuinnDP like this.
  3. Smuggler20

    Smuggler20

    Joined:
    Apr 20, 2015
    Posts:
    19
    Just do this:

    Code (CSharp):
    1. Resources.Load<Sprite>(spriteName);
     
    QuinnDP likes this.