Search code examples
unity-game-engine2dspriteunityscript

How to programmatically assign a random sprite to game object?


I have a function that generates a game object on screen every 100 frames:

 var trash : Transform ;
 function Update()
 {
      if(count == 1)
      {
         Instantiate(trash,new Vector3(UnityEngine.Random.Range(-3f,3f),UnityEngine.Random.Range(-3f,3f),UnityEngine.Random.Range(-3f,3f)), Quaternion.identity);
      }

     else if(count == 100)
     {
         count = 0;
     }
 }

Now, I want each of those generated objects to pick a random sprite from my assets. I thought about making a sprite array and picking from that, but I'm not sure how to go about doing so or how to assign the sprite to the object.

Anu help would be much appreciated!


Solution

  • Well, you can generate an array of sprites of the length of your choosing with: Sprite[] _sprites = new Sprite[quantity desired]

    Then using the resources folder and the Resources.Load method (found here: http://docs.unity3d.com/ScriptReference/Resources.Load.html), you could load all your sprites into the array one after the other. Then using your random number generator, you can access sprites at random from it.

    Still probably not the best way of doing it, but I would imagine it is considerably better and easier to maintain than the prefab method, but different situations call for different approaches.