I'm lost. Basically I would like to create a gameobject and assign a sprite to it. The problem now seems to exchange the sprite during runtime with void OnMouseDown It would have been simple to just exchange the components SpriteRenderer Sprite but I'm not able to do that. For simplicity I also created a new image and sliced it because I thought I can simply change the [] index of the slices. But I could not find a way. I found this one which looked promising: Code (csharp): private Sprite mySprite; // Use this for initialization void Start () { GetComponent<SpriteRenderer>().sprite = mySprite = new Sprite(); But every try to do something with mySprite failed.
I did some more tests and if I change this: Code (csharp): private Sprite mySprite; // Use this for initialization void Start () { GetComponent<SpriteRenderer>().sprite = mySprite = new Sprite(); to Code (csharp): public Sprite mySprite; // Use this for initialization void Start () { GetComponent<SpriteRenderer>().sprite = mySprite; it works with the spite assets I drop in the inspector. So it''s possible. Can someone help how to to do the same from a script? Thanks a lot
I found a solution for my case. Maybe someone can help with the solution First I created a folder Resources and put a png in it. For example back.png. Now my working code: Code (csharp): public Sprite mySprite; // Use this for initialization void Start () { mysprite = Resources.Load("back",typeof(Sprite)) as Sprite; GetComponent<SpriteRenderer>().sprite = mySprite; And that's it
This should work for you: Code (csharp): //Load the .png Sprite backSprite = Resources.Load("back", typeof(Sprite)) as Sprite; //Create a new gameobject GameObject obj = new GameObject("Ducky-By-Code"); //Attach a SpriteRenender to the newly created gameobject SpriteRenderer rend = obj.AddComponent(typeof(SpriteRenderer)) as SpriteRenderer; //Assign the sprite to the SpriteRenender rend.sprite = backSprite;
Thanks a lot loki70x7 Your version is basically the same I have now up and running. I needed it for a "low" level beginner solution to create a memory/pairs game in 2D. Now I should find the time and recreate all bitmaps I use to have shadow ... A "highscore" is on my list as well. Because this is a gift, I had no time to create the tiles in blender so that I could make it a "real" 3d object. So far I like Unity. First projekt and it runs. Even with some little sound
Hi all, I have a question regarding this, how can I access the sprites with multiple frames that I've already created in the editor, instead of loading them up from the resources folder?