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. Dismiss Notice

Shield Mechanic.

Discussion in 'Scripting' started by EdwardMollan, May 10, 2022.

  1. EdwardMollan

    EdwardMollan

    Joined:
    May 4, 2022
    Posts:
    9
    I have a top down 2D game and I want to add a shield mechanic where the player holds the left shift and the shield animation shows up blocking all enemies attacks and when the player lets go the shield animation stops. What's the best way to do this I have a tiny bit of code but I believe I messed it up quite heavily.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Blocking : MonoBehaviour
    6. {
    7.     Animator animator;
    8.     CircleCollider2D Collider;
    9.     void Start()
    10.     {
    11.         Collider = GetComponent<CircleCollider2D>();
    12.     }
    13.  
    14.     // Update is called once per frame
    15.     void Update()
    16.     {
    17.         if (Input.GetKeyDown(KeyCode.LeftShift))
    18.         {
    19.             Collider.isTrigger = true;
    20.             Debug.Log(Collider.isTrigger);
    21.             animator.SetBool("Block", true);
    22.  
    23.         }
    24.         if (Input.GetKeyUp(KeyCode.LeftShift))
    25.         {
    26.             Collider.isTrigger = false;
    27.             Debug.Log(Collider.isTrigger);
    28.             animator.SetBool("Block", false);
    29.         }
    30.     }
    31. }
     
  2. SkrenZz

    SkrenZz

    Joined:
    Apr 11, 2020
    Posts:
    26
    I think you forgot to assign your animator variable. I don't see any other problem with your code (except you may want to enable and disable the CircleCollider2D instead of switching isTrigger, if it has no other purposes).
    If things are still not working I would make sure your Animator Tree is set up correctly.
     
    Bunny83 likes this.