Skip to content

Instantly share code, notes, and snippets.

@bcatcho
Last active August 29, 2015 14:17
Show Gist options
  • Save bcatcho/3dd6b0c8071634344073 to your computer and use it in GitHub Desktop.
Save bcatcho/3dd6b0c8071634344073 to your computer and use it in GitHub Desktop.
Unity 5 Behaviour to help with applying texture atlases to a model without changing UVs
// The MIT License (MIT) - https://gist.github.com/bcatcho/1926794b7fd6491159e7
// Copyright (c) 2015 Brandon Catcho
using UnityEngine;
using System.Collections.Generic;
namespace CatchCo
{
[RequireComponent(typeof(MeshRenderer))]
public class UniformTextureAtlasMeshRenderHelper : MonoBehaviour
{
public Vector2 AtlasOffset;
public Vector2 Size = Vector2.one;
public bool RandomizeOnSpawn;
public OffsetRange RandomOffsetRange;
public List<string> TextureNames; // if there are multiple textures in a shader, list them all here
private Material _customMat;
private void OnDidEnterGameplay ()
{
if (RandomizeOnSpawn)
{
AtlasOffset.x = Random.Range (RandomOffsetRange.XMin, RandomOffsetRange.XMax);
AtlasOffset.y = Random.Range (RandomOffsetRange.YMin, RandomOffsetRange.YMax);
}
}
private void Start ()
{
var meshRenderer = GetComponent<MeshRenderer>();
_customMat = meshRenderer.material;
UpdateMaterials ();
}
private void UpdateMaterials ()
{
var scale = new Vector2 (1f / Size.x, 1f / Size.y);
var offset = AtlasOffset.ScaleXY (scale);
foreach (var tex in TextureNames)
{
_customMat.SetTextureOffset (tex, offset);
_customMat.SetTextureScale (tex, scale);
}
}
[System.Serializable]
public struct OffsetRange
{
public int XMin;
public int XMax;
public int YMin;
public int YMax;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment