Hello Guest

Author Topic: Randomly instantiating sprites in a sprite collection?  (Read 4085 times)

neo750a

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 4
    • View Profile
Randomly instantiating sprites in a sprite collection?
« on: December 28, 2013, 01:24:57 am »
Is this possible?  Or do i have to make a database myself and store prefabs to achieve this?  It would be immensely helpful if I could as it would cut out alot of what I need done.  What I am trying to do is to display 6 different sprites on 6 random points(one unique sprite each point) on the game view.  Thanks in advance and sorry if this was asked previously.

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Randomly instantiating sprites in a sprite collection?
« Reply #1 on: December 28, 2013, 07:37:28 pm »
Create a prefab of a sprite from the sprite collection, instantiate it and then change the sprite Id using something like this:

Code: [Select]
int randomSprite = 0;
do {
  randomSprite = Random.Range(0, sprite.Collection.Count);
} while (!sprite.Collection.spriteDefinitions[randomSprite].Valid);
sprite.SetSprite( randomSprite);

the while loop is necessary in case you have deleted / invalid sprites in your collection.

neo750a

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 4
    • View Profile
Re: Randomly instantiating sprites in a sprite collection?
« Reply #2 on: January 05, 2014, 01:19:59 am »
Create a prefab of a sprite from the sprite collection, instantiate it and then change the sprite Id using something like this:

Code: [Select]
int randomSprite = 0;
do {
  randomSprite = Random.Range(0, sprite.Collection.Count);
} while (!sprite.Collection.spriteDefinitions[randomSprite].Valid);
sprite.SetSprite( randomSprite);

the while loop is necessary in case you have deleted / invalid sprites in your collection.

I have to say, thank very much for the response!  Sorry for the long reply.  This helped me out immensely!