- Home /
How can I load and position my sprites in c#?
I'm still trying to learn unity (latest 4.3.3) and coming from a monogame / xna C# background.
In monogame, I could simply run through a List and set each sprites updated position. Childs play.. In unity, this is proving to be an exercise in frustration and I know it has to be something really simple that Im missing..
I have the following in a c# script:
public class Flake
{
public Sprite sprite;
public int col { get; set; }
public int row { get; set; }
public float alpha { get; set; }
public Vector2 pos { get; set; }
public float scale { get; set; }
public Vector2 velocity { get; set; }
GameObject menuObject;
Transform t;
public Flake(Sprite spr, int c, int r, float a, Vector2 p, float s, Vector2 v)
{
col = c;
row = r;
alpha = a;
pos = p;
scale = s;
velocity = v;
}
public void Update(float elapsed)
{
if (sprite == null)
Debug.Log("null sprite!");
alpha -= 45 * elapsed;
alpha = Mathf.Clamp(alpha, 0, 255);
scale -= 0.055f * elapsed;
scale = Mathf.Clamp(scale, 0, 2.0f);
pos += velocity * elapsed;
t.localPosition = new Vector3(pos.x, 0, pos.y);
}
}
In another part of the main script, I am loading my sprites and creating a new "flake" and setting the sprite texture. This "seems" to be working fine.. the sprites are not null..
public Sprite[] sprites;
List<Flake> flakeList = new List<Flake>();
sprites = Resources.LoadAll<Sprite>("Flakes");
flakeList.Add(new Flake(this.sprites[Random.Range(0, this.sprites.GetLength(0) - 1)], 0, 0, 1, new Vector2(1, 1), 1, new Vector2(1, 1)));
Next, I want to update my sprites positions by calling their update and then this is where I am getting stuck. I have my sprite object, and I have tried playing with the renderer and transforms, but I can not figure out how to make the sprites actually display on the scene and update their positions. I would think its a simple:
t.localPosition = new Vector3(pos.x, 0, pos.y);
But Im not getting it to work.. So how does one go about making these sprites appear and update their position on screen?? Do I need to instantiate a new gameobject for each? or ??
Any help would be greatly appreciated!
If you want to view the full script, its here: http://pastebin.com/9fqz2wVh
and the main part does derive from a monobehavior.. I dont want the Flake class to update itself really..
Answer by zee_ola05 · Feb 23, 2014 at 08:40 PM
What you need is to create a Flake Prefab and Instantiate it to add it to the scene..
Create A Flake GameObject: Drag your Flake Sprite Texture to Scene.
Make it a Prefab: Drag your Flake GameObject to Project.
You can load that prefab via Resources.Load() and Instantiate.
Hope it helps.