Updating texture pixels?
Background: I'm trying to implement a marshmallow-toasting mechanic, in which I have a texture for the marshmallow's skin that I update based on (currently) proximity to a heat source. (Currently I'm using the Player as a proxy for the heat source for ease of testing.) I could just do that in the fragment shader, except if I do it that way, the toasting won't "stick" (i.e. it will go away when the player moves away from the heat source). Hence why I need to modify the texture itself in memory.
Actual question: I'm trying to update the pixels of a texture based on the player's distance from the object using that texture; what am I doing wrong here? Why doesn't the texture change when I get close? It changes to red seemingly in the first frame, but then never changes.
public class ProximityToast : MonoBehaviour
{
Texture2D texture;
void Start()
{
this.texture = new Texture2D(256, 256);
GetComponent<Renderer>().material.mainTexture = this.texture;
for (int y = 0; y < this.texture.height; y++)
{
for (int x = 0; x < this.texture.width; x++)
{
this.texture.SetPixel(x, y, Color.white);
}
}
this.texture.Apply();
}
void Update()
{
Vector3 marshmallowPos = gameObject.transform.position;
GameObject player = GameObject.FindGameObjectWithTag("Player");
Vector3 playerPos = player.transform.position;
float roughPos = (playerPos - marshmallowPos).magnitude;
float toastVal = Mathf.Max(0, 255f - roughPos * 50);
GetComponent<Renderer>().material.mainTexture = this.texture;
Color color = new Color(toastVal, 0, 0);
for (int y = 0; y < this.texture.height; y++)
{
for (int x = 0; x < this.texture.width; x++)
{
this.texture.SetPixel(x, y, color);
}
}
this.texture.Apply();
}
}
Your answer
Follow this Question
Related Questions
2D advanced texture blurriness 1 Answer
Importing tiff file as www.texture 1 Answer
1024x1024 Texture2D Takes up over 8MB of memory 0 Answers
how to properly set a texture? 0 Answers