Skip to content

Instantly share code, notes, and snippets.

@danamuise
Last active May 5, 2018 19:08
Show Gist options
  • Save danamuise/8d8c257c6ef412068f4d36d3b321d888 to your computer and use it in GitHub Desktop.
Save danamuise/8d8c257c6ef412068f4d36d3b321d888 to your computer and use it in GitHub Desktop.
Unity C# instantiates a child object at run time based on frequency or usage. This improves performance, as it can be used to instantiates particle effects only when they are needed, also reduced particle emissions when frame rate drops below a specified amount.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace ProjectKing {
/**
//Add this script to a gameobject that you would like to instantiate a particle effect object
//Also optimizes particle emmisions based on frame rate drop
//
**/
public class InstanceAdd: MonoBehaviour {
public GameObject parentGameObject;
public bool destoryOnDeactiveate = true;
public eMemoryLevels targetMemoryLevel;
//optimize particles settings
public float targetFPS = 60.0 f; //What is your target frame rate?
public float lossTolerance = 100.0 f; //what is the maximimum percentage of frame rate drop allowable?
public bool optimize = false; //optimize particle system default: off
public ParticleSystem myParticles; // drag your particle system here in inspector
public static bool shouldShowDuringLock = false; //Show if game is paused
private int rate = 0;
private int size = 1;
// Do not show effects while spinning or whenever they are moving too fast to be seen.
public static bool lockEffectShow = false;
protected GameObject addedInstance;
private bool instantiateObject = false;
// Use this for initialization
void OnEnable() {
if (addedInstance == null && (shouldShowDuringLock || !lockEffectShow)) {
if (instantiateObject) {
addedInstance = GameObject.Instantiate(parentGameObject);
addedInstance.transform.parent = this.transform;
addedInstance.transform.localPosition = Vector3.zero;
addedInstance.transform.localRotation = Quaternion.identity;
addedInstance.transform.localScale = Vector3.one;
}
}
}
//When parent is disabled, object is destroyed
void OnDisable() {
if (destoryOnDeactiveate && addedInstance != null) {
Destroy(addedInstance);
}
}
void OnUpdate() {
//monitor fps. If it drops below tolerance, remove a percentage of particle emmisions
if (targetFPS < targetFPS / (lossTolerance * 0.01) && optimize)
OptimizeParticles(0.1 f);
}
void OptimizeParticles(float scaler) {
float opScaler = scaler;
myParticles.emissionRate = (int) scaler; // reduce emissions rate
myParticles.startSize = scaler; //reduce particle size
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment