Skip to content

Instantly share code, notes, and snippets.

@ryanc-unity
Last active August 22, 2022 14:55
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save ryanc-unity/1fe70f93161e768f8c853d2b57ffb511 to your computer and use it in GitHub Desktop.
Save ryanc-unity/1fe70f93161e768f8c853d2b57ffb511 to your computer and use it in GitHub Desktop.
Dummy object generator for project testing
using System.Collections;
using System.IO;
using UnityEngine;
public class AsyncBundleLoader : MonoBehaviour
{
// Used for visual debugging as to not generate unnecessary allocations
public GameObject worldLight;
// Private fields to keep track of loaded objects
private AssetBundle m_Bundle;
private Texture2D m_Asset;
private const string kASSETBUNDLE_PATH = "Assets/Bundles/Textures/Texture0.png";
private static string kASSETBUNDLE_FILE;
private void Awake()
{
kASSETBUNDLE_FILE = Path.Combine(Application.streamingAssetsPath, "generated");
}
private IEnumerator Start()
{
while (true)
{
// TODO: Add an exit hook besides ALT+F4
// Wait to trigger loading
while (!Input.anyKeyDown)
yield return null;
yield return null;
// Load Bundle
var bundleRequest = AssetBundle.LoadFromFileAsync(kASSETBUNDLE_FILE);
yield return bundleRequest;
m_Bundle = bundleRequest.assetBundle;
// Load Asset
var assetRequest = m_Bundle.LoadAssetAsync<Texture2D>(kASSETBUNDLE_PATH);
yield return assetRequest;
m_Asset = assetRequest.asset as Texture2D;
// Turn off the light, visual loading status indicator
worldLight.SetActive(false);
// Wait to trigger unloading
while (!Input.anyKeyDown)
yield return null;
yield return null;
// Unload Bundle and Asset
m_Asset = null;
m_Bundle.Unload(true);
m_Bundle = null;
// Turn on the light, visual loading status indicator
worldLight.SetActive(true);
}
}
}
using System.Collections;
using UnityEngine;
public class AsyncResourcesLoader : MonoBehaviour
{
// Used for visual debugging as to not generate unnecessary allocations
public GameObject worldLight;
// Private field to keep track of loaded objects
private Texture2D m_Asset;
private const string kRESOURCE_PATH = "Textures/Texture0";
private IEnumerator Start()
{
while (true)
{
// TODO: Add an exit hook besides ALT+F4
// Wait to trigger loading
while (!Input.anyKeyDown)
yield return null;
yield return null;
// Load Asset
var assetRequest = Resources.LoadAsync<Texture2D>(kRESOURCE_PATH);
yield return assetRequest;
m_Asset = assetRequest.asset as Texture2D;
// Turn off the light, visual loading status indicator
worldLight.SetActive(false);
// Wait to trigger unloading
while (!Input.anyKeyDown)
yield return null;
yield return null;
// Unload Bundle and Asset
Resources.UnloadAsset(m_Asset);
m_Asset = null;
// Turn on the light, visual loading status indicator
worldLight.SetActive(true);
}
}
}
using System.IO;
using UnityEngine;
public class BundleLoader : MonoBehaviour
{
// Used for visual debugging as to not generate unnecessary allocations
public GameObject worldLight;
// Private fields to keep track of loaded objects
private AssetBundle m_Bundle;
private Texture2D m_Asset;
private const string kASSETBUNDLE_PATH = "Assets/Bundles/Textures/Texture0.png";
private static string kASSETBUNDLE_FILE;
private void Awake()
{
kASSETBUNDLE_FILE = Path.Combine(Application.streamingAssetsPath, "generated");
}
private void Update()
{
if (m_Asset == null)
DoLoadAsset();
else
DoUnloadAsset();
}
private void DoLoadAsset()
{
// Wait to trigger loading
if (!Input.anyKeyDown)
return;
// Load Bundle
m_Bundle = AssetBundle.LoadFromFile(kASSETBUNDLE_FILE);
// Load Asset
m_Asset = m_Bundle.LoadAsset<Texture2D>(kASSETBUNDLE_PATH);
// Turn off the light, visual loading status indicator
worldLight.SetActive(false);
}
private void DoUnloadAsset()
{
// Wait to trigger unloading
if (!Input.anyKeyDown)
return;
// Unload Bundle and Asset
m_Asset = null;
m_Bundle.Unload(true);
m_Bundle = null;
// Turn on the light, visual loading status indicator
worldLight.SetActive(true);
}
}
#if UNITY_EDITOR
using System;
using System.IO;
using UnityEditor;
using UnityEngine;
public class Generator
{
public const string kSUBFOLDER = "Bundles";
public const string kBUNDLENAME = "generated";
public const int kSCRIPT_COUNT = 100;
public const int kPREFAB_COUNT = 100;
public const int kPREFAB_DEPTH = 100;
public const int kTEXTURE_COUNT = 100;
public const int kSEED = 8147056;
public const BuildAssetBundleOptions kBUILD_OPTIONS = BuildAssetBundleOptions.UncompressedAssetBundle;
[MenuItem("Tools/Build Asset Bundles", false, 0)]
public static void BuildAssetBundles()
{
// Setup output folder
try { Directory.Delete(Application.streamingAssetsPath, true); } catch { /*Ignored*/ }
Directory.CreateDirectory(Application.streamingAssetsPath);
// Set the asset bundle name
var importer = AssetImporter.GetAtPath(string.Format("Assets/{0}", kSUBFOLDER));
importer.assetBundleName = kBUNDLENAME;
AssetDatabase.Refresh();
// Write out asset bundles using the current build target
BuildPipeline.BuildAssetBundles(Application.streamingAssetsPath, kBUILD_OPTIONS, EditorUserBuildSettings.activeBuildTarget);
}
[MenuItem("Tools/Create Code Types", false, 1)]
public static void CreateCodeFiles()
{
// Setup output folder - Note: Code does not go in Resource folder or in an Asset Bundle, thus kSUBFOLDER not used here
var directoryPath = string.Format("{0}/Code", Application.dataPath);
try { Directory.Delete(directoryPath, true); } catch { /*Ignored*/ }
Directory.CreateDirectory(directoryPath);
// Write code files
for (var i = 0; i < kSCRIPT_COUNT; i++)
{
var filePath = string.Format("{0}/CodeType{1}.cs", directoryPath, i);
var fileContents = string.Format("using UnityEngine;\npublic class CodeType{0} : MonoBehaviour {{\n\tpublic int someInt = {0};\n\tpublic float someFloat = {0}.0f;\n\tpublic string someString = \"{0}\";\n}}", i);
File.WriteAllText(filePath, fileContents);
}
// Update the AssetDatabase
AssetDatabase.Refresh();
}
[MenuItem("Tools/Create Game Object Prefabs", false, 2)]
public static void CreateGameObjectPrefab()
{
// Setup output folder
var directoryPath = string.Format("{0}/{1}/Prefabs", Application.dataPath, kSUBFOLDER);
try { Directory.Delete(directoryPath, true); } catch { /*Ignored*/ }
Directory.CreateDirectory(directoryPath);
// Generate some prefabs
var random = new System.Random(kSEED);
var gameObjects = new GameObject[kPREFAB_DEPTH];
for (var i = 0; i < kPREFAB_COUNT; i++)
{
// Create Game Objects and add components
for (var j = 0; j < kPREFAB_DEPTH; j++)
{
gameObjects[j] = new GameObject(string.Format("GameObject{0}", j));
var type = Type.GetType(string.Format("CodeType{0}, Assembly-CSharp", random.Next(0, kSCRIPT_COUNT)));
gameObjects[j].AddComponent(type);
}
// Parent GameObjects
for (var j = 1; j < kPREFAB_DEPTH; j++)
gameObjects[j].transform.SetParent(gameObjects[random.Next(0, j)].transform);
// Write generated prefab to disk
var assetsPath = directoryPath.Replace(Application.dataPath, "Assets");
PrefabUtility.CreatePrefab(string.Format("{0}/GameObjectPrefab{1}.prefab", assetsPath, i), gameObjects[0]);
// Cleanup generated prefab
UnityEngine.Object.DestroyImmediate(gameObjects[0]);
}
// Update the AssetDatabase
AssetDatabase.Refresh();
}
[MenuItem("Tools/Create Textures", false, 3)]
public static void CreateTextures()
{
// Setup output folder
var directoryPath = string.Format("{0}/{1}/Textures", Application.dataPath, kSUBFOLDER);
try { Directory.Delete(directoryPath, true); } catch { /*Ignored*/ }
Directory.CreateDirectory(directoryPath);
// Generate some textures
var random = new System.Random(kSEED);
for (var i = 0; i < kTEXTURE_COUNT; i++)
{
// Create Texture and set pixels
var texture = new Texture2D(256, 256);
for (var x = 0; x < texture.width; x++)
{
for (var y = 0; y < texture.height; y++)
texture.SetPixel(x, y, new Color((float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble(), (float)random.NextDouble()));
}
// Apply modifed pixels to texture
texture.Apply();
// Write generated texture to disk
File.WriteAllBytes(string.Format("{0}/Texture{1}.png", directoryPath, i), texture.EncodeToPNG());
// Cleanup generated texture
UnityEngine.Object.DestroyImmediate(texture);
}
// Update the AssetDatabase
AssetDatabase.Refresh();
}
}
#endif
using UnityEngine;
public class ResourcesLoader : MonoBehaviour
{
// Used for visual debugging as to not generate unnecessary allocations
public GameObject worldLight;
// Private field to keep track of loaded objects
private Texture2D m_Asset;
private const string kRESOURCE_PATH = "Textures/Texture0";
private void Update()
{
if (m_Asset == null)
DoLoadAsset();
else
DoUnloadAsset();
}
private void DoLoadAsset()
{
// Wait to trigger loading
if (!Input.anyKeyDown)
return;
// Load Asset
m_Asset = Resources.Load<Texture2D>(kRESOURCE_PATH);
// Turn off the light, visual loading status indicator
worldLight.SetActive(false);
}
private void DoUnloadAsset()
{
// Wait to trigger unloading
if (!Input.anyKeyDown)
return;
// Unload Bundle and Asset
Resources.UnloadAsset(m_Asset);
m_Asset = null;
// Turn on the light, visual loading status indicator
worldLight.SetActive(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment