Guest User

For Stackoverflow

a guest
Feb 24th, 2021
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 9.65 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. //  Optimise theory - Since the world generates as 1 pixel = a block, optimise by only loading in blocks that are currently visible to the player camera
  7. //  Or, use multiple pixels to load blocks instead of 1 pixel per block
  8. public class ReadImage : MonoBehaviour
  9. {
  10.     [SerializeField]
  11.     private Texture2D[] _images;
  12.     private Texture2D _image;
  13.     [SerializeField]
  14.     private GameObject _wall;
  15.     [SerializeField]
  16.     private GameObject _ground;
  17.     private string _imagesDir = "/LevelImages";
  18.     [SerializeField]
  19.     private Text _levelText;
  20.     [SerializeField]
  21.     private float _scale;
  22.  
  23.     private List<GameObject> groundObjectsToCombine = new List<GameObject>();
  24.     private List<GameObject> wallObjectsToCombine = new List<GameObject>();
  25.  
  26.     public GameObject[] groundObjects;
  27.     public GameObject[] wallObjects;
  28.  
  29.     private void Start()
  30.     {
  31.         string dataPath = Application.persistentDataPath;
  32.         _imagesDir = dataPath + _imagesDir;
  33.  
  34.         if(Directory.Exists(_imagesDir))
  35.         {
  36.             Debug.Log("Dir exists!");
  37.             string[] filesFound = Directory.GetFiles(_imagesDir);
  38.             if(filesFound.Length > 0)
  39.             {
  40.                 _images = new Texture2D[filesFound.Length];
  41.                 int counter = 0;
  42.                 foreach(string fileAndPath in filesFound)
  43.                 {
  44.                     string fileName = fileAndPath.Substring(fileAndPath.LastIndexOf("\\") + 1);                 // Returns name of the file
  45.                     string filePath = _imagesDir + "/" + fileName;                                              // Returns full location of file plus it's name
  46.                    
  47.  
  48.                     if (File.Exists(filePath))
  49.                     {
  50.                         Debug.Log("File exists!");
  51.                         byte[] imageData = File.ReadAllBytes(filePath);                                         // Input all image data into bytes array
  52.                         Texture2D levelTex = new Texture2D(1, 1);                                               // Create a new texture file
  53.                         levelTex.LoadImage(imageData);                                                          // Load byte array (image data) into texture file
  54.                         _images[counter] = levelTex;                                                            // Set current image in array position to = current texture
  55.                         counter++;                                                                              // Increase array position counter
  56.                         //_levelText.text = filePath.ToString();
  57.                     }
  58.                     else
  59.                     {
  60.                         Debug.Log("File not found: " + filePath);
  61.                     }
  62.                 }
  63.                 GenerateImage(_images[Random.Range(0, _images.Length)]);                                        // Run GenerateImage function from random texture in images array
  64.                
  65.             }
  66.             else
  67.             {
  68.                 Debug.LogWarning("No files found in directory! Looking for files at dir: " + _imagesDir);       // Warning log - No files in directory
  69.             }
  70.         }
  71.  
  72.         else
  73.         {
  74.             Debug.LogError("Dir does not exist! Trying to find: " + _imagesDir);                                // Error log - Directory does not exist
  75.         }
  76.     }
  77.  
  78.     private void GenerateImage(Texture2D _image)
  79.     {
  80.         Color[] pixel = _image.GetPixels();                                                                     // Set color array for all pixels in image
  81.  
  82.         int mapX = _image.width;                                                                                // Set map size by image width and height
  83.         int mapZ = _image.height;
  84.  
  85.         Vector3[] spawnPositions = new Vector3[(pixel.Length)];                                                 // Set Vector3 array for spawn positions to = how many pixels exist
  86.         Debug.Log("Amount of pixels = " + pixel.Length);
  87.         Vector3 startSpawnPosition = new Vector3(-Mathf.Round(mapX / 2), 0, -Mathf.Round(mapZ / 2) * _scale);            // Set start position
  88.         Vector3 currentSpawnPosition = startSpawnPosition;                                                      // Ensure current position is the start position
  89.         int counter = 0;
  90.  
  91.         for (int z = 0; z < mapZ; z++)
  92.         {
  93.             for (int x = 0; x < mapX; x++)
  94.             {
  95.                 spawnPositions[counter] = currentSpawnPosition;                                                 // Moves position of image generator along in a left to right then up 'S pattern'
  96.                 counter++;
  97.                 currentSpawnPosition.x+= _scale;
  98.             }
  99.  
  100.             currentSpawnPosition.x = startSpawnPosition.x;
  101.             currentSpawnPosition.z+= _scale;
  102.         }
  103.  
  104.        
  105.         foreach (Vector3 pos in spawnPositions)                                                                 // For each spawn position
  106.         {
  107.             counter = 1;
  108.             int arraycounter = 0;
  109.             Color colour = pixel[counter];                                                                      // Check colour of pixel at counter position
  110.             if (colour.Equals(Color.white))                                                                     // If colour of pixel is white
  111.             {
  112.                 Transform spawnedTransform = Instantiate(_wall, pos, Quaternion.identity).transform;            // Spawn wall for white pixel
  113.                 spawnedTransform.localScale = Vector3.one * _scale;
  114.                 spawnedTransform.localScale = new Vector3(_scale, 3, _scale);
  115.                 //spawnedTransform.transform.parent = gameObject.transform;
  116.                 groundObjectsToCombine.Add(spawnedTransform.gameObject);                                          // Add object to list for wall objects to be mesh combined
  117.                 Debug.Log(arraycounter);
  118.                 groundObjects[arraycounter] = spawnedTransform.gameObject;
  119.                 spawnedTransform.transform.SetParent(groundObjects[arraycounter].transform);
  120.             }
  121.  
  122.             else if (colour.Equals(Color.black))                                                                // If colour of pixel is black
  123.             {
  124.                 Transform spawnedTransform = Instantiate(_ground, pos, Quaternion.identity).transform;          // Spawn ground for black pixel
  125.                 spawnedTransform.localScale = Vector3.one * _scale;
  126.                 //spawnedTransform.transform.parent = gameObject.transform;
  127.                 groundObjectsToCombine.Add(spawnedTransform.gameObject);                                        // Add object to list for ground objects to be mesh combined
  128.                 Debug.Log(arraycounter);
  129.                 groundObjects[arraycounter] = spawnedTransform.gameObject;
  130.                 spawnedTransform.transform.SetParent(groundObjects[arraycounter].transform);
  131.             }
  132.  
  133.             else
  134.             {
  135.                 Transform spawnedTransform = Instantiate(_ground, pos, Quaternion.identity).transform;          // Spawn ground for undefined pixel
  136.                 spawnedTransform.localScale = Vector3.one * _scale;
  137.                 //spawnedTransform.transform.parent = gameObject.transform;
  138.                 groundObjectsToCombine.Add(spawnedTransform.gameObject);                                        // Add object to list for ground objects to be mesh combined
  139.                 Debug.Log(arraycounter);
  140.                 groundObjects[arraycounter] = spawnedTransform.gameObject;
  141.                 spawnedTransform.transform.SetParent(groundObjects[arraycounter].transform);
  142.             }
  143.             counter++;                                                                                          // Increase counter
  144.             arraycounter++;
  145.         }
  146.  
  147.         for (int i = 0; i < groundObjects.Length; i++)
  148.         {
  149.             CombineGroundMeshes(groundObjects[i]);
  150.         }  
  151.  
  152.         // BELOW IS A DEBUG FUNCTION AND IS NOT REQUIRED FOR IMAGE GENERATOR - THIS FUNCTION COUNTS BLACK AND WHITE PIXELS IN INPUT IMAGE
  153.         int black = 0;
  154.         int white = 1;
  155.  
  156.         foreach (Color colour in pixel)
  157.         {
  158.             if (colour.Equals(Color.white))
  159.             {
  160.                 white++;
  161.             }
  162.  
  163.             else if (colour.Equals(Color.black))
  164.             {
  165.                 black++;
  166.             }
  167.         }
  168.  
  169.         Debug.Log("White = " + white);
  170.         Debug.Log("Black = " + black);
  171.     }
  172.  
  173.     private void CombineGroundMeshes(GameObject groundobj)
  174.     {
  175.         Debug.Log("I got here");
  176.         Vector3 position = groundobj.transform.position;
  177.         groundobj.transform.position = Vector3.zero;
  178.  
  179.         MeshFilter[] meshfilters = groundobj.GetComponentsInChildren<MeshFilter>();
  180.         CombineInstance[] combine = new CombineInstance[meshfilters.Length];
  181.         int amt = 1;
  182.         while(amt < meshfilters.Length)
  183.         {
  184.             combine[amt].mesh = meshfilters[amt].sharedMesh;
  185.             combine[amt].transform = meshfilters[amt].transform.localToWorldMatrix;
  186.             meshfilters[amt].gameObject.SetActive(false);
  187.             amt++;
  188.         }
  189.  
  190.         groundobj.transform.GetComponent<MeshFilter>().mesh = new Mesh();
  191.         groundobj.transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine, true, true);
  192.         groundobj.transform.gameObject.SetActive(true);
  193.  
  194.         groundobj.transform.position = position;
  195.         groundobj.AddComponent<MeshCollider>();
  196.     }
  197. }
  198.  
Advertisement
Add Comment
Please, Sign In to add comment