Phoera Phoera - 1 year ago 67
C# Question

Getting guid's from prefabs in Unity

Kinda specific question, I'm working on a script which will retreive all unused materials and textures from the project and show/delete them. I went by path of GUID parsing from a scene file, but encountered a couple of problems, which, if can't be solved, make this solution impossible.

1) In scene ".unity" file, when a prefab is used, it contains only this prefab's GUID, but prefab itself contains child objects - how can they be accessible?

m_ObjectHideFlags: 0
serializedVersion: 2
m_TransformParent: {fileID: 0}
- target: {fileID: 444956, guid: 6a526c61069224c92930d52849053cbe, type: 2}
propertyPath: m_LocalPosition.x
value: 0
objectReference: {fileID: 0}

And as well in the Project view there are no children more than second hierarchy level:
enter image description here

What I want to do - somehow to get all the materials AND textures used by, for example, "Ceiling" in the scene. Taking in account that "Blue" prefab is loaded at runtime, not present in the scene, so I can only take the root guid from the monobehaviour.

2) Even if I somehow get all the used the materials, how to properly get textures used by them without accessing renderer of a gameobject, just these:

enter image description here

I know it's a bit messy question, so please, ask if something is not clear. Thanks in advance.

Answer Source

You may need this: AssetDatabase.GUIDToAssetPath(string guid);

  1. You have parent prefab -> you can extract all guid of its children -> you can find children prefabs -> you can extract all guid of their children and so on ...
  2. You have a material -> you can extract all guid of its used materials then you can use AssetDatabase.GUIDToAssetPath(string guid) to get all the used texture paths. Resources.Load<Texture2D>(string assetPath); can be used to get the actual textures.
  3. I'm afraid accessing prefab loaded at run-time is not possible. Just like shader. If you load a shader at runtime and you forget to add it to AlwaysIncludedShaders you will get the pink stuff only on the built version but not when playing in the Editor. Even Unity can't solve that problem. At least not yet.

Some more methods you may be intersted in: