7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Unity】CanvasGroupを通じてUIの表示/非表示を切り替える

Last updated at Posted at 2018-02-09

◆使い方
①CanvasGroupと一緒にアタッチ
②任意のタイミングでSetActive(),SetInactive()を呼ぶ

CanvasGroupCtr.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CanvasGroupCtr : MonoBehaviour
{
	private CanvasGroup thisCanvasGroup;

	private CanvasGroup canvasGroup {
		get {
			if (thisCanvasGroup == null) {
				thisCanvasGroup = GetComponent<CanvasGroup> ();
			}
			return thisCanvasGroup;
		}
	}

	//表示する
	public void ShowWithFade (bool isFade = true, float FadeSpeed = 5f)
	{
		//FadeInさせるかどうか
		if (isFade) {
			StartCoroutine (TimeForFadeIn (FadeSpeed));
		} else {
			canvasGroup.alpha = 1;
		}
		canvasGroup.interactable = true;
		canvasGroup.blocksRaycasts = true;
	}

	//非表示にする
	public void HideWithFade (bool isFade = true, float FadeSpeed = 5f)
	{
		//FadeOutさせるかどうか
		if (isFade) {
			StartCoroutine (TimeForFadeOut (FadeSpeed));
		} else {
			canvasGroup.alpha = 0;
		}
		canvasGroup.interactable = false;
		canvasGroup.blocksRaycasts = false;
	}

	//FadeIn用コルーチン
	IEnumerator TimeForFadeIn (float FadeSpeed)
	{
		while (canvasGroup.alpha < 1) {
			canvasGroup.alpha += Time.deltaTime * FadeSpeed;
			yield return null;
		}
		yield return null;
	}

	//FadeOut用コルーチン
	IEnumerator TimeForFadeOut (float FadeSpeed)
	{
		while (canvasGroup.alpha > 0) {
			canvasGroup.alpha -= Time.deltaTime * FadeSpeed;
			yield return null;
		}
		yield return null;
	}
}

7
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?