Okay, I know bout the Animator and Mecanim...but setting a single sprite?

Hello everybody,

I just ran into a problem regarding setting a sprite to a enemy.
Let me explain my enemy and the game-view first.

The game is top down.
The enemy can walk → up, down, left, right.
The enemy can stand still.

So, I got the animations for the walking done…but…
How can I programatically set the SINGLE sprite when the enemy is standing still and looking into a single direction?

I read about loading the sprite from the ressources…but that would mean I have to move all sprites into a “Ressources” folder…

Isn’t there some other way to approach it?
Do I really have to create animations with just a single image so I can assign this in the Animator?

Thanks in advance :slight_smile:

You need to put the sprites you will set programmatically in the resource folder. All others can remain where they are.

Here’s some code from a little demo game I did with my students:

using UnityEngine;
using System.Collections;

public class Spawn : MonoBehaviour {
    public GameObject pokemon;

    Sprite[] sprites;

    // Use this for initialization
    void Start () {
        sprites = Resources.LoadAll<Sprite> ("Pokemon");

        Spawner ();
    }
   
    void Spawner() {
        GameObject p = (GameObject)Instantiate (pokemon);
       
        SpriteRenderer sr = p.GetComponent<SpriteRenderer> ();
       
        sr.sprite = sprites [Random.Range (0, sprites.Length)];

        float time = Random.Range (0.1f, 1.0f);
       
        Invoke ("Spawner", time);
    }
}
1 Like

Hey PGJ,

once again: Thanks for your help. Nice to see u around :slight_smile:
So, basicly I will always need a Ressources folder…

Well, okay, fine… I’ll try to setup my games like that from now on :slight_smile:

Edit
Okay, …can you maybe tell me how to deactivate the Animator logic?
I want the animator logic to work unless I want to use my single sprites…but it seems the animator always overwrites my single image sprite assignment :frowning:

You need to disable the animator when you want to handle the sprite’s images yourself and then turn it back on once you need it to handle the animation. In your case it’s probably much better to create single frame animations and trigger them, instead of turning the animator component off and on again all the time.

1 Like