Skip to content

Instantly share code, notes, and snippets.

@brainwipe
Last active December 5, 2021 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brainwipe/10697562f0fcb8b678ef11939edb9dc8 to your computer and use it in GitHub Desktop.
Save brainwipe/10697562f0fcb8b678ef11939edb9dc8 to your computer and use it in GitHub Desktop.
Creating and Saving Unity Prefabs
/*
Unity C# Psudocode to show how to create a mesh, save it as an asset and then attach it to a prefab.
by Rob Lang https://www.youtube.com/roblang
*/
#if (UNITY_EDITOR)
using UnityEditor;
using UnityEngine;
public static class PrefabBuilder
{
/// <summary>
/// Creates and saves a mesh and prefab from the given mesh, material and name
/// </summary>
/// <param name="myMesh">The mesh you want attached to the prefab</param>
/// <param name="myMaterial">The material that the mesh will be rendered with</param>
/// <param name="name">The Unity and hard disc safe name for the prefab</param>
/// <returns>A prefab game object. You must instantiate real game objects from this if you want to use it</returns>
public static class PrefabBuilder
{
/// <summary>
/// Creates and saves a mesh and prefab from the given mesh, material and name
/// </summary>
/// <param name="myMesh">The mesh you want attached to the prefab</param>
/// <param name="myMaterial">The material that the mesh will be rendered with</param>
/// <param name="name">The Unity and hard disc safe name for the prefab</param>
/// <returns>A prefab game object. You must instantiate real game objects from this if you want to use it</returns>
public static GameObject CreatePrefabFrom(Mesh myMesh, Material myMaterial, string name)
{
AssetDatabase.CreateAsset(myMesh, $"{name}.asset"); // If mesh asset exists, overwrite. Otherwise create.
// Try load the prefab
var prefabPath = $"Resources/{name}.asset";
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
if (prefab == null)
{
var instance = new GameObject($"{name}");
instance.AddComponent<MeshFilter>().sharedMesh = myMesh;
instance.AddComponent<MeshRenderer>().material = myMaterial;
prefab = PrefabUtility.SaveAsPrefabAssetAndConnect(instance, prefabPath, InteractionMode.AutomatedAction);
UnityEngine.Object.DestroyImmediate(instance);
}
return prefab; // Although a gameobject, this is just a prefab - you have to Instantiate new gameobjects from it if you want to use it
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment