🎮 محو و ظاهر کردن شیء با کلیک چپ و راست در یونیتی — آموزش + کد کامل

در این مقاله کوتاه یاد می‌گیریم چطور یک شیء (GameObject) در یونیتی را با کلیک چپ و کلیک راست موس، به صورت هموار محو (Fade Out) و ظاهر (Fade In) کنیم. این افکت با استفاده از تغییر آلفای متریال (یا کامپوننت SpriteRenderer/Renderer) و کوروتین انجام می‌شود.

اسکریپت FadeOnClick.cs

این اسکریپت را به GameObject مورد نظرتان اضافه کنید:

using UnityEngine;
using System.Collections;

public class FadeOnClick : MonoBehaviour
{
    [SerializeField] private float fadeDuration = 1f; // مدت زمان فید
    private Renderer objectRenderer;
    private Color originalColor;

    void Start()
    {
        // پیدا کردن کامپوننت رندرر
        objectRenderer = GetComponent<Renderer>();
        if (objectRenderer == null)
        {
            Debug.LogError("Renderer not found on this GameObject!");
            return;
        }

        // ذخیره رنگ اصلی برای بازگشت
        originalColor = objectRenderer.material.color;
    }

    void Update()
    {
        // کلیک چپ: محو کردن
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit) && hit.transform == transform)
            {
                StartCoroutine(FadeOut());
            }
        }

        // کلیک راست: ظاهر کردن
        if (Input.GetMouseButtonDown(1))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit) && hit.transform == transform)
            {
                StartCoroutine(FadeIn());
            }
        }
    }

    IEnumerator FadeOut()
    {
        Color currentColor = objectRenderer.material.color;
        float startAlpha = currentColor.a;
        float time = 0;

        while (time < fadeDuration)
        {
            time += Time.deltaTime;
            float alpha = Mathf.Lerp(startAlpha, 0f, time / fadeDuration);
            currentColor.a = alpha;
            objectRenderer.material.color = currentColor;
            yield return null;
        }

        currentColor.a = 0f;
        objectRenderer.material.color = currentColor;
    }

    IEnumerator FadeIn()
    {
        Color currentColor = objectRenderer.material.color;
        float startAlpha = currentColor.a;
        float time = 0;

        while (time < fadeDuration)
        {
            time += Time.deltaTime;
            float alpha = Mathf.Lerp(startAlpha, originalColor.a, time / fadeDuration);
            currentColor.a = alpha;
            objectRenderer.material.color = currentColor;
            yield return null;
        }

        currentColor.a = originalColor.a;
        objectRenderer.material.color = currentColor;
    }
}