这里用到反射,会用到AudioUtil,源码调用如下:

https://github.com/jamesjlinden/unity-decompiled/blob/master/UnityEditor/UnityEditor/AudioUtil.cs 

思路如下:

http://baba-s.hatenablog.com/entry/2017/12/04/173920

这里放一下拓展类:

 1 #if UNITY_EDITOR
 2 using System;
 3 using UnityEditor;
 4 #endif
 5 using System.Reflection;
 6 using UnityEngine;
 7
 8 //生成配置文件
 9 [CreateAssetMenu(fileName = "AudioClipPlayWithOutRunning", menuName = "AudioClipPlayWithOutRunning", order = 0)]
10 [Serializable]
11 public class AudioClipPlayWithOutRunning : ScriptableObject
12 {
13     //存储数据
14     [SerializeField] private AudioClip soundData;
15
16     //自动绑定脚本
17     [CustomEditor(typeof(AudioClipPlayWithOutRunning))]
18     class AudioClipPlayWithOutRunningEditor : Editor
19     {
20         public override void OnInspectorGUI()
21         {
22             var tempData = target as AudioClipPlayWithOutRunning;
23             tempData.soundData =
24                 (AudioClip) EditorGUILayout.ObjectField("AudioClip", tempData.soundData, typeof(AudioClip));
25             if (GUILayout.Button("PlayClip"))
26             {
27                 PlayClip(tempData.soundData);
28             }
29
30             if (GUILayout.Button("StopClip"))
31             {
32                 StopClip(tempData.soundData);
33             }
34         }
35
36         void PlayClip(AudioClip clip)
37         {
38             if (clip == null)
39             {
40                 Debug.LogError("SampleContainer PlayClip clip is null");
41                 return;
42             }
43
44             var unityEditorAssembly = typeof(AudioImporter).Assembly;
45             //获取dll
46             var audioUtil = unityEditorAssembly.GetType("UnityEditor.AudioUtil");
47             //获取反射方法
48             var method = audioUtil.GetMethod
49             (
50                 "PlayClip",
51                 BindingFlags.Default | BindingFlags.Static | BindingFlags.Public,
52                 null,
53                 new[] {typeof(AudioClip)},
54                 null
55             );
56             //调用
57             method.Invoke(null, new[] {clip});
58         }
59
60         void StopClip(AudioClip clip)
61         {
62             if (clip == null)
63             {
64                 Debug.LogError("SampleContainer StopClip clip is null");
65                 return;
66             }
67
68             var unityEditorAssembly = typeof(AudioImporter).Assembly;
69             var audioUtil = unityEditorAssembly.GetType("UnityEditor.AudioUtil");
70             var method = audioUtil.GetMethod
71             (
72                 "StopClip",
73                 BindingFlags.Default | BindingFlags.Static | BindingFlags.Public,
74                 null,
75                 new[] {typeof(AudioClip)},
76                 null
77             );
78             method.Invoke(null, new[] {clip});
79         }
80     }
81 }
AudioClipPlayWithOutRunning

这个时候在Unity中点击Asset -> AudioClipPlayWithOutRunning 生成该配置文件.

将音效资源放入进去即可.. ..

这样

12-22 22:53