Unity - Particle system - Particle count - c#

Does any know if Unity has a way to count how many particles have been emitted by a particle system? So I could check to see if there has been an emission, like:
public ParticleSystem mySystem;
private int currentParticleCount;
private int lastParticleCount;
void Start () {
lastParticleCount = mySystem.getEmissionCount();
}
void Update () {
currentParticleCount = mySystem.getEmissionCount();
if(currentParticleCount>lastParticleCount) {
DoStuff();
}
lastParticleCount = currentParticleCount;
}

You can use ParticleSystem.particleCount to return the current number of particles. If that's not giving you the proper amount of particles, use the ParticleSystem.GetParticles function since that returns just the current number of alive particles. Below is an example for both of them:
private ParticleSystem ps;
// Use this for initialization
void Start()
{
ps = GetComponent<ParticleSystem>();
}
// Update is called once per frame
void Update()
{
Debug.Log("Particles Count: " + ps.particleCount);
Debug.Log("Particles Alive Count: " + GetAliveParticles());
}
int GetAliveParticles()
{
ParticleSystem.Particle[] particles = new ParticleSystem.Particle[ps.particleCount];
return ps.GetParticles(particles);
}

The exact feature that you are asking for is not build it, BUT:
You can know the current particles displayed by the system, so you can make a counter that acumulates the number, or if you know the "displaying time" you can do the maths.
Knowing the current particles:
ParticleSystem.particleCount https://docs.unity3d.com/ScriptReference/ParticleSystem-particleCount.html

Related

How much cost GameObject.FindGameObjects takes in Unity Update function

I'm making a game in which I want to player collect coins using a magnet
here is the coins spawning code
// Spawn Coins In Air
void SpawnCoinsInAir ()
{
float yPos = transform.position.y + 1f;
float zPos = transform.position.z + 4f;
for (int i = 0 ; i < 10 ; i += 1)
{
int line = i == 0 ?
RandomsPlayerController.Instance.CurrentLineIdx
:
Random.Range(0, RandomsPlayerController.Instance.Lines.Count);
for (int j = 0 ; j < Random.Range(3,6) ; j += 1)
{
zPos += j + 10f;
var it = Instantiate(
coinTransform,
new Vector3(RandomsPlayerController.Instance.Lines [line].x,yPos , zPos),
Quaternion.identity
);
// do random rotattion in y
it.transform.DORotate (
Utilities.VectorY (Vector3.zero, Random.Range(-360,360)),
1f,
RotateMode.FastBeyond360
)
.SetEase (Ease.InOutSine);
Destroy (it, actionDuration + 1f);
}
}
}
Now I got all my coins in my game and I have to find each coin by its tag and collect them in the shortest distance.
I'm wondering how much cost it takes to find all coins in the Update function OR is there any way to do the same thing by keeping performance in mind?
Here is the code
private void UseMagnet ()
{
// collect coins
foreach (var coin in GameObject.FindGameObjectsWithTag ("coin")) continue;
}
private void Update () => UseMagnet();
Thanks in Advance
For smaller games, the cost is insignificant to the player. But it tends to get exponential the larger the search-space it.
How much cost GameObject.FindGameObjects
This is a case-by-case answer, use the profiler to see what is causing the most lag in your game.
Though unity documentation did state For performance reasons, it is recommended to not use this function every frame.
OR is there any way to do the same thing by keeping performance in mind?
Yes, what you are looking for is called caching.Create a static list and store all the coins there, like so:
// NOTE: Alternatively, you can turn this into a singleton
public static class GlobalCache {
// Transform or Coin Object.
private static HashSet<Transform> coinCache = new HashSet<Transform>();
public static Transform FetchAnyCoin() {
if (coinCache.Count <= 0) {
// Create a new coin, return it;
// NOTE: Ideally, creation of coins into this cache should be done else-where.
// The 'cache' should only handle storing and get/set requests.
return CreateNewCoin();
}
var result = coinCache.First();
// You can remove the fetched coin from the cache if you like.
coinCache.Remove(result);
return result;
}
}
In contrary to the generic Find, which you should never use if there is any other option, the FindGameObjectsWithTag as the name says uses a hashed (pre-indexed) tag which is quite optimized and not too expensive.
Of course there is still other ways to go which are even faster.
I would use a collection so the type itself can keep track of its own instances:
public class Coin : MonoBehaviour
{
private static readonly HashSet<Coin> instances = new ();
public static IEnumerable<Coin> Instances => instances;
private void Awake()
{
// will automatically register itself when coming to live
instances.Add(this);
}
private void OnDestroy()
{
// will automatically unregister itself when destroyed
instances.Remove(this);
}
}
Now you can simply iterate all coins via e.g.
foreach(var coin in Coin.Instances)
{
// check if close enough for your magnet e.g.
if(Vector3.Distance(coin.transform.position, player.transform.position) <= magnetRange)
{
//TODO: e.g. add points ?
Destroy(coin.gameObject);
}
}
It is considered fairly costly and is advised against using it in the Update function.
Essentially what you wish to do is to have a list over all spawned coins, and you control the spawning. This means you could easily add the spawned object to the list when you spawn it, and - if needed - remove them when you destroy them (if you dont remove them, you need to check for null in the list).
Not perfect, but depending on what you need it might work for you (not perfect because you're looping through a list asynchronously as you're adding/removing things from it)
For simplicity's sake, let's add a static (accessible anywhere) list somewhere
public static List<GameObject> SpawnedCoins = new List<GameObject>();
var it = Instantiate<GameObject>(coinTransform, ...);
SpawnedCoins.Add(it);
StartCoroutine(RemoveCoin(it))
IEnumerator RemoveCoin(GameObject coin, float time) {
yield return new WaitForSeconds(time);
SpawnedCoins.Remove(coin);
Destroy(coin);
}
Another class
foreach (var coin in SpawnedCoins) {
// Check for null first, if you Destroy them they will be null in the list
}
Alternatively, Destroy and check for null and then every few seconds clear the list of nulls before running the loop.

Unity Question: How Can I Switch From One prefab To Another With GetAxis?

I want to bind the up and down arrow keys to cycle through different sprites upon being pressed. If one end is reached, it would loop back to the first sprite. I've tried using the following code:
public class PhaseChanger : MonoBehaviour
{
// saved for efficiency
[SerializeField]
public GameObject prefabMoon0;
[SerializeField]
public GameObject prefabMoon1;
[SerializeField]
public GameObject prefabMoon2;
[SerializeField]
public GameObject prefabMoon3;
[SerializeField]
public GameObject prefabMoon4;
// needed for new phase
GameObject currentPhase;
bool previousFramePhaseChangeInput = false;
/// <summary>
/// Start is called before the first frame update
/// </summary>
void Start()
{
currentPhase = Instantiate<GameObject>(prefabMoon0);
}
/// <summary>
/// Update is called once per frame
/// </summary>
void Update()
{
// change phase on up arrow or down arrow
if (Input.GetAxis("ChangePhase") > 0)
{
// only change phase on first input frame
if (!previousFramePhaseChangeInput)
{
previousFramePhaseChangeInput = true;
// Save current position and destroy current phase
Destroy(currentPhase);
// instantiate next phase
if (currentPhase = prefabMoon0)
{
currentPhase = Instantiate(prefabMoon1);
}
else if (currentPhase = prefabMoon1)
{
currentPhase = Instantiate(prefabMoon2);
}
else if (currentPhase = prefabMoon2)
{
currentPhase = Instantiate(prefabMoon3);
}
else if (currentPhase = prefabMoon3)
{
currentPhase = Instantiate(prefabMoon4);
else
{
// no phase change input
previousFramePhaseChangeInput = false;
}
}
}
}
When I attach the script to my main camera and run it, I'm able to make a single change with the up arrow, and then nothing else happens on subsequent presses.
I feel like I'm really close to making this work, but I also may being doing the whole thing inefficiently. Help would be much appreciated, thanks!
Also: I know I said sprites in my post and am sharing a script that calls on prefabs. I didn't know how to approach this using just the sprites without making a prefab for each. Is it possible to do this without separate prefabs for each sprite?
Problems
First of all you are using assignments
currentPhase = XY
where you should be using
currentPhase == XY
The reason why it still compiles is the implicit conversion operator for UnityEngine.Object -> bool. Basically your assigning equals writing
currentPhase = XY;
if(currentPhase)
It won't work like this either way because you are using Instantiate to create a new clone of a prefab which will of course have a different reference than the original prefab it was cloned from.
So even if your checks where looking like
if(currentPhase == XY)
they will ever be true.
Solution
Instead of checking for reference equality I would rather store all prefabs/instances in an array
public GameObject[] phases;
and then simply have an int index for this array so you can simply move to the next element from the array by increasing the index.
private int currentPhase;
And you can increase it and make it wrap around using e.g.
currentPhase = (currentPhase + 1) % phases.Length;
so it will always grow from 0 up to phases.Length - 1 and then start over from 0 again.
And then I don't know the exact requirements of your use case but I would suggest to rather not all the time use Instantiate and Destroy but rather have already all the objects as instances under your object and just (de)actívate them!
you could do this like e.g.
public GameObject[] phases;
private int currentPhase;
private void Awake ()
{
Init();
}
private void Update ()
{
if (Input.GetAxis("ChangePhase") > 0)
{
if (!previousFramePhaseChangeInput)
{
previousFramePhaseChangeInput = true;
NextPhase();
}
}
else
{
previousFramePhaseChangeInput = false;
}
}
// Disables all phases except the first one and sets the current index to 0
private void Init()
{
for(var i = 1; i < phases.Length; i++)
{
phases[i].SetActive(false);
}
phases[0].SetActive(true);
currentPhase = 0;
}
// Disables the current phase and enables the next one
// wraps around at the end of the array
public void NextPhase()
{
phases[currentPhase].SetActive(false);
// increase the counter and wrap around at the end of the array
currentPhase = (currentPhase + 1) % phases.Length;
phases[currentPhase].SetActive(true);
}
If you still want to Instantiate the objects because having them already in the scene is no option (for whatever reason) you could do it right before calling Init like e.g.
public GameObject[] phasePrefabs;
private GameObject[] phases;
private void Awake ()
{
var amount = phasePrefabs.Length;
phases = new GameObject [amount];
for(var i = 0; i < amount; i++)
{
phases[i] = Instantiate(phasePrefabs[i]);
}
Init();
}
Though as said I would prefer to already have them right away as this is way less error prone ;)

Monogame C# Timer (do something for 15 seconds every 3 seconds)

I am trying to create a timer, which, for example, every 3 seconds during eg 15 seconds will perform an action.
I tried to use gameTime.ElapsedGameTime.TotalSeconds and loop, but unfortunately it doesn't work.
I have an Attack () function that reduces player statistics when an enemy attacks it. I would like that in case of one particular enemy, this function for a specified period of time would subtract player's HP, eg for every 3 seconds. I guess it should be done in the Update function to access gameTime, unfortunately, I have no idea how to do it.
public override Stats Attack()
{
attack = true;
return new Stats(0, -stats.Damage, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
public override void Update(GameTime gameTime)
{
spriteDirection = Vector2.Zero; // reset input
Move(Direction); // gets the state of my keyborad
float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds; // make movement framerate independant
spriteDirection *= Speed; // add hero's speed to movement
position += (spriteDirection * deltaTime); // adding deltaTime to stabilize movement
totalPosition = new Vector2((int)((BottomBoundingBox.Center.X) / 32.0f), (int)((BottomBoundingBox.Center.Y) / 32.0f));
base.Update(gameTime);
}
I will make it simple, so you need to modify my code to achieve your desire result.
My best guess is that you want to have a special effect when your monsters hit your player.
First, you need to check if the monster actually hits the player (if collision is detected):
if (collision)//if it's true
{
// Apply your special effect if it is better than
// the one currently affecting the target :
if (player.PoisonModifier <= poisonModifier) {
player.PoisonModifier = poisonModifier;
player.ModifierDuration = modifierDuration;
}
//player.setColor(Color.Blue);//change color to blue
player.hitPoints -= Poision.Damage;//or enemy.PoisonDamage or whatever you define here
hit.Expire();//this can be for the arrow or bullet from your enemy or simply just a normal hit
}
In your Player class, you need:
public float ModifierDuration {
get {
return modifierDuration;
}
set {
modifierDuration = value;
modiferCurrentTime = 0;
}
}
Then in Update method of Player class:
// If the modifier has finished,
if (modiferCurrentTime > modifierDuration) {
// reset the modifier.
//stop losing HP code is here
modiferCurrentTime = 0;//set the time to zero
setColor(Color.White);//set back the color of your player
}
count += gameTime.ElapsedGameTime.TotalSeconds;//timer for actions every 3s
if (posionModifier != 0 && modiferCurrentTime <= modifierDuration) {
// Modify the hp of the enemy.
player.setHP(player.getCurrentHP() - posionDamage);
//Or change it to every 3s
//if (count > 3) {
// count = 0;
//DoSubtractHP(player);
//}
// Update the modifier timer.
modiferCurrentTime += (float) gameTime.ElapsedGameTime.TotalSeconds;
setColor(Color.Blue);//change the color to match the special effect
}
Hope this helps!
You need to store the start time, or the last time that the action was carried out. Then during each update compare the elapsed time to the stored time. If 3 seconds have passed then perform the action, store the current time and repeat the process.
I do not know monogame, but if I were doing this in one of my C# applications, I would use a timer, and pass in anything that the timer would need to modify.
There is good info here https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.8 and I stole a bit of code from here and modified it as an example to demonstrate my idea. I extended the System.Timer to allow it to run for a duration and stop itself. You can set the frequency and duration and forget about it. Assuming that you are able to update this information from a timer.
class Program
{
private static FixedDurationTimer aTimer;
static void Main(string[] args)
{
// Create a timer and set a two second interval.
aTimer = new FixedDurationTimer();
aTimer.Interval = 2000;
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
// Start the timer
aTimer.StartWithDuration(TimeSpan.FromSeconds(15));
Console.WriteLine("Press the Enter key to exit the program at any time... ");
Console.ReadLine();
}
private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
FixedDurationTimer timer = source as FixedDurationTimer;
if (timer.Enabled)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
}
public class FixedDurationTimer : System.Timers.Timer
{
public TimeSpan Duration { get; set; }
private Stopwatch _stopwatch;
public void StartWithDuration(TimeSpan duration)
{
Duration = duration;
_stopwatch = new Stopwatch();
Start();
_stopwatch.Start();
}
public FixedDurationTimer()
{
Elapsed += StopWhenDurationIsReached;
}
private void StopWhenDurationIsReached(object sender, ElapsedEventArgs e)
{
if (_stopwatch != null && Duration != null)
{
if (_stopwatch.Elapsed > Duration)
{
Console.WriteLine("Duration has been met, stopping");
Stop();
}
}
}
}
}
You could see examples of how to pass objects into the timer here (#JaredPar's example) How do I pass an object into a timer event?
string theString = ...;
timer.Elapsed += (sender, e) => MyElapsedMethod(sender, e, theString);
static void MyElapsedMethod(object sender, ElapsedEventArgs e, string theString) {
...
}
One way to do this would be to use coroutines. MonoGame does not have built-in support for them like other game engines, but they are not too complicated to implement yourself. You need some knowledge of the yield keyword and enumerators to understand them, but once abstracted away they make your game code way easier to write and understand.
Here's an example of what your gameplay logic would look using a Coroutine system like the one described below:
public void Attack(Enemy enemyAttacking)
{
if (enemyAttacking.Type == "OneParticularEnemy")
{
StartCoroutine(RunDamageOverTimeAttack());
}
}
// This coroutine starts a second coroutine that applies damage over time, it
// then waits 15 seconds before terminating the second coroutine.
public IEnumerator RunDamageOverTimeAttack()
{
var cr = StartCoroutine(ApplyDamageOverTime());
yield return 15000; // in milleseconds (ms), i.e. 15000 ms is 15 seconds
cr.IsFinished = true;
}
// This coroutine applies the damage every 3 seconds until the coroutine is finished
public IEnumerator ApplyDamageOverTime()
{
while (true)
{
ApplyDamageToPlayer();
yield return 3000;
}
}
The code reads very close to the way you described the actual problem you're trying to solve. Now for the coroutine system...
The StartCouroutine method creates a Coroutine class instance and stores it. During the Update step of the game loop you iterate through the coroutines and update them, providing gameTime to calculate when the next step of the method should run. Each step executes the code in the routine until a yield is found OR until the method ends naturally. Once the coroutine is finished you clear them out. This logic looks something like this:
private List<Coroutine> coroutines = new List<Coroutine>();
public Coroutine StartCoroutine(IEnumerator routine)
{
var cr = new Coroutine(routine);
couroutines.Add(cr);
return cr;
}
public void UpdateCoroutines(GameTime gameTime)
{
// copied in case list is modified during coroutine updates
var coroutinesToUpdate = coroutines.ToArray();
foreach (coroutine in coroutinesToUpdate)
coroutine.Update(gameTime);
coroutines.RemoveAll(c => c.IsFinished);
}
public void Update(GameTime gameTime)
{
// normal update logic that would invoke Attack(), then...
UpdateCoroutines(gameTime);
}
A Coroutine class is responsible for tracking the time remaining between steps of the routine, and tracking when the routine is finished. It looks something like this:
public class Coroutine
{
private IEnumerator routine;
private double? wait;
public Coroutine(IEnumerator routine)
{
this.routine = routine;
}
public bool IsFinished { get; set; }
public void Update(GameTime gameTime)
{
if (IsFinished) return;
if (wait.HasValue)
{
var timeRemaining = wait.Value - gameTime.ElapsedGameTime.TotalMilliseconds;
wait = timeRemaining < 0 ? null : timeRemaining;
// If wait has a value we still have time to burn before the
// the next increment, so we return here.
if (wait.HasValue) return;
}
if (!routine.MoveNext())
{
IsFinished= true;
}
else
{
wait = routine.Current as double?;
}
}
}
This may seem considerably more complex than other solutions provided here, and it may be overkill, but Coroutines allow you to forgo tracking a bunch of state in tracking variables, making complex scenarios easier to follow and cleaner to read. For example, here's a arrow spawning strategy I used Coroutines for in Ludum Dare 37. It spawns 3 arrows 600 milleseconds apart with a 3 second wait between them: https://github.com/srakowski/LD37/blob/477cf515d599eba7c4b55c3f57952865d894f741/src/LD37/GameObjects/BurstArrowSpawnBehavior.cs
If you'd like more social proof of the value of Coroutines take a look at Unity. Unity is one of the more popular game engines, and it has Coroutine support. They describe a scenario where it is useful in their documentation: https://docs.unity3d.com/Manual/Coroutines.html.
I use this for my game :
Public Async Function DelayTask(Time As Double) As Threading.Tasks.Task
Await Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(Time))
End Function
Converted to C# :
public async System.Threading.Tasks.Task DelayTask(double Time)
{
await System.Threading.Tasks.Task.Delay(TimeSpan.FromSeconds(Time));
}
You would use it like this in an Async Function :
Await DelayTask(1.5);
The number is in seconds, you can change this by changing the TimeSpan.whateverformat.
Considering that you'll have various things that affect your stats maybe you're better off at having an update subroutine in your Stats class that will check a list of effects that are scheduled to update after one point in time.
This would be better for performance than having each effect relying on its own thread.

Wrong number converting int to string c#

I have simple coin counter, in 2d Unity game. But It's count one coin as 2. I think that it's because of wrong converting int to string.
public GameObject coin; // Gameobject with coin
public Text CoinCounter; // Text with counter that shows in game
private float TotalCounter = 0; // Float for counting total amount of picked up coins
{
TotalCounter = Convert.ToInt32((CoinCounter.text)); // Converting text counter to Numbers
}
private void Update()
{
TotalCounter = Convert.ToInt32((CoinCounter.text)); // Updating Counter evry frame update
Debug.Log(TotalCounter); // Showing Counter in Console
}
private void OnTriggerEnter2D(Collider2D collision)
{
TotalCounter = (TotalCounter + 1); // adding 1 to total amount when player touching coin
CoinCounter.text = TotalCounter.ToString(); // Converting to Text, and showing up in UI
coin.SetActive(false); // Hiding coin
}
So, in Debug Log it's showing right Total amount, but in UI, It's Showing wrong number. As example, When Total Amount is 1 it's showing 2 etc.
It's better to write your convertor code into the trigger void , after that check it ; this might be happened because of update function, try like that and check again: `
public GameObject coin;
public Text CoinCounter;
private float TotalCounter = 0;
private void Update()
{}
private void OnTriggerEnter2D(Collider2D collision)
{
TotalCounter = (TotalCounter + 1);
Debug.Log(TotalCounter);
CoinCounter.text = TotalCounter.ToString();
Debug.Log(CoinCounter.text);
coin.SetActive(false);
}
`
You don't have to do it in Update but only when you actually change it.
The method you are looking for is probably int.TryParse
you should use int for amounts (unless will you have values like 1.5 coins later)
Than you execute your code everytime it collides ... with anything. You should only collide with a coin instead. Either use tags or compare with the referenced value in your case
public GameObject Coin; // Gameobject with coin
public Text CoinCounter; // Text with counter that shows in game
private int _totalCounter = 0; // Int for counting total amount of picked up coins
// I guess it's supposed to be Start here
void Start()
{
// Converting text counter to Numbers
int.TryParse(CoinCounter.text, out _totalCounter);
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject != Coin) return;
// later this should probably rather be
//if(collision.gameObject.tag != "Coin") return
_totalCounter += 1; // adding 1 to total amount when player touching coin
CoinCounter.text = _totalCounter.ToString(); // Converting to Text, and showing up in UI
Coin.SetActive(false); // Hiding coin
// later this should probably rather be
//collision.gameObject.SetActive(false);
}
Problem was not in converting, trigger worked twice. Need check if the coin is enabled before disabling it and adding to the coin counter. Eg:
if (coin.activeSelf)
{
coin.SetActive(false);
Debug.Log("Object is not active ");
TotalCounter += 1;
Debug.Log("Total Counter + :" + TotalCounter);
CoinCounter.text = TotalCounter.ToString();
Debug.Log("Text after +:" + CoinCounter.text);
}

Calculating the frame-rate in a Unity scene

I'm making a project with Augmented Reality, using Unity and Vuforia extensions. I'm new to C#, but I was looking for a method similar to ARToolKit's getFrame(), and I'm really not finding anything.
My questions are:
Is it necessary that I can calculate the frame-rate that my scene is operating at?
Which scene object should i use to track the frame-rate?
Thats as simple as:
public float avgFrameRate;
public void Update()
{
avgFrameRate = Time.frameCount / Time.time;
}
Put this code in any MonoBehaviour and attatch it to any GameObject in the scene hierarchy.
Please note: this will only give you an average frame-rate. For a more current frame-rate, other answers have addressed effective ways of accomplishing that.
None of the answers here consider the fact that the timescale can be modified in Unity and if it is, all the above approaches will be incorrect. This is because Time.Delta time is influenced by the timescale.
As such, you need to use Time.unscaledDeltaTime:
int fps = 0;
void Update () {
fps = (int)(1f / Time.unscaledDeltaTime);
}
You should look at Time.smoothDeltaTime. This returns a smoothed Time.deltaTime value which you can use instead of having to smooth it yourself using one of the techniques mentioned in other answers.
You will want something like a timer that tracks the time, and how long it took to update the screen, and extrapolates from that how many frames are drawn in a second.
I am fairly rusty with Unity, but I believe something like 1/Time.deltaTime should give you what you want.
So you'd have something like
public void Update()
{
framerateThisFrame = 1/Time.deltaTime;
}
Next you would have to decide how often to change the displayed FPS, since framerateThisFrame can change a lot during every frame. You might want to change it every two seconds for example.
EDIT
An improvement you might want to make is something like storing the past n frames, and use an average to calculate the FPS, then display it. So you could end up with something like:
public int Granularity = 5; // how many frames to wait until you re-calculate the FPS
List<double> times;
int Counter = 5;
public void Start ()
{
times = new List<double>();
}
public void Update ()
{
if (counter <= 0)
{
CalcFPS ();
counter = Granularity;
}
times.Add (Time.deltaTime);
counter--;
}
public void CalcFPS ()
{
double sum = 0;
foreach (double F in times)
{
sum += F;
}
double average = sum / times.Count;
double fps = 1/average;
// update a GUIText or something
}
EDIT
You might even multiply the frame time by Time.timeScale, if you want to be consistent while you apply slow-down/time altering effects.
Since the framerate can vary constantly, it will change many times during a given second. I've used the following recommended approach to get the current framerate. Just put it in a new script and add it to a new, empty game object in your scene.
float deltaTime = 0f;
void Update() {
deltaTime += (Time.deltaTime - deltaTime) * .1f;
}
Source, including display method: http://wiki.unity3d.com/index.php?title=FramesPerSecond
IEnumerator FramesPerSecond()
{
while (true)
{
yield return new WaitForSeconds(1);
Debug.LogFormat("Fps {0}", Time.frameCount/Time.time);
}
}
private void Start()
{
StartCoroutine(FramesPerSecond());
}

Categories