Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Need to add a layer to my terrain chunks VIA SCRIPT URGENT!

Discussion in 'Scripting' started by MrBlub2010, Oct 12, 2020.

  1. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    Hey guys, im trying to figure out a way in VS Code and in Unity3d to add layers to objects such as my terrain chunks. This is a very urgent need of help and I only started about 3 - 4 months ago I think.

    Ill give you my script and i hope some people can help me...


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. public class Chunk : MonoBehaviour {
    6.  
    7.     const float scale = 5f;
    8.  
    9.     const float viewerMoveThresholdForChunkUpdate = 25f;
    10.     const float sqrViewerMoveThresholdForChunkUpdate = viewerMoveThresholdForChunkUpdate * viewerMoveThresholdForChunkUpdate;
    11.  
    12.     public LODInfo[] detailLevels;
    13.     public static float maxViewDst;
    14.  
    15.     public Transform viewer;
    16.     public Material mapMaterial;
    17.  
    18.     public static Vector2 viewerPosition;
    19.     Vector2 viewerPositionOld;
    20.     static MapGenerator mapGenerator;
    21.     int chunkSize;
    22.     int chunksVisibleInViewDst;
    23.  
    24.     Dictionary<Vector2, TerrainChunk> terrainChunkDictionary = new Dictionary<Vector2, TerrainChunk>();
    25.     static List<TerrainChunk> terrainChunksVisibleLastUpdate = new List<TerrainChunk>();
    26.  
    27.     void Start() {
    28.         mapGenerator = FindObjectOfType<MapGenerator> ();
    29.  
    30.         maxViewDst = detailLevels [detailLevels.Length - 1].visibleDstThreshold;
    31.         chunkSize = MapGenerator.mapChunkSize - 1;
    32.         chunksVisibleInViewDst = Mathf.RoundToInt(maxViewDst / chunkSize);
    33.  
    34.         UpdateVisibleChunks ();
    35.     }
    36.  
    37.     void Update() {
    38.         viewerPosition = new Vector2 (viewer.position.x, viewer.position.z) / scale;
    39.  
    40.         if ((viewerPositionOld - viewerPosition).sqrMagnitude > sqrViewerMoveThresholdForChunkUpdate) {
    41.             viewerPositionOld = viewerPosition;
    42.             UpdateVisibleChunks ();
    43.         }
    44.     }
    45.    
    46.     void UpdateVisibleChunks() {
    47.  
    48.         for (int i = 0; i < terrainChunksVisibleLastUpdate.Count; i++) {
    49.             terrainChunksVisibleLastUpdate .SetVisible (false);
    50.         }
    51.         terrainChunksVisibleLastUpdate.Clear ();
    52.          
    53.         int currentChunkCoordX = Mathf.RoundToInt (viewerPosition.x / chunkSize);
    54.         int currentChunkCoordY = Mathf.RoundToInt (viewerPosition.y / chunkSize);
    55.  
    56.         for (int yOffset = -chunksVisibleInViewDst; yOffset <= chunksVisibleInViewDst; yOffset++) {
    57.             for (int xOffset = -chunksVisibleInViewDst; xOffset <= chunksVisibleInViewDst; xOffset++) {
    58.                 Vector2 viewedChunkCoord = new Vector2 (currentChunkCoordX + xOffset, currentChunkCoordY + yOffset);
    59.  
    60.                 if (terrainChunkDictionary.ContainsKey (viewedChunkCoord)) {
    61.                     terrainChunkDictionary [viewedChunkCoord].UpdateTerrainChunk ();
    62.                 } else {
    63.                     terrainChunkDictionary.Add (viewedChunkCoord, new TerrainChunk (viewedChunkCoord, chunkSize, detailLevels, transform, mapMaterial));
    64.                 }
    65.  
    66.             }
    67.         }
    68.     }
    69.  
    70.     public class TerrainChunk {
    71.  
    72.         GameObject meshObject;
    73.         Vector2 position;
    74.         Bounds bounds;
    75.  
    76.         MeshRenderer meshRenderer;
    77.         MeshFilter meshFilter;
    78.         MeshCollider colliderMesh;
    79.      
    80.  
    81.         LODInfo[] detailLevels;
    82.         LODMesh[] lodMeshes;
    83.  
    84.         MapData mapData;
    85.         bool mapDataReceived;
    86.         int previousLODIndex = -1;
    87.  
    88.         public TerrainChunk(Vector2 coord, int size, LODInfo[] detailLevels, Transform parent, Material material) {
    89.             this.detailLevels = detailLevels;
    90.  
    91.             position = coord * size;
    92.             bounds = new Bounds(position,Vector2.one * size);
    93.             Vector3 positionV3 = new Vector3(position.x,0,position.y);
    94.  
    95.             meshObject = new GameObject("Terrain Chunk");
    96.             meshRenderer = meshObject.AddComponent<MeshRenderer>();
    97.             meshFilter = meshObject.AddComponent<MeshFilter>();
    98.             colliderMesh = meshObject.AddComponent<MeshCollider>();
    99.          
    100.      
    101.  
    102.             meshRenderer.material = material;
    103.  
    104.             meshObject.transform.position = positionV3 * scale;
    105.             meshObject.transform.parent = parent;
    106.             meshObject.transform.localScale = Vector3.one * scale;
    107.             SetVisible(false);
    108.  
    109.             lodMeshes = new LODMesh[detailLevels.Length];
    110.             for (int i = 0; i < detailLevels.Length; i++) {
    111.                 lodMeshes = new LODMesh(detailLevels.lod, UpdateTerrainChunk);
    112.             }
    113.  
    114.             mapGenerator.RequestMapData(position,OnMapDataReceived);
    115.         }
    116.  
    117.         void OnMapDataReceived(MapData mapData) {
    118.             this.mapData = mapData;
    119.             mapDataReceived = true;
    120.  
    121.             Texture2D texture = TextureGenerator.TextureFromColourMap (mapData.colourMap, MapGenerator.mapChunkSize, MapGenerator.mapChunkSize);
    122.             meshRenderer.material.mainTexture = texture;
    123.  
    124.             UpdateTerrainChunk ();
    125.         }
    126.  
    127.  
    128.  
    129.         public void UpdateTerrainChunk() {
    130.             if (mapDataReceived) {
    131.                 float viewerDstFromNearestEdge = Mathf.Sqrt (bounds.SqrDistance (viewerPosition));
    132.                 bool visible = viewerDstFromNearestEdge <= maxViewDst;
    133.  
    134.                 if (visible) {
    135.                     int lodIndex = 0;
    136.  
    137.                     for (int i = 0; i < detailLevels.Length - 1; i++) {
    138.                         if (viewerDstFromNearestEdge > detailLevels .visibleDstThreshold) {
    139.                             lodIndex = i + 1;
    140.                         } else {
    141.                             break;
    142.                         }
    143.                     }
    144.  
    145.                     if (lodIndex != previousLODIndex) {
    146.                         LODMesh lodMesh = lodMeshes [lodIndex];
    147.                         if (lodMesh.hasMesh) {
    148.                             previousLODIndex = lodIndex;
    149.                             meshFilter.mesh = lodMesh.mesh;
    150.                             colliderMesh.sharedMesh = lodMesh.mesh;
    151.                         } else if (!lodMesh.hasRequestedMesh) {
    152.                             lodMesh.RequestMesh (mapData);
    153.                         }
    154.                     }
    155.  
    156.                     terrainChunksVisibleLastUpdate.Add (this);
    157.                 }
    158.  
    159.                 SetVisible (visible);
    160.             }
    161.         }
    162.  
    163.         public void SetVisible(bool visible) {
    164.             meshObject.SetActive (visible);
    165.         }
    166.  
    167.         public bool IsVisible() {
    168.             return meshObject.activeSelf;
    169.         }
    170.  
    171.     }
    172.  
    173.     class LODMesh {
    174.  
    175.         public Mesh mesh;
    176.         public bool hasRequestedMesh;
    177.         public bool hasMesh;
    178.         int lod;
    179.         System.Action updateCallback;
    180.  
    181.         public LODMesh(int lod, System.Action updateCallback) {
    182.             this.lod = lod;
    183.             this.updateCallback = updateCallback;
    184.         }
    185.  
    186.         void OnMeshDataReceived(MeshData meshData) {
    187.             mesh = meshData.CreateMesh ();
    188.             hasMesh = true;
    189.  
    190.             updateCallback ();
    191.         }
    192.  
    193.         public void RequestMesh(MapData mapData) {
    194.             hasRequestedMesh = true;
    195.             mapGenerator.RequestMeshData (mapData, lod, OnMeshDataReceived);
    196.         }
    197.  
    198.     }
    199.  
    200.     [System.Serializable]
    201.     public struct LODInfo {
    202.         public int lod;
    203.         public float visibleDstThreshold;
    204.     }
    205.  
    206. }
     
  2. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    Welp. No one has replied yet. :(
     
  3. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,992
  4. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    @mgear where am i meant to put rthat?
     
  5. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
  6. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,992
    ok they are using mesh, so that script wont help (its for unity terrain).

    in which part your are at? or already finished, and want to add new features?
     
  7. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    Im at EO9 but because i have a character for my jump script to work i need the ground to be layered to Ground otherwise i wont be able to jump. Player needs to be &&Grounded. Ive got a brackeys vid i watched for the player movement


    This should be a better explanation. :)
     
  8. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    if your wondering what E09 means its pretty simple Episode 9 lol.
     
  9. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,992
    ok, totally misunderstood terrain & layers :)

    can assign layer to gameobject from script, with something like:
    Code (CSharp):
    1. public LayerMask groundLayer; // you can assign this layer in inspector
    2. ..
    3. // go is the gameobject you want to assign layer to
    4. go.layer = (int)(Mathf.Log((uint)groundLayer.value, 2));
    or maybe directly with:
    Code (CSharp):
    1.  
    2. // go is the gameobject you want to assign layer to
    3. go.layer = (int)(Mathf.Log((uint)LayerMask.NameToLayer("MyLayer"), 2));
     
  10. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
  11. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,992
    in your script its the chunk gameobject, so probably: meshObject
     
  12. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    IVe got the scripts working its adding something but i dont know what?
     
  13. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    And i cant jump
    still
     
  14. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    What does the 2 stand for?
     
  15. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,992
    can you see from hierarchy, does the chunk have a correct layer now?

    if you used the first script, then need to assign the layer in inspector,
    if you used the 2nd script, need to set the correct layer name into that "MyLayer"
     
  16. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    i used the second script but hmm let me try again
     
  17. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    @mgear i need to kno what the 2 at the end means?
     
  18. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,992
  19. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    @mgear its not Giving the layer i want it to
    :( :/
     
  20. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,992
    ok tested it in unity, no need for that conversion in the 2nd script,
    Code (CSharp):
    1. go.layer = LayerMask.NameToLayer("Ground");
     
  21. MrBlub2010

    MrBlub2010

    Joined:
    Aug 24, 2020
    Posts:
    66
    DUDE THANKS SO MUCH! :)
    You fixed my issue!
     
  22. Cranky5

    Cranky5

    Joined:
    Feb 18, 2023
    Posts:
    3
    how u fix that problem ?
     
  23. Cranky5

    Cranky5

    Joined:
    Feb 18, 2023
    Posts:
    3
    u remember where to put this in to work so the Generated Terrain Chunk got the Layer Ground ?
     
  24. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,992
    should be somewhere where it generates any new gameobject()
     
  25. Cranky5

    Cranky5

    Joined:
    Feb 18, 2023
    Posts:
    3
    okay so i complete the same Tutorial and i think i should go in TerrainChunk Script in Line 46

    but he says :
    Error CS0103 The name 'go' does not exist in the current context
     
  26. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,992
    it might use different variable name for the created gameobject,
    like in the original script on first message here, its "meshObject"
    meshObject = new GameObject("Terrain Chunk");