P
P
Pavel Arutyunov2022-01-19 19:40:58
Unity
Pavel Arutyunov, 2022-01-19 19:40:58

How to change texture transparency in Unity2D?

A question arose during the development of the game on Unity2D. It is necessary that when the player enters the building, the texture becomes transparent, and when he leaves it, it takes on an opaque state. I would like everything to work through the OnTriggerEnter2D function.

Please help, thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
B0w1, 2022-01-19
@alex22122

You need to get the value of the color property from the SpriteRenderer component , change the a field of the received object, and write the color back to the color property. C# script example: using UnityEngine; public class SpriteAlphaChanger : MonoBehaviour { public SpriteRenderer _sprite = null; // Here in the inspector you need to drag the sprite (building) you need. public floatSpeed ​​= 1f; // Sets the color change rate in units per second. void Update () { // Get the color of the sprite. varcolor = _sprite.color; } void OnTriggerEnter2D(Collider2D col) {
// Decrease the alpha value at the given rate. Don't forget Time.deltaTime.
color.a -= Speed ​​* Time.deltaTime;
else
// Increase the alpha value at the given rate. Don't forget Time.deltaTime.
color.a += Speed ​​* Time.deltaTime;
// Don't let the value go out of bounds, for the color it's (0, 1).
color.a = Mathf.Clamp(color.a, 0, 1);
// Set the sprite to a new color.
_sprite.color = color;
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question