If the z-axis increases add 1 to variable in unity

Viewed 73

I have a game where the score system is linked directly to the z-axis but I want to know how to make it so if the z-axis increases that it will ad one to a variable and if it decreases it will decrease the variable.

2 Answers

You'd want to check on each Update the Z-axis of the GameObject, and then store it so it can be compared in the next Update:

float zAxis = transform.position.z;
unsigned int score = 0;

void Update()
{
    if (zAxis > transform.position.z)
        score++;
    else if (zAxis < transform.position.z && score > 0)
        score--;    
    zAxis = transform.position.z;
}

The above assumes this script would be placed on the GameObject in question (if not, you'll need to get a reference to it), and the score variable should be unsigned if it's not allowed to go below 0 (unsigned integers can only be positive numbers).

Assuming this script is attached to the object whose z-coordinate you are checking. You can update the score variable given the last z-coord:

private int score = 0;
private float lastZ = transform.position.z;

void Update() {

    if (transform.position.z < lastZ) {
        score--;
    }
    else if (transform.position.z > lastZ) {
        score++;
    }

    lastZ = transform.position.z;

}
Related