- Home /
This question was
closed Apr 11, 2017 at 03:54 PM by
fastwings12 for the following reason:
found a solotion
Question by
fastwings12 · Apr 11, 2017 at 05:41 PM ·
spriteresources
how to dynamic create a prefabs from existing sprite (png file)
i have an issue that have alot of assets of png files a.k.a sprite that loaded into the unity project i try build small tool that will load a from them a prefabs (have more then 30 and it is a pain create prefab each of them and they may change) i build this code:
void GeneratorPrefab(AssetSpriteObject assetSprite)
{
GameObject obj = new GameObject();
obj.name = assetSprite.Name;
Sprite sprite = new Sprite();
string spritePath = assetSprite.RelativePath.Replace(".png", "");
Debug.Log(String.Format("Loading Res {0}", spritePath));
sprite = Resources.Load<Sprite>(spritePath);
obj.AddComponent<SpriteRenderer>();
SpriteRenderer SR = obj.GetComponent<SpriteRenderer>();
SR.sprite = sprite;
String pathString = Path.GetFullPath(new Uri(Path.Combine(Path.GetDirectoryName(globalPath), String.Format(@"../../Assets/Prefabs/Gen/{0}", prefixName))).AbsolutePath);
if (!Directory.Exists(pathString))
Directory.CreateDirectory(pathString);
UnityEngine.Object prefab = PrefabUtility.CreateEmptyPrefab(String.Format(@"Assets/Prefabs/Gen/{0}/{0}_{1}.prefab", prefixName, assetSprite.Name.Replace(".png", "")));
PrefabUtility.ReplacePrefab(obj, prefab, ReplacePrefabOptions.ReplaceNameBased);
DestroyImmediate(obj);
}
now it create the prefab but it without a sprite like the code "sprite = Resources.Load(spritePath);" if i debug i see at as null and don't understand why or how to fix my question what i do wrong here P.S the link for the source file here
Comment
Ok i found the issue it look like i load wrong i change the sprite = Resources.Load(spritePath); into Sprite s = (Sprite)Resources.Load(spritePath, typeof(Sprite)); and it did the trick look like is has casting wrong