-1

I have a character with BoxCollider2D and Animator components. I need to change a physic material's friction dynamically so I use the next function:

private void ChangeFriction(float friction)
{
    boxCollider.sharedMaterial.friction = friction;
    boxCollider.enabled = false; // The friction won't be changed if I won't reset the collider
    boxCollider.enabled = true;
}

The problem is that after an execution of this function the walking animation isn't played anymore totally. If I comment two last lines then all works perfectly but the friction doesn't change, just like To be or not to be.

How can I fix this issue?

Denis Sologub
  • 7,277
  • 11
  • 56
  • 123
  • Is there a particular reason why you used `sharedMaterial` instead of `material`? Is this collider collider of your player or the object player moves on? – Ali Kanat Jan 28 '19 at 08:58
  • @AliKanat There isn't property `material`. – Denis Sologub Jan 29 '19 at 10:30
  • How come? Unity documentation says Collider has [both](https://docs.unity3d.com/ScriptReference/Collider-material.html) of [them](https://docs.unity3d.com/ScriptReference/Collider-sharedMaterial.html) – Ali Kanat Jan 29 '19 at 10:36
  • 1
    Ah my bad you have a 2D box collider i now realized. i think there is another issue in your code because i try it now and i do not have to enable and disable my collider to change the friction. How do you access this `boxCollider`? – Ali Kanat Jan 29 '19 at 10:52
  • @AliKanat, as always `GetComponent()` inside `Awake()` method. – Denis Sologub Jan 30 '19 at 10:28
  • @AliKanat, can you show your code, pls? I really have troubles with it. – Denis Sologub Jan 30 '19 at 10:32

1 Answers1

0

I have been using this piece of code to access friction and change it and it works without enabling and disabling the collider. I can see it changes in Editor as well.

private Collider2D col;
void Start () {
    col = gameObject.GetComponent<Collider2D>();

}

void Update () {
    if(Input.GetKeyDown(KeyCode.Mouse0))
    {
        col.sharedMaterial.friction = 1;

    }

    if (Input.GetKeyDown(KeyCode.Mouse1))
    {
        col.sharedMaterial.friction = 0.5f;
    }
    Debug.Log(col.sharedMaterial.friction);
}
Ali Kanat
  • 1,888
  • 3
  • 13
  • 23