Call a methode "recursively"?

I’m building a simple 2D platformer in C#.

I have multiple characters in the game. And when they are stacked on top of each other, I want the ones on the top to move like the one on the bottom (like in thomas was a lone game).

So I have this code for each characters that almost work:

void OnTriggerEnter2D(Collider2D other) {
    // Store the payer above the current one in "playerAbove" variable
	if (other.gameObject.transform.position.y > transform.position.y) {
		isPlayerAbove = true;
		playerAbove = other.gameObject;
	}
}

void OnTriggerExit2D(Collider2D other) {
	if (other.gameObject.transform.position.y > transform.position.y) 
		isPlayerAbove = false;
}

// Gets called if the current player is moving right or left 
public void MovePlayerAbove() {
	if (isPlayerAbove) {
        // Move the player above by the sam velocity, so they stay stacked
		playerAbove.rigidbody2D.velocity = rigidbody2D.velocity;

        // Try to move the player above the one above (if there is any)
		playerAbove.MovePlayerAbove(); // This is the line that doesn't work
	}
}

It works if I comment the last line and I have only 2 characters on top of each other. When I add the last line, I just get an error message that MovePlayerAbove doesn’t exist. How to fix that?

Example: I have 3 players on top of each other. If the bottom one moves, then he will call MovePlayerAbove to move the middle player, who will then call MovePlayerAbove again to move the top player. This way all 3 players will move exactly together.

Thanks!

Your playerAbove is the game object and since the game object does not have any method such as MovePlayerAbove() you are getting that error.

As your function is inside the same class you can directly call it like:

MovePlayerAbove();

Instead of

playerAbove.MovePlayerAbove();

But just beware that it will go into an infinity loop calling function like that so you also need to set a condition before you call it like:

if(condition satisfied)
{
MovePlayerAbove();
}

so that it doesn’t get into an infinite loop.

Alternatively, instead of your MovePlayerAbove method, you could simply make the bottom object the parent of the object on top. This still works in cases when three objects or more are stacked

void OnTriggerEnter2D(Collider2D other) {
    if(other.gameObject.transform.position.y > transform.position.y)
    {
       other.transform.parent = gameObject.transform;
       isPlayerAbove = true;
    }
}
     
void OnTriggerExit2D(Collider2D other) {
    if(other.gameObject.transform.position.y > transform.position.y)
    {
       other.transform.parent = null;
       isPlayerAbove = false;
    }

Also, consider using a downwards raycast to detect characters beneath others, as opposed to comparing y values, as your code would still execute if one of your characters jumped at the side of another, as its y value is still higher.