LoadAssetAtPath









How do I use Load Asset At Path
Below are practical examples compiled from projects for learning and reference purposes

Featured Snippets


File name: PhotonEditor.cs Copy
215     static PhotonEditor()
216     {
217         EditorApplication.projectWindowChanged += EditorUpdate;
218         EditorApplication.hierarchyWindowChanged += EditorUpdate;
219         EditorApplication.playmodeStateChanged += PlaymodeStateChanged;
220         EditorApplication.update += OnUpdate;
221
222         WizardIcon = AssetDatabase.LoadAssetAtPath("Assets/Photon Unity Networking/photoncloud-icon.png", typeof(Texture2D)) as Texture2D;
223
224         // to be used in toolbar, the enum needs conversion to string[] being done here, once.
225         Array enumValues = Enum.GetValues(typeof(CloudRegionCode));
226         CloudServerRegionNames = new string[enumValues.Length];
227         for (int i = 0; i < CloudServerRegionNames.Length; i++)
228         {
229             CloudServerRegionNames[i] = enumValues.GetValue(i).ToString();
230             if (CloudServerRegionNames[i].Equals("none"))
231             {
232                 CloudServerRegionNames[i] = PhotonEditor.CurrentLang.BestRegionLabel;
233             }
234         }
235
236         // detect optional packages
237         PhotonEditor.CheckPunPlus();
238
239     }
File name: PhotonGUI.cs Copy
139     {
140         get
141         {
142             if( m_HelpIcon == null )
143             {
144                 m_HelpIcon = AssetDatabase.LoadAssetAtPath( "Assets/Photon Unity Networking/Editor/PhotonNetwork/help.png", typeof( Texture2D ) ) as Texture2D;
145             }
146
147             return m_HelpIcon;
148         }
149     }
File name: PunSceneSettings.cs Copy
50     {
51         get
52         {
53             if (instanceField != null)
54             {
55                 return instanceField;
56             }
57
58             instanceField = (PunSceneSettings)AssetDatabase.LoadAssetAtPath(PunSceneSettingsCsPath, typeof(PunSceneSettings));
59             if (instanceField == null)
60             {
61                 instanceField = ScriptableObject.CreateInstance();
62                 AssetDatabase.CreateAsset(instanceField, PunSceneSettingsCsPath);
63             }
64
65             return instanceField;
66         }
67     }
File name: ScmlPostProcessor.cs Copy
66         static void ImportScml(string assetPath)
67         {
68             string folderPath = Path.GetDirectoryName(assetPath);
69
70             //Load the SCML as XML
71             var doc = new XmlDocument();
72             doc.Load(assetPath);
73
74             //Parse the SCML file
75             var scml = new Spriter.ScmlObject(doc);
76
77             //TODO: Verify that all files/folders exist
78             var pb = new PrefabBuilder();
79             foreach (var entity in scml.Entities)
80             {
81                 //TODO: Settings file to customize prefab location
82                 var prefabPath = Path.Combine(folderPath, entity.Name + ".prefab");
83
84                 //Change to forward slash for asset database friendliness
85                 prefabPath = prefabPath.Replace('\\', '/');
86
87                 //Either instantiate the existing prefab or create a new one
88                 GameObject go;
89                 var prefabGo = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));
90                 if (prefabGo == null)
91                 {
92                     go = new GameObject();
93                     prefabGo = PrefabUtility.CreatePrefab(prefabPath, go, ReplacePrefabOptions.ConnectToPrefab);
94                 }
95                 else
96                 {
97                     go = GameObject.Instantiate(prefabGo) as GameObject;
98
99                     var oldAnimator = go.GetComponent();
100                     if (oldAnimator) GameObject.DestroyImmediate(oldAnimator);
101                 }
102
103                 //Build the prefab based on the supplied entity
104                 pb.MakePrefab(entity, go, folderPath);
105
106                 var animator = go.AddComponent();
107
108
109
110                 //Add animations to prefab object
111                 var anim = new AnimationBuilder();
112                 var allAnimClips = anim.BuildAnimationClips(go, entity, prefabPath);
113                 AssetDatabase.SaveAssets();
114
115                 var animatorControllerPath = Path.ChangeExtension(prefabPath, "controller");
116                 UnityEditor.Animations.AnimatorController oldController = (UnityEditor.Animations.AnimatorController)AssetDatabase.LoadAssetAtPath(animatorControllerPath, typeof (UnityEditor.Animations.AnimatorController));
117                 UnityEditor.Animations.AnimatorController controller = oldController;
118
119                 if (!oldController)
120                 {
121                     controller = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(animatorControllerPath);
122                     foreach (var animationClip in allAnimClips)
123                     {
124                         if (animationClip)
125                         {
126                             //UnityEditor.Animations.AnimatorController.AddAnimationClipToController(controller, animationClip);
127                         }
128                     }
129                 }
130                 UnityEditor.Animations.AnimatorController.SetAnimatorController(animator, controller);
131                 go.SetActive(true);
132                 //Update the prefab
133                 PrefabUtility.ReplacePrefab(go, prefabGo, ReplacePrefabOptions.ConnectToPrefab);
134
135                 //Add a generic avatar - because why not?
136                 //TODO: May need to eventually break this into a separate class
137                 // ie: if we want to look for a root motion node by naming convention
138                 //var avatar = AvatarBuilder.BuildGenericAvatar(go, "");
139                 //avatar.name = go.name;
140                 //AssetDatabase.AddObjectToAsset(avatar, prefabPath);
141
142                 GameObject.DestroyImmediate(go);
143
144                 AssetDatabase.SaveAssets();
145             }
146         }
File name: AssetUtils.cs Copy
35         public static Sprite GetSpriteAtPath(string filePath, string spriteFolder)
36         {
37             Sprite sprite = null;
38
39             if (string.IsNullOrEmpty(spriteFolder))
40             {
41                 var assetPath = AssetDatabase.GetAllAssetPaths().Where(path => path.EndsWith(filePath)).FirstOrDefault();
42                 if (!string.IsNullOrEmpty(assetPath))
43                 {
44                     sprite = (Sprite)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Sprite));
45                 }
46             }
47             else
48             {
49                 var assetPath = System.IO.Path.Combine(spriteFolder, filePath);
50                 sprite = (Sprite)AssetDatabase.LoadAssetAtPath(assetPath, typeof(Sprite));
51             }
52             return sprite;
53         }
File name: ImportTiled2Unity.Material.cs Copy
19         public Material FixMaterialForMeshRenderer(string objName, Renderer renderer)
20         {
21             string xmlPath = ImportUtils.GetXmlPath(objName);
22
23             XDocument xml = XDocument.Load(xmlPath);
24
25             // The mesh to match
26             string meshName = renderer.name;
27
28             // The mesh name may be decorated by Unity
29             string pattern = @"_MeshPart[\d]$";
30             Regex regex = new Regex(pattern);
31             meshName = regex.Replace(meshName, "");
32
33             var assignMaterials = xml.Root.Elements("AssignMaterial");
34
35             // Find an assignment that matches the mesh renderer
36             XElement match = assignMaterials.FirstOrDefault(el => el.Attribute("mesh").Value == meshName);
37
38             if (match == null)
39             {
40                 // The names of our meshes in the AssignMaterials elements may be wrong
41                 // This happened before when Unity replaced whitespace with underscore in our named meshes
42                 // That case is handled now, but there may be others
43                 StringBuilder builder = new StringBuilder();
44                 builder.AppendFormat("Could not find mesh named '{0}' for material matching\n", renderer.name);
45                 string choices = String.Join("\n ", assignMaterials.Select(m => m.Attribute("mesh").Value).ToArray());
46                 builder.AppendFormat("Choices are:\n {0}", choices);
47
48                 Debug.LogError(builder.ToString());
49                 return null;
50             }
51
52             string materialName = match.Attribute("material").Value;
53             string materialPath = ImportUtils.GetMaterialPath(materialName);
54
55             // Assign the material
56             renderer.sharedMaterial = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
57
58             // Set the sorting layer for the mesh
59             string sortingLayer = match.Attribute("sortingLayerName").Value;
60             if (!String.IsNullOrEmpty(sortingLayer) && !SortingLayerExposedEditor.GetSortingLayerNames().Contains(sortingLayer))
61             {
62                 Debug.LogError(string.Format("Sorting Layer \"{0}\" does not exist. Check your Project Settings -> Tags and Layers", sortingLayer));
63                 renderer.sortingLayerName = "Default";
64             }
65             else
66             {
67                 renderer.sortingLayerName = sortingLayer;
68             }
69
70             // Set the sorting order
71             renderer.sortingOrder = ImportUtils.GetAttributeAsInt(match, "sortingOrder");
72
73             // Do we have an alpha color key?
74             string htmlColor = ImportUtils.GetAttributeAsString(match, "alphaColorKey", "");
75             if (!String.IsNullOrEmpty(htmlColor))
76             {
77                 // Take for granted color is in the form '#RRGGBB'
78                 byte r = byte.Parse(htmlColor.Substring(1, 2), System.Globalization.NumberStyles.HexNumber);
79                 byte g = byte.Parse(htmlColor.Substring(3, 2), System.Globalization.NumberStyles.HexNumber);
80                 byte b = byte.Parse(htmlColor.Substring(5, 2), System.Globalization.NumberStyles.HexNumber);
81                 Color color = new Color32(r, g, b, 255);
82                 renderer.sharedMaterial.SetColor("_AlphaColorKey", color);
83             }
84
85             return renderer.sharedMaterial;
86         }
File name: ImportTiled2Unity.Mesh.cs Copy
27         private void CreatePrefab(XElement xmlPrefab, string objPath)
28         {
29             var customImporters = GetCustomImporterInstances();
30
31             // Part 1: Create the prefab
32             string prefabName = xmlPrefab.Attribute("name").Value;
33             float prefabScale = ImportUtils.GetAttributeAsFloat(xmlPrefab, "scale", 1.0f);
34             GameObject tempPrefab = new GameObject(prefabName);
35             HandleCustomProperties(tempPrefab, xmlPrefab, customImporters);
36
37             // Part 2: Build out the prefab
38             AddGameObjectsTo(tempPrefab, xmlPrefab, objPath, customImporters);
39
40             // Part 3: Allow for customization from other editor scripts to be made on the prefab
41             // (These are generally for game-specific needs)
42             CustomizePrefab(tempPrefab, customImporters);
43
44             // Part 3.5: Apply the scale only after all children have been added
45             tempPrefab.transform.localScale = new Vector3(prefabScale, prefabScale, prefabScale);
46
47             // Part 4: Save the prefab, keeping references intact.
48             string prefabPath = ImportUtils.GetPrefabPath(prefabName);
49             UnityEngine.Object finalPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));
50
51             if (finalPrefab == null)
52             {
53                 // The prefab needs to be created
54                 ImportUtils.ReadyToWrite(prefabPath);
55                 finalPrefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
56             }
57
58             // Replace the prefab, keeping connections based on name.
59             PrefabUtility.ReplacePrefab(tempPrefab, finalPrefab, ReplacePrefabOptions.ReplaceNameBased);
60
61             // Destroy the instance from the current scene hiearchy.
62             UnityEngine.Object.DestroyImmediate(tempPrefab);
63         }
File name: ImportTiled2Unity.Texture.cs Copy
14         public void TextureImported(string texturePath)
15         {
16             // This is fixup method due to materials and textures, under some conditions, being imported out of order
17             Texture2D texture2d = AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D)) as Texture2D;
18             Material material = AssetDatabase.LoadAssetAtPath(ImportUtils.GetMaterialPath(texturePath), typeof(Material)) as Material;
19             material.SetTexture("_MainTex", texture2d);
20         }
File name: ImportTiled2Unity.Xml.cs Copy
42         private void ImportTexturesFromXml(XDocument xml)
43         {
44             var texData = xml.Root.Elements("ImportTexture");
45             foreach (var tex in texData)
46             {
47                 string name = tex.Attribute("filename").Value;
48                 string data = tex.Value;
49
50                 // The data is gzip compressed base64 string. We need the raw bytes.
51                 //byte[] bytes = ImportUtils.GzipBase64ToBytes(data);
52                 byte[] bytes = ImportUtils.Base64ToBytes(data);
53
54                 // Save and import the texture asset
55                 {
56                     string pathToSave = ImportUtils.GetTexturePath(name);
57                     ImportUtils.ReadyToWrite(pathToSave);
58                     File.WriteAllBytes(pathToSave, bytes);
59                     AssetDatabase.ImportAsset(pathToSave, ImportAssetOptions.ForceSynchronousImport);
60                 }
61
62                 // Create a material if needed in prepartion for the texture being successfully imported
63                 {
64                     string materialPath = ImportUtils.GetMaterialPath(name);
65                     Material material = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
66                     if (material == null)
67                     {
68                         // We need to create the material afterall
69                         // Use our custom shader
70                         material = new Material(Shader.Find("Tiled/TextureTintSnap"));
71                         ImportUtils.ReadyToWrite(materialPath);
72                         AssetDatabase.CreateAsset(material, materialPath);
73                     }
74                 }
75             }
76         }
File name: ImportTiled2Unity.Xml.cs Copy
78         private void CreateMaterialsFromInternalTextures(XDocument xml)
79         {
80             var texData = xml.Root.Elements("InternalTexture");
81             foreach (var tex in texData)
82             {
83                 string texAssetPath = tex.Attribute("assetPath").Value;
84                 string materialPath = ImportUtils.GetMaterialPath(texAssetPath);
85
86                 Material material = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
87                 if (material == null)
88                 {
89                     // Create our material
90                     material = new Material(Shader.Find("Tiled/TextureTintSnap"));
91
92                     // Assign to it the texture that is already internal to our Unity project
93                     Texture2D texture2d = AssetDatabase.LoadAssetAtPath(texAssetPath, typeof(Texture2D)) as Texture2D;
94                     material.SetTexture("_MainTex", texture2d);
95
96                     // Write the material to our asset database
97                     ImportUtils.ReadyToWrite(materialPath);
98                     AssetDatabase.CreateAsset(material, materialPath);
99                 }
100             }
101         }

LoadAssetAtPath 136 lượt xem

Gõ tìm kiếm nhanh...