Search Unity

How to enable a component (PolygonCollider2d) On click?

Discussion in '2D' started by UltraConstructor, Feb 20, 2021.

  1. UltraConstructor

    UltraConstructor

    Joined:
    Feb 9, 2021
    Posts:
    1
    I am a VERY new coder. I wrote this under a script in the object which I would like to have the component enabled in.

    void OnMouseDown()
    {
    PolygonCollider2D.enabled = true;
    }

    I get the error "An object reference is required for the non-static field, method, or property Behaviour.enabled"
     
  2. MarekUnity

    MarekUnity

    Unity Technologies

    Joined:
    Jan 6, 2017
    Posts:
    207
    Hi @UltraConstructor, welcome to the 2D forums. It looks like you are trying to access the field as if it was static. What you can do instead is create a field to reference your polygon collider and call enable using that reference:
    Code (CSharp):
    1. public PolygonCollider2D m_PolygonCollider2D;
    2.  
    3. void OnMouseDown()
    4. {
    5.     m_PolygonCollider2D.enabled = true;
    6. }
    make sure that you assign correct PolygonCollider2D in the inspector to make it work.

    Also, to make it easier for other users to read your code, make sure that you tag it properly. You ca refer to this post:
    https://forum.unity.com/threads/using-code-tags-properly.143875/
    There is also a great beginner's tutorial on C# scripting tutorials on our Lean page.