C# How to trigger event at certain height (y axis)

I am making a 2d infinite runner game, with enemies spawning at specific heights (y axis).

I want a different action to happen when they are destroyed based on their y value.

I have tried:

	if (gameObject.transform.position.y = -2.5f){
		//do stuff
	}

Along with variations where I have removed gameObject, added a second = sign, and used variables in place of floats.

The most common errors I get back are:

error CS1612: Cannot modify a value type return value of `UnityEngine.Transform.position'. Consider storing the value in a temporary variable

error CS0029: Cannot implicitly convert type `float' to `bool'

== is what you need to use for a comparison. = is to set a value and a position cannot be set like that, you’d have to use = new Vector3(0,0,0) if you actually wanted to set it.

if (gameObject.transform.position.y == -2.5f)

That shouldn’t give you an error but it probably also won’t work as it is unlikely that a float will ever exactly equal a value.

You could check the height of the object within a range:

float enemyHeight = gameObject.transform.position.y;

if (enemyHeight < 0 && enemyHeight > -2.5f)
{
    //do stuff
}

Or use approximate values:

float enemyHeight = gameObject.transform.position.y;        
    
if (Mathf.Approximately(enemyHeight, -2.5f))
{
     //do stuff
}

Or round the value so you can compare it directly:

float enemyHeight = Mathf.Round(gameObject.transform.position.y);

if (enemyHeight == 3)
{
     //do stuff
}