• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by pioiwan · Dec 16, 2013 at 10:06 PM · editorprefabaudioclip

Generating a prefab from Audio Clip via script

I'm importing some wavs and mp3 to Unity and for each one I want to create a prefab consisting of a Game Object with Audio Source component filled with proper Audio Clip. It's a boring task that should be automated and I'm looking at editor scripts to do it right.

1)I've made an OnPostprocessAudio script that does that quite well, but in this approach I can only create a properly named prefab and then I have to manualy drag the clip into it. Other problem is that the prefab is generated with each reimport (which means additional dragging each time!), which is not an elegant solution.

2)I've tried extending the Audio Clip Inspector, but after selecting the asset in Project Window I can't actually click the button I created. The button appears not in the "Import Settings" section, but in the "Imported Object" section which is inactive. That would be an ideal solution - I select an audio asset and launch a script associated with it.

3)Adding a Top Menu item is probably a possibility, but I haven't tried it yet (it doensn't seem too elegant and usable).

What approach would you suggest, what's the right way to do it? I'm only learning editor scripting now and maybe don't see simpler ways to achieve this goal.

tl;dr: Scripted creation of a prefab from Audio Clip asset, how?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by Statement · Dec 17, 2013 at 12:30 AM

Did some basic testing to try catch any simple mistakes. It supports modifying the clip and repopulating existing prefabs.

Basically, you need to get a callback that is safe for you to use the audio clip. Unfortunately the `OnPostprocessAudio` was not ideal as the object is transient (or if not, I made some silly mistake). I was able to get it working by going through all imported assets at the end of the post processing step, in `OnPostprocessAllAssets`.

 using UnityEngine;
 using UnityEditor;
 using System.IO;
 
 public class AudioPrefabProcessor : AssetPostprocessor
 {
     public static void OnPostprocessAllAssets (
         string[] importedAssets,
         string[] deletedAssets,
         string[] movedAssets,
         string[] movedFromAssetPaths)
     {
         foreach (string path in importedAssets)
             BuildAudioPrefabs(path);
     }
 
     private static void BuildAudioPrefabs (string path)
     {
         AudioClip clip = LoadAsset<AudioClip>(path);
         if (clip)
         {
             string prefabPath = GetPrefabPath(path);
             GameObject oldPrefab = LoadAsset<GameObject>(prefabPath);
             if (oldPrefab)
             {
                 // Alternatively we could choose to do nothing.
                 // If you think about it, all you're doing is setting a ref.
                 // But in case you renamed a clip, perhaps you want to regen
                 // the actual prefab.
                 UpdateOldPrefab(clip, oldPrefab);
             }
             else
             {
                 CreateNewPrefab(clip, prefabPath);
             }
         }
     }
 
     private static void UpdateOldPrefab (AudioClip clip, GameObject oldPrefab)
     {
         AssetDatabase.StartAssetEditing();
         oldPrefab.GetComponent<AudioSource>().clip = clip;
         AssetDatabase.StopAssetEditing();
     }
 
     private static void CreateNewPrefab (AudioClip clip, string prefabPath)
     {
         GameObject temp = new GameObject();
         temp.AddComponent<AudioSource>().clip = clip;
         PrefabUtility.CreatePrefab(prefabPath, temp);
         Object.DestroyImmediate(temp, false);
     }
 
     private static T LoadAsset<T> (string path) where T : Object
     {
         return AssetDatabase.LoadAssetAtPath(path, typeof (T)) as T;
     }
 
     private static string GetPrefabPath (string path)
     {
         string clipName = Path.GetFileNameWithoutExtension(path);
         return "Assets/" + clipName + ".prefab";
     }
 }


Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Statement · Dec 17, 2013 at 12:39 AM 1
Share

If you decide to change how to build the game object (perhaps you add more components in the future), consider changing UpdateOldPrefab to include your creation steps as in CreateNewPrefab, but do a call to `PrefabUtility.ReplacePrefab` ins$$anonymous$$d of `PrefabUtility.CreatePrefab`! (I think it works on assets, but I may be wrong. Try before rolling out on your project :))

avatar image pioiwan · Dec 17, 2013 at 10:54 AM 1
Share

Ha, that's great! Asset generated in onPostprocessAudio is indeed temporary and cannot be used, but your workaround with onPostprocessAllAssets actually does the job. Thanks!

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

18 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How can I mimic the "Apply" button in editor script? 1 Answer

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

How do I reference a prefab after I create it in editor? 3 Answers

Show and Hide a prefab or GameObject 10 Answers

How Mark Prefab Dirty? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges