Search Unity

Question Trying to trigger animation with a collision with no luck Help Please!

Discussion in '2D' started by BevvyofFun, Oct 27, 2020.

  1. BevvyofFun

    BevvyofFun

    Joined:
    Aug 19, 2020
    Posts:
    27
    Here's the code I have been using, although, honestly, I have tried a lot of variations with no luck. The code causes no errors but simply doesn't trigger any animation.

    Help!


    Code (CSharp):
    1. Animator animator;
    2. bool nSand;
    3.  
    4. void Start()
    5. {
    6. animator = gameObject.GetComponent<Animator>();
    7. nSand = false;
    8. }
    9.  
    10. void Update()
    11. {
    12. void OnCollisionEnter2D(Collision2D other)
    13.  
    14.     {
    15.     LandonController player = other.gameObject.GetComponent<LandonController >();
    16.     if (player != null)
    17.     {
    18.     nSand = true;
    19.     animator.SetTrigger("Sand");
    20.     }
    21.     else
    22.     {
    23.     nSand = false;
    24.     animator.SetTrigger("Idle");
    25.    
    26.    
    27.    
    28.    
    29.     }
    30.     }
    31.     }
    32.  
     
  2. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,464
    Throw in some Debug.Logs to see if it is even calling. Also, for OnCollisionEnter2D you need to make sure both objects have a 2D collider and one of them needs a Rigidbody2D.
     
    BevvyofFun likes this.
  3. BevvyofFun

    BevvyofFun

    Joined:
    Aug 19, 2020
    Posts:
    27
    Yes, both have 2D colliders and RigidBody2D. I did put in Debug.Log and it did not register at all.
     
  4. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,464
    Oh, it looks like you put OnCollisionEnter2D inside your Update function. You need to have it as its own function outside of the Update { }. Try that and see if your Debug.Logs get called.
     
    BevvyofFun likes this.
  5. BevvyofFun

    BevvyofFun

    Joined:
    Aug 19, 2020
    Posts:
    27
    Thank you so much!!! That finally worked!!!
     
    Cornysam likes this.