- Home /
Having code fire once in update function?
Hi, I'm a Unity noob (still learning) and I'm trying to build a basic space invaders clone to get my head around how everything works. Here is my enemy movement script, it's working for left and right movement, but when I fire the jump variable, they either fly off the screen (because it keeps firing the jump code) or doesn't jump at all (if I turn the variable off after it fires, the entire variable never even fires once).
I've tried Invoke instead, and placed the jump code in a function, but then I couldn't work out how to have it affect all of the enemies (as it would just work on the one that triggered the jump scenario). I was playing with GameObject.FindGameObjectsWithTag (since all my enemies are tagged "Enemy") but couldn't work out how to then take that information and use it to move all the enemies down (sigh).
I've searched everywhere, so I'm hoping somebody can answer this simple question for me?
function Update () {
var amtToMove = enemySpeed * Time.deltaTime;
if (startMove==true)
{
transform.Translate(Vector3.forward*amtToMove);
}
if (transform.position.z >= 63)
{
startMove = false;
JumpOn=true;
hitRIGHT = true;
}
if(transform.position.z <= -61)
{
hitRIGHT = false;
JumpOn=true;
hitLEFT = true;
}
if(hitRIGHT==true)
{
hitLEFT=false;
transform.Translate(Vector3.back*amtToMove);
JumpOn=false;
}
if(hitLEFT==true)
{
hitRIGHT=false;
transform.Translate(Vector3.forward*amtToMove);
JumpOn=false;
}
if (JumpOn==true)
{
transform.position.y -=20;
}
Answer by Linus · Jul 09, 2012 at 10:55 AM
if (JumpOn==true)
{
transform.position.y -=20;
JumpOn = false;
}
Also make sure that the conditions for jumping are not true again for the next frame.
Sorry, I don't think I was clear. This is for the automatic movement of the enemy. I can't have the enemy movement linked to player control. The 'jump' is when the enemies in space invaders hit the side of the screen, and move down.
oops, you where not unclear, I was just not paying attention. I will update or remove my answer
All good! I actually tried the updated code, and it refused to work. It results in the enemies not jumping at all, strangely enough. I then got the impression you couldn't turn a variable to false if you were doing it within the variable itself, which is why the code became the way it is.
Hmm, i thought the revision history was fixed... it seems not... I still just see the last revision.
Have a look at http://answers.unity3d.com/questions/24257/how-do-i-find-all-game-objects-with-the-same-name.html
for(var thisEnemy : GameObject in GameObject.FindGameObjectsWithTag("Enemy")) { thisEnemy.transform.position.y -=20; thisEnemy.transform.position.y = JumpOn = false; }
Answer by darkironphoenix · Jul 09, 2012 at 01:03 PM
You could fire a function from within your update if's.
if (JumpOn==true)
{
JumpFunction();
}
And then have the code in the function.
function JumpFunction(){
transform.position.y -=20;
JumpOn = false;
}