92 lines
2.1 KiB
C#
92 lines
2.1 KiB
C#
|
using System;
|
|||
|
using UnityEngine;
|
|||
|
using Object = UnityEngine.Object;
|
|||
|
|
|||
|
namespace BitGames.Terrain
|
|||
|
{
|
|||
|
[RequireComponent(typeof(MeshRenderer), typeof(MeshFilter))]
|
|||
|
[DisallowMultipleComponent]
|
|||
|
public class TerrainFloorRenderer : MonoBehaviour, ITerrainMaterialUser
|
|||
|
{
|
|||
|
public TerrainAsset Asset;
|
|||
|
|
|||
|
private MeshRenderer _renderer;
|
|||
|
private MeshFilter _meshFilter;
|
|||
|
private Material _instancedMaterial;
|
|||
|
|
|||
|
private void Awake()
|
|||
|
{
|
|||
|
LinkMaterial();
|
|||
|
ActivateAsset();
|
|||
|
UpdateMesh();
|
|||
|
}
|
|||
|
|
|||
|
private void UpdateMesh()
|
|||
|
{
|
|||
|
VerifyComponents();
|
|||
|
|
|||
|
transform.localScale = (Asset != null ? Asset.Size : 32) * RuntimeGlobals.TILE_SIZE * Vector3.one;
|
|||
|
transform.position = Vector3.zero;
|
|||
|
transform.rotation = Quaternion.Euler(90, 0, 0);
|
|||
|
GetComponent<MeshFilter>().sharedMesh = Resources.GetBuiltinResource<Mesh>("Quad.fbx");
|
|||
|
}
|
|||
|
|
|||
|
private void LinkMaterial()
|
|||
|
{
|
|||
|
VerifyComponents();
|
|||
|
|
|||
|
if (_instancedMaterial == null)
|
|||
|
{
|
|||
|
_instancedMaterial = RuntimeGlobals.RegisterMaterialUser(this);
|
|||
|
}
|
|||
|
|
|||
|
_renderer.sharedMaterial = _instancedMaterial;
|
|||
|
}
|
|||
|
|
|||
|
private void UnlinkMaterial()
|
|||
|
{
|
|||
|
RuntimeGlobals.RemoveMaterialUser(this);
|
|||
|
}
|
|||
|
|
|||
|
private void ActivateAsset()
|
|||
|
{
|
|||
|
if(Asset != null)
|
|||
|
RuntimeGlobals.ActivateAsset(Asset);
|
|||
|
}
|
|||
|
|
|||
|
#if UNITY_EDITOR
|
|||
|
internal void OnValidate()
|
|||
|
{
|
|||
|
UpdateMesh();
|
|||
|
LinkMaterial();
|
|||
|
ActivateAsset();
|
|||
|
}
|
|||
|
|
|||
|
internal void HideMeshFilterRenderer()
|
|||
|
{
|
|||
|
VerifyComponents();
|
|||
|
const HideFlags flags = HideFlags.HideInInspector; // Hide mesh renderer and filter
|
|||
|
_renderer.hideFlags = flags;
|
|||
|
_meshFilter.hideFlags = flags;
|
|||
|
}
|
|||
|
#endif
|
|||
|
|
|||
|
private void VerifyComponents()
|
|||
|
{
|
|||
|
EnsureComponent(ref _renderer);
|
|||
|
EnsureComponent(ref _meshFilter);
|
|||
|
}
|
|||
|
|
|||
|
private void EnsureComponent<T>(ref T component) where T : Component
|
|||
|
{
|
|||
|
if(component == null)
|
|||
|
component = gameObject.TryGetComponent(out T found) ? found : gameObject.AddComponent<T>();
|
|||
|
}
|
|||
|
|
|||
|
private void OnDestroy()
|
|||
|
{
|
|||
|
UnlinkMaterial();
|
|||
|
}
|
|||
|
}
|
|||
|
}
|