As the title says, I’m trying to make procedurally generated terrain with netcode, and just can’t figure out how to do it. This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Netcode;
public class MeshGenerator : NetworkBehaviour
{
Mesh mesh;
Vector3[] vertices;
int[] triangles;
public int xSize = 40;
public int zSize = 40;
public int Scale = 20;
public Vector2 maxMinOffset;
public void Start()
{
mesh = new Mesh();
mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
GetComponent<MeshFilter>().mesh = mesh;
this.gameObject.AddComponent<MeshCollider>().sharedMesh = mesh;
GetComponent<MeshCollider>().convex = true;
CreateShape();
UpdateMesh();
}
void CreateShape()
{
vertices = new Vector3[(xSize + 1) * (zSize + 1)];
for (int i = 0, z = 0; z <= zSize; z++)
{
for (int x = 0; x <= xSize; x++)
{
float scaleY = Random.Range(maxMinOffset.x, maxMinOffset.y);
float y = Mathf.PerlinNoise(x * scaleY, z * scaleY);
vertices[i] = new Vector3(x * Scale, y * Scale, z * Scale);
i++;
}
}
int vert = 0;
int tris = 0;
triangles = new int[xSize * zSize * 6];
for (int z = 0; z < zSize; ++z)
{
for (int x = 0; x < xSize; x++)
{
triangles[tris + 0] = vert + 0;
triangles[tris + 1] = vert + xSize + 1;
triangles[tris + 2] = vert + 1;
triangles[tris + 3] = vert + 1;
triangles[tris + 4] = vert + xSize + 1;
triangles[tris + 5] = vert + xSize + 2;
vert++;
tris += 6;
}
vert++;
}
}
void UpdateMesh()
{
mesh.Clear();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.RecalculateNormals();
GetComponent<MeshCollider>().convex = false;
}
}
I’m just trying to find out how to generate the world on the hosts side, and not create multiple worlds.