Hello there,
I'm trying to assign a material to UI2DSprite on the run and update the material properties. Weird things is, it's only working if I change the parent of objects so I believe when I change the parent it somehow updates something about how widget is drawing and starts to use new material.
I couldn't do it manually, tried MarkAsChanged, MarkParentChanged and all other stuff. Only way to get it working now is when I change the parent of the object. Am I doing something wrong here?
You can find the code below.
using UnityEngine;
using DG.Tweening;
public class MaterialBlinkColor
{
public bool ShouldContinue { get; set; }
Tweener _curTween;
Material _material;
Material _defaultMaterial;
UI2DSprite _sprite;
string _property;
public MaterialBlinkColor(UI2DSprite sprite, Material material)
{
ShouldContinue = true;
_defaultMaterial
= new Material
(material
); _sprite = sprite;
_material
= new Material
(material
); _sprite.material = _material;
BlinkSmoothly
("_AddColor", _material
.GetColor("_AddColor"),
new Color
(0
.85f, 0
.85f, 0
.85f,
0), 1f
); //_sprite.MarkAsChanged();
//_sprite.SetDirty();
//NGUITools.MarkParentAsChanged(_sprite.transform.parent.gameObject);
}
public void BlinkSmoothly(string property, Color startColor, Color endColor, float totalDuration, bool runOnce = false)
{
//_sprite.GetComponent<Rigidbody2D>().isKinematic = true;
//_sprite.transform.parent = _sprite.root.transform;
_sprite.onRender = OnRender;
_property = property;
if (ShouldContinue)
{
_curTween = _material.DOColor(endColor, _property, totalDuration / 2)
.OnComplete(new TweenCallback
(() => BlinkSmoothly
(_property, endColor, startColor, totalDuration, runOnce
))) .SetEase(Ease.InOutCubic);
ShouldContinue &= !runOnce;
}
}
void OnRender(Material mat)
{
if (!ShouldContinue)
{
_sprite.onRender = null;
_material = _defaultMaterial;
}
mat.SetColor(_property, _material.GetColor(_property));
}
}
Thanks,
Burkay