Gravestone - Animator's state stops changing

In this lecture @Rick_Davidson creates a placeholder method for adding the triggering of animation for the Gravestone;

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gravestone : MonoBehaviour
{
    private void OnTriggerStay2D(Collider2D otherCollider)
    {
        Attacker attacker = otherCollider.GetComponent<Attacker>();

        if(attacker)
        {
            // TODO Add some sort of animation
        }
    }
}

…it’s use isn’t covered in the remainder of the section, however, if you expand upon this yourself and create the animation, or, perhaps tie the wobble animation in so that it only occurs when an attacker makes contact with the gravestone, be aware of the following.

A Rigidbody2D has a performance optimisation which puts it to sleep. It will be put to sleep after a specific amount of time has passed after the Rigidbody2D has stopped moving. Whilst it is asleep it will not take part in the physics simulation, meaning it will not be detected during collisions.

Why does this matter?

If you have a Lizard attacker which stops at a Gravestone, it will stop moving, if it’s Rigidbody2D goes to sleep then the above method OnTriggerStay2D will stop receiving messages and as such, any code within this method will stop executing. This could be the code which sets the Animator’s trigger parameter to set the Gravestone to wobble for example.

This is quite subtle and you could lose quite a bit of time trying to work out why your Animator’s state isn’t being triggered, and/or waste time looking at various animation-related settings/configuration.

There are several ways in which you can resolve this;

  • increase the duration of the Time to Sleep property within the Project Settings / Physics 2D;
    image

  • change the Sleeping Mode on the Rigidbody2D component to Never Sleep;
    image

  • programmatically check to see if the Rigidbody2D is asleep and wake it up using IsAwake / IsSleeping and WakeUp methods (see below).

About each option;

  • Changing the Time to Sleep setting will invariably be the least useful, the period of time to set this would need to be based on how much damage the attacker is causing the Gravestone and how much health the Gravestone has. It would be very easy to tweak those values as you play test and forget to change this setting.

  • Setting the Rigidbody2D’s Sleeping Mode to Never Sleep is the quickest and easiest fix, however, in doing so you completely lose the benefits that the optimisation was providing. Measuring these benefits, however, could be more challenging and take more time than it’s worth.

  • Programmatically waking the Rigidbody2D when necessary can prevent the issue whilst still allowing the performance optimisation to take place.

Of the three options, I would recommend the last.

I hope the above is of use :slight_smile:


See also;

2 Likes

Privacy & Terms