How to create SpriteRenderer Color.Lerp?

Hello folks!

I want to create a SpriteRenderer smooth lerp color change, but i get the error: CS0120(10,35)&(14,35)

    using UnityEngine;
    using System.Collections;
    
    public class elementMaterialColorLerp : MonoBehaviour {
    	public Color A = Color.white;
    	public Color B = Color.red;
    	private float timer = 1f;
    
    	void Update(){
    		if(SpriteRenderer.color == A){
    			Color.Lerp(A, B, timer);
    		}
    		if(SpriteRenderer.color == B){
    			Color.Lerp(B, A, timer);
    		}
    	}
    }

thanks!

1 Answer

1

‘SpriteRenderer’ is the class. What you need is the instance of that class attached to this game object. You can get the instance of the class using GetComponent(). The rest of your code won’t work to do what I think you want here (lerping back and forth between two colors). Try this:

using UnityEngine;
using System.Collections;

public class ColorLerp : MonoBehaviour {
	public Color A = Color.magenta;
	public Color B = Color.blue;
	public float speed = 1.0f;

	SpriteRenderer spriteRenderer;

	void Start() {
		spriteRenderer = GetComponent<SpriteRenderer>();
	}
	
	void Update(){
			spriteRenderer.color = Color.Lerp(A, B, Mathf.PingPong(Time.time * speed, 1.0f));
	}
}

I made such a stupid mistake xD thank you, it works!

Is it a good way to do it in memory point of view as you are using Update function and the lerp will be called in every frame.