2013年7月16日 星期二

Custom Assets

Unity Custom Assets


Excerpt:

 Create simple serializable data container for each individual dialogue speech element as so:
 [System.Serializable]  
 public class DialogueElement  
 {  
   public enum Characters{ David, Megan};  
   public enum AvatarPos{ left, right};  
   public Characters Character;  
   public AvatarPos CharacterPosition;  
   public Texture2D CharacterPic;  
   public string DialogueText;  
   public GUIStyle DialogueTextStyle;  
   public float TextPlayBackSpeed;  
   public AudioClip PlayBackSoundFile;  
 }  

The ScriptableObject class will give us the magic of being able to turn our dialogue class into our own custom asset files.
 public class Dialogue: ScriptableObject  
 {  
   public List<DialogueElement> DialogItems;  
 }  

Create CustomAssetUtility.cs: 


 using UnityEngine;  
 using UnityEditor;  
 using System.IO;  
   
 public static class CustomAssetUtility  
 {  
   public static void CreateAsset<T> () where T : ScriptableObject  
   {  
     T asset = ScriptableObject.CreateInstance<T> ();  
   
     string path = AssetDatabase.GetAssetPath (Selection.activeObject);  
     if (path == "")  
     {  
       path = "Assets";  
     }  
     else if (Path.GetExtension (path) != "")  
     {  
       path = path.Replace (Path.GetFileName (AssetDatabase.GetAssetPath (Selection.activeObject)), "");  
     }  
   
     string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath (path + "/New " + typeof(T).ToString() + ".asset");  
   
     AssetDatabase.CreateAsset (asset, assetPathAndName);  
   
     AssetDatabase.SaveAssets ();  
     EditorUtility.FocusProjectWindow ();  
     Selection.activeObject = asset;  
   }  
 }  

Once you have that installed in your project you can turn that dialog class or any of your classes that inherit from ScriptableObject into a custom assets super easily with just a couple lines.
Just make a new class/file called DialogueAsset.cs and make sure it’s inside an Editor folder. Then inside that class create a menu item for your new asset that just calls CreateAsset from the downloaded utility class like so:

 using UnityEngine;  
 using UnityEditor;  
 using System;  
   
 public class DialogueAsest  
 {  
   [MenuItem("Assets/Create/Dialogue")]  
   public static void CreateAsset ()  
   {  
     ScriptableObjectUtility.CreateAsset<Dialogue> ();  
   }  
 }  

沒有留言:

張貼留言