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

I just need to change one Animation Layers's weight from 0 to 1 at the press of a button

Discussion in 'Scripting' started by igotsuss, Feb 18, 2021.

  1. igotsuss

    igotsuss

    Joined:
    Feb 15, 2021
    Posts:
    5
    I'm thinking it should be simple...but I'm just an artist and I need this stuff just to help build my portfolio, so what I getting so far is having the character getting into the Attack Layer but never coming out. I need to press "q" for having the Attack Layer fully weighted. It does work fine with GetKey, but I want it to stay that way until I press "q" again to get him out. Could someone please give me a hint at least. Cheers!


    // Start is called before the first frame update
    void Start()
    {
    any_controller = GetComponent<Animator>();
    any_controller.SetLayerWeight(0, 1);
    }

    // Update is called once per frame
    void Update()
    {

    if (Input.GetKeyDown("q"))
    {
    any_controller.SetLayerWeight( any_controller.GetLayerIndex("Attack Layer"), 1);
    }
    else if (!Input.GetKeyDown("q"))
    {
    any_controller.SetLayerWeight( any_controller.GetLayerIndex("Attack Layer"), 0);
    }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,762
    If the above is the correct way to set the layer (I don't know this but I'll take your word), all you need to change is to make a bool in your class (not in your method!):

    Code (csharp):
    1. private bool InAttackMode;
    then in your Update():

    Code (csharp):
    1. // toggle attack mode
    2. if (Input.GetKeyDown("q"))
    3. {
    4.   InAttackMode = !InAttackMode;
    5. }
    6.  
    7. // now check and act on it:
    8.  
    9. if (InAttackMode)
    10. {
    11.   any_controller.SetLayerWeight( any_controller.GetLayerIndex("Attack Layer"), 1);
    12. }
    13. else
    14. {
    15.   any_controller.SetLayerWeight( any_controller.GetLayerIndex("Attack Layer"), 0);
    16. }
    See how that flips the bool from true to false, then acts on it separately based on what it is?
     
  3. igotsuss

    igotsuss

    Joined:
    Feb 15, 2021
    Posts:
    5
    It worked perfectly an the way you wrote this, makes sense to me( "writing" code for 4 days now). Thank you so much!!!
     
    Kurt-Dekker likes this.