Hey, I’m trying to make a counter for a grenade. I use this script
var Timer = 0;
var explosion : GameObject;
function Update ()
{
Timer += Time.deltaTime * 1;
if(Timer >= 3)
{
Instantiate (explosion, transform.position, transform.rotation);
Destroy(gameObject);
}
}
but the timer won’t count upwards. i tried with Timer -= 1 * Time.deltaTime and that counted down each frame and not each second like it should. how can I make it count seconds so the grenade wont blast earlier the faster computer you have.
you do know multiplying 1 * x = x. It’s the identity theorem. So that’s just a superfluous operation.
as for the rest, your code looks like it should work. The grenade (gameObject) should only last for 3 seconds before being destroyed and replaced by an explosion.
The only problem I see is that Timer is probably defaulting to ‘int’ (I’m not certain as I don’t write UnityScript). Try saying:
var Timer:float = 0.0f;
where you declare your var.
If it’s just an int though. An integer X plus a very small number like 1/60th (the average deltaTime) will result in just X. Because integers can’t represent fractions, and a fractional value will just be rounded.
Yeah, always avoid having code like this in your Update if not REALLY needed. First price will be to make your own little timer script, attach it to the game object and let it destroy itself after doing it’s work. as it is at the mement, that timer will keep on running and add un needed performance bottleneck. It might not be much, but at the end every bit counts.
I avoid string at all costs except for when representing actual text.
For instance when it comes to animations. I create an enum of the animation names and pass those around. It just requires writing a couple extension methods for Animation that retrieve the string name based on the enum and passes through via that. This way the only area prone to error is this set of functions that convert from enum to string.
as I said, “This way the only area prone to error is this set of functions that convert from enum to string”. That’s not a speed thing, that’s a standards thing.