- Home /
Instantiate a gameObject with a dynamically generated sprite?
Hi, I'm trying to create terrain using randomized sinusoidal functions (NYI) but I can't seem to get any dynamically generated sprites to draw. Here's my current code:
 public class GenerateTerrain : MonoBehaviour {
 
     public int initialCount;
     List<GameObject> terrains;
     public GameObject prefab;
 
     // Use this for initialization
     void Start()
     {
         terrains = new List<GameObject>();
         for (int i = 0; i < initialCount; i++)
         {
             AddTerrain();  
         }
     }
 
     public void AddTerrain()
     {
         // create texture
         // placeholder: 800 x 600, all white
         Texture2D texture = new Texture2D(800, 600);
         Color[] pixels = new Color[texture.width * texture.height];
         for (int i = 0; i < pixels.Length; i++)
         {
              pixels[i] = Color.red;
         }
         texture.SetPixels(pixels);
         texture.Apply();
 
         // instantiate new terrain
         GameObject terrain = Instantiate(prefab) as GameObject;
         
         // add components
         // create new sprite from generated texture, pivot in middle
         Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(texture.width * 0.5f, texture.height * 0.5f));
 
         // create new renderer and assign it the sprite
         SpriteRenderer spriteRenderer = terrain.AddComponent<SpriteRenderer>();
         spriteRenderer.sprite = sprite; 
 
         // generate collider
         terrain.AddComponent<PolygonCollider2D>();
 
         // add to list for later removal (memory management)
         terrains.Add(terrain);
     }
 }
The initialCount variable is set to 1 and the prefab is an empty gameObject (just a transform with default values). The inspector shows a single terrain being created and the preview window shows an 800x600 red sprite, but nothing appears on screen. Any suggestions are welcome!
Your answer
 
 
             Follow this Question
Related Questions
Can I create a sprite at runtime? 3 Answers
Slicing sliced sprite via script 0 Answers
How do I make sure my sprites are fitted properly to my textures? 1 Answer
How do I fill a Texture2D with pixels and display a sprite with that texture using script? 1 Answer
Can't create a 2D sprite with Sprite.Create when creating texture in code 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                