Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Respawning Player

Discussion in '2D' started by gotnull, Jul 6, 2015.

  1. gotnull

    gotnull

    Joined:
    Jun 7, 2015
    Posts:
    7
    I have a relatively easy question on how to position the Y-axis on a game object and how to wait for an animation to finish before my player is re-spawned to a checkpoint.

    This is the code I have so far:

    public void RespawnPlayer ()
    {
    body2d.gravityScale = 0f;

    var pos = player.transform.position;
    pos.y = currentCheckpoint.transform.position.y - 0.068f;
    pos.x = currentCheckpoint.transform.position.x;
    player.transform.position = pos;

    player.warping = true;
    player.warpStarted = false;
    }

    This is called from a coroutine in an `Update()`:

    void Update ()
    {
    if (!warping) {
    if (collisionState.standing) {
    ChangeAnimationState (0);
    }
    } else if (!warpStarted) {
    StartCoroutine (Warp ());
    warpStarted = true;
    }
    }

    IEnumerator Warp ()
    {
    Debug.Log ("Should only execute once.");

    ChangeAnimationState (5); // Ideally I'd like to get the total time of the animation and set the WaitForSeconds with that time.
    yield return new WaitForSeconds (1);
    body2d.gravityScale = 5f;
    warping = false;
    }

    void ChangeAnimationState (int value)
    {
    animator.SetInteger ("AnimState", value);
    }

    The problem I'm facing is that I see for a split second that the the position of the sprite is in the correct position but then straight away changes to the position of the `currentCheckpoint` in the `RespawnPlayer()` method.

    Is there a better way of achieving what I'm after?
     
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    897
    You can add events to your animation. You'll find them in the animation window, it looks like a wedge with a plus sign. Once the animation reaches an event, the assigned method will be called.
     
    theANMATOR2b and gotnull like this.
  3. gotnull

    gotnull

    Joined:
    Jun 7, 2015
    Posts:
    7
    Thanks for the reply. Appreciate it. I'll look into the events.