Leaking Materials When Drawing Text Gizmo

Avatar
  • updated

I am using Shapes to draw a text gizmo into my scene to make designing levels easier. I only want this Gizmo in the editor. I created a CustomLabel component which draws some text but it emits an error when doing so.

The error:

Instantiating material due to calling renderer.material during edit mode. This will leak materials into the scene. You most likely want to 
use renderer.sharedMaterial instead 

UnityEngine.Renderer:get_material ()
TMPro.TextMeshPro:SetOutlineColor (UnityEngine.Color32) (at ./Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMPro_Private.cs:867)
TMPro.TMP_Text:set_outlineColor (UnityEngine.Color32) (at ./Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_Text.cs:424)
Project.CustomLabel:OnDrawGizmos () (at Assets/_Project/_Code/_Scripts/Action/CustomLabel.cs:31)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)

The script:

using System;
using Shapes;
using TMPro;
using UnityEngine;

namespace Project
{
public class CustomLabel : MonoBehaviour
{
[SerializeField]
private string _text = "";

[NonSerialized]
private TextElement? _textElement;

private void OnDrawGizmos()
{
if (_textElement == null)
{
_textElement = new TextElement();
TextMeshPro? tmp = _textElement.Tmp;

if (tmp == null)
{
return;
}

tmp.color = Color.white;
tmp.outlineColor = Color.black;
tmp.outlineWidth = 5;
}

Vector3 position = transform.position;

Draw.Text(_textElement, position, _text);
}
}
}
Reporting a bug? please specify Unity version:
2022.3.19f1
Reporting a bug? please specify Shapes version:
4.3.1
Reporting a bug? please specify Render Pipeline:
URP
Avatar
Kevin Serra

Fixed it, it was an issue with TextMeshPro not Shapes.


Here's how I fixed it:

tmp.color = Color.white;
tmp.fontSharedMaterial.SetColor(ShaderUtilities.ID_OutlineColor, Color.black);
tmp.fontSharedMaterial.SetFloat(ShaderUtilities.ID_OutlineWidth, 0.1f);
tmp.ForceMeshUpdate();