Search Unity

Resolved Optimizing texturing of an object.

Discussion in 'Visual Scripting' started by pawelekezg, Oct 22, 2021.

  1. pawelekezg

    pawelekezg

    Joined:
    Nov 7, 2019
    Posts:
    12
    Hey,
    I have in my game a big wall which is generated on runtime and i have it textured by a script:
    Code (CSharp):
    1.  
    2.     Mesh mesh;
    3.     Vector2[] uvs;
    4.     Vector3[] meshVer;
    5.  
    6.     void Start()
    7.     {
    8.         mesh = transform.GetComponent<MeshFilter>().mesh;
    9.  
    10.         if (mesh.vertices != null && mesh.vertices.Length > 0)
    11.             meshVer = mesh.vertices;
    12.         else
    13.             meshVer = new Vector3[0];
    14.     }
    15.  
    16.     void calculateTexture()
    17.     {
    18.         uvs = new Vector2[mesh.vertices.Length];
    19.         Vector3[] normals = mesh.normals;
    20.         for (int i = 0; i < mesh.vertices.Length; i++)
    21.         {
    22.  
    23.             if (Mathf.Abs(normals[i].y) > 0.5f)
    24.                 uvs[i] = new Vector2(mesh.vertices[i].x, mesh.vertices[i].z);
    25.             else if (Mathf.Abs(normals[i].x) > 0.5f)
    26.                 uvs[i] = new Vector2(mesh.vertices[i].z, mesh.vertices[i].y);
    27.             else
    28.                 uvs[i] = new Vector2(mesh.vertices[i].x, mesh.vertices[i].y);
    29.  
    30.         }
    31.  
    32.         mesh.uv = uvs;
    33.         mesh.RecalculateNormals();
    34.         mesh.RecalculateBounds();
    35.         mesh.Optimize();
    36.         meshVer = mesh.vertices;
    37.  
    38.     }
    39.  
    40.     void Update()
    41.     {
    42.         if (mesh.vertices != null && mesh.vertices.Length > 0)
    43.         {
    44.             if (!checkArrays(meshVer, mesh.vertices))
    45.             {
    46.                 calculateTexture();
    47.             }
    48.         }
    49.     }
    50.  
    51.     bool checkArrays(Vector3[] arr1, Vector3[] arr2)
    52.     {
    53.  
    54.         if (arr1.Length != arr2.Length)
    55.             return false;
    56.  
    57.         for (int i = 0; i < arr1.Length; i++)
    58.         {
    59.             if (!(arr1[i].x == arr2[i].x && arr1[i].y == arr2[i].y && arr1[i].z == arr2[i].z))
    60.                 return false;
    61.         }
    62.  
    63.         return true;
    64.     }
    65. }
    66.  
    It's texturing the wall properly as i want it to be but there is a problem when a player destroys the wall (it's a game about destroying surroundings). As i mentioned the wall is big and when it comes to retexturing the wall (which part of it was destroyed-deleted) it takes too long, because it retextures the whole wall. I was wondering whether it is possible and if so how to make the script retexture only the part of wall which has been destroyed...