Random object and random sprites?
I have a game where you check other people bags, I wanted to have a pre-defined layout for the bag and have it randomly picked, I also wanted the items inside the bag to have a random sprite. Can you help me with the logic for this? I'm thinking about using an array of prefabs
Answer by dacarrera · Nov 11, 2019 at 01:25 AM
There are a lot of approaches to this, but here is a common one. Of course this should be changed to meet your specific needs.
Setup a list of possible items that can be shown (however you define your items is up to you) and use Random.Range to grab a random index. If each of your items need random sprites too (i.e there aren't specific sprites to each item) then you can use the same Random.Range to get a random index in a different itemSpriteList.
If you want to use prefabs like mentioned, it could be something like (assuming each of your prefabs have an 'Item' script/component attached): [Untested]
[SerializeField]
private List<Item> possibleItems;
[SerializeField]
private List<Sprite> possibleSprites;
// How you assign will depend on how your bag is setup
// This example will assume your Bag has an items list
private void AssignRandom(int x)
{
// Get a random index from 0 to the length of the list
bag.items[x] = possibleItems[Random.Range(0,possibleItems.Count)]
bag.items[x].sprite = possibleSprites[Random.Range(9,possibleSprites.Count)]
}
It's hard to get an ideal solution without more information about your structure setup, but typically Random.Range is a good way utilize randomization when you don't need true random.
Your answer
Follow this Question
Related Questions
Sprites Clipping Trough 3d Objects 0 Answers
Spawning an object betwheen two positions (while making sure whole object is within area) 1 Answer
is there simple way to put random sprite to gameobject multi child with no repating. 1 Answer
Random Object Selection 0 Answers
making object move forward 0 Answers