My if-statement is not being read

Hello.
I’m working on a script to generate platforms infinitely. I got it started but ran into an issue when I checked for the instantiated platform’s position.

First off, here is the code:

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class Generation : MonoBehaviour
{
    [SerializeField] GameObject[] GroundLevels;
    [SerializeField] GameObject startPlatform;
    [SerializeField] GameObject lastInstantiatedPlatform;
   
    public float generationSpeed;
   

    private List<GameObject> instantiatedLevels;


    void Start()
    {
        instantiatedLevels = new List<GameObject>();
       
        //Create the starting platform (The first platform that will be instantaited
        lastInstantiatedPlatform = Instantiate(startPlatform, transform.position, Quaternion.identity);
        instantiatedLevels.Add(lastInstantiatedPlatform);

    }


    void Update()
    {

        foreach (GameObject level in instantiatedLevels)
        {
            level.transform.Translate(Vector3.back * generationSpeed);
        }


        if (lastInstantiatedPlatform.transform.position.z == -5)
        {
            print("next!");
        }
        print(lastInstantiatedPlatform.transform.position.z);
    }

    GameObject CreateNewPlatform()
    {
        GameObject nextPlatform = Instantiate(GroundLevels[Random.Range(0, GroundLevels.Length)], transform.position, Quaternion.identity);
        instantiatedLevels.Add(nextPlatform);
        return nextPlatform;
       
    }
}

I wanted to spawn the platforms when the lastInstantiatedPlatform.transform.position.z was equal to its negative scale in the z-axis. However, when this didn’t work, I just changed it to print “next!” when its position.z equaled -5.

When this didn’t work, I inserted the print(lastInstantiatedPlatform.transform.position.z); to make sure that I was actually getting the z position. And I was! -5 was printed, and “next!” was not printed.

You’re running into floating point precision issues. A floating point number is very rarely ever going to be exactly equal to a whole number. You probably should just check if it’s greater than or less than a value, depending on what you’re doing.

Also how hard is it to post scripting questions in the scripting subforum?

1 Like

Thank you, this works

You can also use the Unity - Scripting API: Mathf.Approximately method if you want to check two floating point numbers to see if they are similar (within Unity - Scripting API: Mathf.Epsilon of each other).
If the variance between the floating points is more than the arbitrary Epsilon value, then you would be better going with spiney’s option to check greater/less than two values.