10
7

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】AudioClipをクリックした瞬間にプレビュー再生させるエディター拡張

Last updated at Posted at 2016-05-31

※この記事のUnityのバージョンは5.3.5f1です

#1. はじめに
通常、UnityEditor上で音アセットをクリックしても再生されることはありません.

Unity (64bit) - DemoScene.unity - TestPolygonGame - Web Player DX11 2016-05-31 10.26.03.png

これをクリックしただけでプレビュー再生されるようにするエディター拡張を作ってみました.

#2. ソースコード

AudioPreview.cs
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;

[InitializeOnLoad]
public class AudioPreview
{
  const string AudioGameObjectName = "[AudioSourcePreview]";

  static Object previousObject = null;
  static AudioSource audioSource;

  // 音のプレビュー再生に使うオブジェクト
  static GameObject audioGameObject;

  [DidReloadScripts]
  static AudioPreview()
  {
    EditorApplication.projectWindowItemOnGUI += (string guid, Rect selectionRect) =>
    {
      if (Selection.activeObject != null && Selection.activeObject != previousObject)
      {
        // プレビュー再生用のオブジェクト作成
        CreateObject();

        Debug.Log("Play : " + Selection.activeObject.name);

        AudioClip clip = Selection.activeObject as AudioClip;
        if (clip != null)
        {
          // ProjectビューでAudioClipを選択したら再生
          audioSource.clip = clip;
          audioSource.Play();
        }
        else
        {
          // AudioClip以外を選択したらプレビュー停止
          GameObject.DestroyImmediate(audioGameObject);
        }
      }

      if (Selection.activeObject == null)
      {
        // 選択が外れたらプレビュー停止
        GameObject.DestroyImmediate(audioGameObject);
      }

      previousObject = Selection.activeObject;
    };
  }

  /// <summary>
  /// プレビュー再生用のオブジェクト作成
  /// </summary>
  private static void CreateObject()
  {
    audioGameObject = GameObject.Find(AudioGameObjectName);
    if (audioGameObject == null)
    {
      audioGameObject = new GameObject(AudioGameObjectName);
    }

    audioSource = audioGameObject.GetComponent<AudioSource>();
    if (audioSource == null)
    {
      audioSource = audioGameObject.AddComponent<AudioSource>();
    }

    audioSource.playOnAwake = false;
  }

}
#endif

#3. 結果
クリックすると音が出るようになります.

10
7
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
10
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?