Search Unity

How to programmatically change sprite of an object

Discussion in 'Scripting' started by adk172, Mar 16, 2014.

  1. adk172

    adk172

    Joined:
    Mar 16, 2014
    Posts:
    9
    Hi, I'm new to Unity and there's something about it's architecture that I'm still not fully understanding... for example I'm trying to create an object that will show (depending on a few conditions) different sprites.

    Now I know a GameObject can have a Sprite Renderer component which is responsible of showing his sprite, so, If I drag from the assets an image.png into the game scene, Unity is automatically creating that Object wich the Sprite Renderer component, which is fine.

    But programmatically I would like to change that sprite... so I need to:

    1. access programmatically the assets to see all the sprites and choose one of them
    2. assign that chosen sprite to the current object, so that the Sprite Renderer will show a different sprite (changed programmatically)

    how can I do these two things? I'm looking around the web without any luck on how to achieve this result, thank you very much
     
  2. raycosantana

    raycosantana

    Joined:
    Dec 23, 2012
    Posts:
    319
    Have you search in the script reference?

    http://docs.unity3d.com/Documentation/ScriptReference/SpriteRenderer.html

    I havent use sprite renderer yet but I know you don't need to access all the assets and choose one of them by code, you just need to store all the sprites you will ever use in a public Variable (for example a Texture2D array) and use them when needed.

    to change the sprite you need to change the variable "sprite" from the SpriteRenderer.
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Code (csharp):
    1. var someSprite : Sprite;
    2.  
    3. function Start () {
    4.     GetComponent(SpriteRenderer).sprite = someSprite;
    5. }
    --Eric
     
  4. adk172

    adk172

    Joined:
    Mar 16, 2014
    Posts:
    9
    Thanks to both of you, now I understand how to reference from components and different scripts, I only need to understand how to store all my sprites inside an array.

    Actually I did an array inside the script, then I dragged from the assets a few sprites into the array in the Inspector but the elements seems not to be in the array when the scene start (I did a print), why? I have to add them programmatically?

    YES I did it, thank you very much :)
     
    Last edited: Mar 16, 2014
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Code (csharp):
    1. var sprites : Sprite[];
    2.  
    3. function Start () {
    4.     for (spr in sprites) {
    5.         Debug.Log (spr.name);
    6.     }
    7. }
    --Eric