Skip to content

Instantly share code, notes, and snippets.

@badjano
Created October 30, 2018 03:49
Show Gist options
  • Save badjano/d7514ecfcfb05d1cf28b1e18775aaa0d to your computer and use it in GitHub Desktop.
Save badjano/d7514ecfcfb05d1cf28b1e18775aaa0d to your computer and use it in GitHub Desktop.
Unity threading example
using System;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
public class TerrainChunk : MonoBehaviour
{
private MeshFilter _meshFilter;
private MeshCollider _meshColllider;
private bool _building;
private Mesh _mesh;
private bool _newMesh;
[SerializeField, Range(1, 50)] private int _iterations = 50;
private Vector3[] _vertices;
private Vector3[] _normals;
private Color[] _colors;
private Vector2[] _uv;
private int[] _triangles;
private Thread _thread;
private bool _requestNewMesh;
// Use this for initialization
void Start()
{
_meshFilter = gameObject.GetComponent<MeshFilter>();
_meshColllider = gameObject.GetComponent<MeshCollider>();
}
private void Update()
{
CheckMesh();
}
public void UpdateMesh()
{
_requestNewMesh = true;
}
private void CheckMesh()
{
if (_newMesh)
{
_queue.Dequeue();
_mesh = new Mesh();
_mesh.vertices = _vertices;
_mesh.colors = _colors;
_mesh.uv = _uv;
_mesh.triangles = _triangles;
_mesh.normals = _normals;
_meshFilter.sharedMesh = _mesh;
_meshColllider.sharedMesh = _mesh;
if (OnBuild != null)
{
OnBuild.Invoke();
}
_newMesh = false;
}
if (_requestNewMesh)
{
if (!_building)
{
_newMesh = false;
_building = true;
_requestNewMesh = false;
_thread = new Thread(BuildChunk);
_thread.Start();
}
}
}
public void BuildChunk()
{
if (_iterations > 0)
{
int rows = _iterations * 2 + 1;
int numVerts = (int) Mathf.Pow(rows, 2);
int numTris = numVerts * 2;
_vertices = new Vector3[numVerts];
_normals = new Vector3[numVerts];
_colors = new Color[numVerts];
_uv = new Vector2[numVerts];
// HEAVY LIFTING
}
_newMesh = true;
_building = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment