Skip to content

Instantly share code, notes, and snippets.

@inertiave
Created February 26, 2020 09:01
Show Gist options
  • Save inertiave/f8e0c105c6884121e484ba7b740cdf94 to your computer and use it in GitHub Desktop.
Save inertiave/f8e0c105c6884121e484ba7b740cdf94 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Renderer))]
public class MaterialHandler : MonoBehaviour
{
static readonly Dictionary<string, Material> materialMap = new Dictionary<string, Material>();
Renderer targetRenderer;
public string materialPath = "Materials/pic";
public bool asInstanced = false;
Material GetSharedMaterial()
{
if (!materialMap.TryGetValue(materialPath, out Material material))
{
if (asInstanced)
{
material = new Material(Resources.Load<Material>(materialPath));
}
else
{
material = Resources.Load<Material>(materialPath);
}
materialMap[materialPath] = material;
}
return material;
}
void ApplySharedMaterial()
{
if (targetRenderer == null)
{
targetRenderer = GetComponent<Renderer>();
}
targetRenderer.sharedMaterial = GetSharedMaterial();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment