Checking an Animator bool when colliding with it

Hi,

I am trying to figure out whether the animator parameter has been set to true when the player collides with an object. I have the following code on a script with the player. However, this is checking the animator for the player. How can I check the collided objects’s parameters?

    void OnTriggerEnter2D(Collider2D collision)
    {
       
        if(anim.GetBool(Tags.STITCH_ANIMATION))
        {
            return;
        }
        else
        {
            totalstitches++;
        }
       
    }

Thanks

From the collision variable you can get the Collider, and from that you can use GetComponent() to retrieve the animator on that GameObject.

BEWARE that it may not be present on that GameObject in all cases, so it is up to you to guard the usage of anything you get back from GetComponent() to ensure it is not null.

So easy :wink:
if(collision.GetComponent().GetBool(Tags.STITCH_ANIMATION))

Thanks

Be sure you read the second part of my post too or else your game will crash and you’ll need this post:

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

You are hereby warned twice now.

Just for my own clarification, checking for the presence could be done like this?

if(collision.GetComponent<Animator>()) {
     // exists, now check the bool
}
else {
    // maybe do something else if no Animator component, maybe do nothing
}

Yes, I would just use a local variable though

var animator = GetComponent<Animator>();
if (animator)
{
   // go to town with your properties
}

EDIT: for the C# enthusiasts out there, AFAIK you may NOT use the null coalescing operator in lieu of the above if statement because Component derives from UnityEngine.Object and hence has that bool override.

1 Like