CodeSmile AssetDatabase 1.10
Unity's AssetDatabase in enjoyable, consistent, concise, convenient, comprehensible, safe, documented form.
Loading...
Searching...
No Matches
Asset.cs
1// Copyright (C) 2021-2024 Steffen Itterheim
2// Refer to included LICENSE file for terms and conditions.
3
4using System;
5using System.Diagnostics.CodeAnalysis;
6using System.IO;
7using UnityEditor;
8// UnityEngine is imported for the GUID type: it is declared in UnityEditor up to Unity
9// 6000.3 and in UnityEngine from Unity 6000.4 on. Neither namespace declared it in both on any
10// of the nine editors tested.
11using UnityEngine;
12using Object = UnityEngine.Object;
13
14namespace CodeSmileEditor
15{
22 public sealed partial class Asset
23 {
24 private Path m_AssetPath;
25 private Object m_MainObject;
26
37 public static implicit operator Object(Asset asset) => asset != null ? asset.MainObject : null;
38
50 public static implicit operator Asset(Object asset) => asset != null ? new Asset(asset) : null;
51
62 public static implicit operator Asset(Path path) => path != null ? new Asset(path) : null;
63
75 public static implicit operator Asset(String path) => (Path)path; // implicit forward to Asset(Path)
76
88 public static implicit operator Asset(GUID guid) => guid.Empty() == false ? new Asset(guid) : null;
89
90 [ExcludeFromCodeCoverage] private Asset() {} // disallow parameterless ctor
91
108 public Asset(Byte[] contents, Path path, Boolean overwriteExisting = false)
109 {
110 ThrowIf.ArgumentIsNull(contents, nameof(contents));
111 ThrowIf.ArgumentIsNull(path, nameof(path));
112
113 path = Path.UniquifyAsNeeded(path, overwriteExisting);
114 var asset = File.CreateInternal(contents, path);
115 InitWithMainObject(asset);
116 }
117
133 public Asset(String contents, Path path, Boolean overwriteExisting = false)
134 {
135 ThrowIf.ArgumentIsNull(contents, nameof(contents));
136 ThrowIf.ArgumentIsNull(path, nameof(path));
137
138 path = Path.UniquifyAsNeeded(path, overwriteExisting);
139 var asset = File.CreateInternal(contents, path);
140 InitWithMainObject(asset);
141 }
142
162 public Asset(Object asset, Path path, Boolean overwriteExisting = false)
163 {
164 ThrowIf.ArgumentIsNull(asset, nameof(asset));
165 ThrowIf.ArgumentIsNull(path, nameof(path));
166 ThrowIf.AlreadyAnAsset(asset);
167
168 path = Path.UniquifyAsNeeded(path, overwriteExisting);
169 File.CreateInternal(asset, path);
170 InitWithMainObject(asset);
171 }
172
183 public Asset(Path path) => InitWithPath(path);
184
194 public Asset(GUID assetGuid) => InitWithGuid(assetGuid);
195
206 public Asset(Object asset) => InitWithMainObject(asset);
207
217 public T GetMain<T>() where T : Object => m_MainObject as T;
218
229 public void Save() => File.Save(m_MainObject);
230
241 public void ForceSave() => File.ForceSave(m_MainObject);
242
259 public Asset SaveAs(Path path) => File.Copy(m_AssetPath, path) ? new Asset(path) : null;
260
277 public Asset SaveAsNew(Path path)
278 {
279 ThrowIf.ArgumentIsNull(path, nameof(path));
280
281 return SaveAs(path.UniqueFilePath);
282 }
283
292 public Asset Duplicate() => SaveAsNew(m_AssetPath);
293
300 public void SetDirty() => EditorUtility.SetDirty(m_MainObject);
301
302 // NOTE: there is no public Import() method needed since the main object is guaranteed to be imported
303 [ExcludeFromCodeCoverage] // private, not used
304 private void Import() {}
305
306 // Private on purpose: the main object is automatically loaded when instantiating an Asset class.
307 private T LoadMain<T>() where T : Object => m_AssetPath != null ? (T)(m_MainObject = File.Load<T>(m_AssetPath)) : null;
308
322 public T Load<T>() where T : Object => File.Load<T>(m_AssetPath);
323
337 public Boolean CanMove(Path destinationPath) => File.CanMove(m_AssetPath, destinationPath);
338
353 public Boolean Move(Path destinationPath)
354 {
355 if (File.Move(m_AssetPath, destinationPath))
356 {
357 SetAssetPathFromObject();
358 return true;
359 }
360
361 return false;
362 }
363
394 public Boolean Rename(String newFileName)
395 {
396 if (File.Rename(m_AssetPath, newFileName))
397 {
398 SetAssetPathFromObject();
399 return true;
400 }
401
402 return false;
403 }
404
416 [ExcludeFromCodeCoverage] // simple relay
417 public Boolean CanOpenInEditor() => File.CanOpenInEditor(m_MainObject);
418
427 [ExcludeFromCodeCoverage] // cannot be tested
428 public void OpenExternal(Int32 lineNumber = -1, Int32 columnNumber = -1) => File.OpenExternal(m_MainObject, lineNumber, columnNumber);
429
444 public Object Delete()
445 {
446 var mainObject = m_MainObject;
447 if (File.Delete(m_AssetPath))
448 InvalidateInstance();
449
450 return mainObject;
451 }
452
467 public Object Trash()
468 {
469 var mainObject = m_MainObject;
470 if (File.Trash(m_AssetPath))
471 InvalidateInstance();
472
473 return mainObject;
474 }
475
485 [ExcludeFromCodeCoverage] // simple relay
486 public void SetLabels(String[] labels) => Label.SetAll(m_MainObject, labels);
487
497 public void ClearLabels() => Label.ClearAll(m_MainObject);
498
506 public void RemoveLabel(String label) => Label.Remove(m_MainObject, label);
507
520 public void AddLabel(String label) => Label.Add(m_MainObject, label);
521
530 public void AddLabels(String[] labels) => Label.Add(m_MainObject, labels);
531
532 // Both branches are duplicated in full on purpose. A preprocessor directive inside a run of ///
533 // lines, or between a doc comment and the declaration it documents, ends that comment for the C#
534 // compiler and drops the <summary>, so the conditional must wrap whole members, never parts of a
535 // doc comment.
536#if UNITY_6000_6_OR_NEWER
552 [ExcludeFromCodeCoverage] // simple relay
553 public void ExportPackage(String packagePath, ExportPackageOptions options = ExportPackageOptions.Default,
554 String ownerOrgId = null) => Package.Export(m_AssetPath, packagePath, options, ownerOrgId);
555#else
566 [ExcludeFromCodeCoverage] // simple relay
567 public void ExportPackage(String packagePath, ExportPackageOptions options = ExportPackageOptions.Default) =>
568 Package.Export(m_AssetPath, packagePath, options);
569#endif
570
580 public void AddSubAsset(Object instance) => SubAsset.Add(instance, m_MainObject);
581
590 public void RemoveSubAsset(Object subAsset) => SubAsset.Remove(subAsset);
591
592 private void InvalidateInstance()
593 {
594 m_AssetPath = null;
595 m_MainObject = null;
596 }
597
598 private void SetAssetPathFromObject() => m_AssetPath = Path.Get(m_MainObject);
599
600 private void InitWithPath(Path path)
601 {
602 ThrowIf.ArgumentIsNull(path, nameof(path));
603 ThrowIf.DoesNotExistInFileSystem(path);
604
605 m_AssetPath = path;
606 m_MainObject = Status.IsImported(path) ? LoadMain<Object>() : File.ImportAndLoad<Object>(path);
607
608 ThrowIf.AssetLoadReturnedNull(m_MainObject, m_AssetPath);
609 }
610
611 private void InitWithMainObject(Object mainObject)
612 {
613 ThrowIf.ArgumentIsNull(mainObject, nameof(mainObject));
614 ThrowIf.NotInDatabase(mainObject);
615
616 m_MainObject = mainObject;
617 m_AssetPath = Path.Get(mainObject);
618 }
619
620 private void InitWithGuid(GUID guid)
621 {
622 ThrowIf.NotAnAssetGuid(guid);
623
624 InitWithPath(Path.Get(guid));
625 }
626 }
627}
static Boolean Rename([NotNull] Path path, String newFileName)
Renames an asset's file or folder name.
static Boolean CanOpenInEditor([NotNull] Object instance)
Returns true if the given object can be opened (edited) by the Unity editor.
static Boolean Delete([NotNull] Path path)
Deletes an asset file or folder.
static Boolean Trash([NotNull] Path path)
Moves an asset file or folder to the OS trash.
static Boolean Move([NotNull] Path sourcePath, [NotNull] Path destinationPath)
Moves an asset file to destination path.
static void OpenExternal([NotNull] Object asset, Int32 lineNumber=-1, Int32 columnNumber=-1)
Opens the asset in the application associated with the file's extension.
Groups file related operations.
Definition Asset.File.cs:38
static void SetAll([NotNull] Object asset, [NotNull] String[] labels)
Sets an asset's labels. Replaces any existing labels.
static void Remove(Object asset, String label)
Removes a label from an asset. Does nothing if the label doesn't exist.
static void ClearAll([NotNull] Object asset)
Clears all labels of an asset.
static void Add([NotNull] Object asset, [NotNull] String label)
Adds a single label to an asset's list of labels.
Groups all asset label related static methods.
static void Export([NotNull] Path assetPath, [NotNull] String packagePath, ExportPackageOptions options=ExportPackageOptions.Default, String ownerOrgId=null)
Exports the asset and its dependencies to a .unitypackage file.
Groups import/export functionality for .unitypackage files (Asset Packages).
static Path Get([NotNull] Object asset)
Gets the relative path of an asset.
Represents a relative path to an asset file or folder, typically under 'Assets' or 'Packages'.
Definition Asset.Path.cs:25
static void Add([NotNull] Object subAssetInstance, [NotNull] Object asset)
Adds an object as sub-asset to the asset. This change is implicitly saved to disk.
static void Remove([NotNull] Object subAsset)
Removes a sub-object from the asset it is contained in.
Groups all Sub-Asset related functionality.
void OpenExternal(Int32 lineNumber=-1, Int32 columnNumber=-1)
Opens the asset in the external (associated) application.
T GetMain< T >()
Gets the main object cast to T.
Asset(GUID assetGuid)
Loads the asset using its GUID.
Asset(Object asset)
Uses an existing asset reference.
Asset SaveAs(Path path)
Saves a copy of the asset to a new path. Overwrites any existing asset at path.
void ClearLabels()
Removes all labels from the asset.
Asset(Path path)
Loads the asset at path.
Boolean Rename(String newFileName)
Renames an asset's file name (without extension) or a folder.
Definition Asset.cs:394
void AddLabel(String label)
Adds a label to the asset.
Boolean CanMove(Path destinationPath)
Tests if a Move operation will be successful without actually moving the asset.
Boolean Move(Path destinationPath)
Moves asset to destination path.
Definition Asset.cs:353
Asset(Byte[] contents, Path path, Boolean overwriteExisting=false)
Creates an asset file from a byte array.
Definition Asset.cs:108
void Save()
Saves any changes to the asset to disk.
void AddLabels(String[] labels)
Adds several labels to the asset.
void AddSubAsset(Object instance)
Adds an object as a sub-object to the asset. The object must not already be an asset.
void ForceSave()
Saves the asset to disk, regardless of whether it is marked as 'dirty'.
Asset(String contents, Path path, Boolean overwriteExisting=false)
Creates an asset file from a string.
Definition Asset.cs:133
void RemoveLabel(String label)
Removes a label from an asset. Does nothing if the label doesn't exist.
Object Trash()
Moves the asset to the OS trash. Same as Delete, but recoverable.
Definition Asset.cs:467
void ExportPackage(String packagePath, ExportPackageOptions options=ExportPackageOptions.Default, String ownerOrgId=null)
Exports this asset and its dependencies as a .unitypackage.
Boolean CanOpenInEditor()
Returns true if the asset can be opened (edited) by the Unity Editor itself.
Asset(Object asset, Path path, Boolean overwriteExisting=false)
Creates an asset file from an existing UnityEngine.Object instance.
Definition Asset.cs:162
void SetDirty()
Marks the main object as dirty.
Asset Duplicate()
Creates a duplicate of the asset with a new, unique file name.
void RemoveSubAsset(Object subAsset)
Removes an object from the asset's sub-objects.
Asset SaveAsNew(Path path)
Saves a copy of the asset to a new path. Generates a unique file/folder name if path already exists.
Definition Asset.cs:277
Object Delete()
Deletes the asset file.
Definition Asset.cs:444
void SetLabels(String[] labels)
Sets the asset's labels, replacing all previously existing labels.
Replacement implementation for Unity's massive AssetDatabase class with a cleaner interface and more ...