Как использовать сопрограмму, чтобы создать эффект плавного переключения материалов?C#

Место общения программистов C#
Ответить
Anonymous
 Как использовать сопрограмму, чтобы создать эффект плавного переключения материалов?

Сообщение Anonymous »

теперь, когда я нажимаю пробел, он переключается между материалами, но сразу.
я хочу сделать так, чтобы при нажатии пробела запускалась сопрограмма, и она плавно начала медленно менять материалы, поэтому я часть цвета изображения изменится на серый материал медленно, а не сразу.
Я добавил метод LerpColor, но не знаю, где и как его использовать, чтобы получить эффект.
Я добавил метод LerpColor, но не знаю, где и как его использовать, чтобы получить эффект.
п>
using System.Collections;
using UnityEngine;
using UnityEngine.UI; // Make sure to include the UI namespace

public class ImageColorSwitching : MonoBehaviour
{
public Material grayScaleMaterial; // The grayscale material
private Material originalMaterial; // The original material of the Image component
private Image imageComponent; // Reference to the Image component
private Sprite originalImage;

void Start()
{
// Get the Image component attached to this GameObject
imageComponent = GetComponent();
originalImage = GetComponent().sprite;

// Store the original material of the Image component
originalMaterial = imageComponent.material;
}

void Update()
{
// Switch materials when the space key is pressed
if (Input.GetKeyDown(KeyCode.Space))
{
SwitchMaterials();
}
}

private void SwitchMaterials()
{
if (imageComponent.material == originalMaterial)
{
// Switch to grayscale material and clear the Source Image to avoid conflict
imageComponent.material = grayScaleMaterial;
imageComponent.sprite = null; // Clear the Source Image field
}
else
{
// Switch back to the original material and restore the Source Image
imageComponent.material = originalMaterial;
imageComponent.sprite = originalImage; // You can reassign the original sprite here if needed
}
}

IEnumerator LerpColor(MeshRenderer mesh, Color fromColor, Color toColor, float duration, int repetitions)
{
for (int i = 0; i < repetitions; ++i)
{
float counter = 0;

while (counter < duration)
{
counter += Time.deltaTime;

float colorTime = counter / duration;
Debug.Log(colorTime);

//Change color
mesh.material.color = Color.Lerp(fromColor, toColor, counter / duration);
//Wait for a frame
yield return null;
}
Color tmp = fromColor;
fromColor = toColor;
toColor = tmp;
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/791 ... hing-smoot
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»