P
P
Pavel Arutyunov2022-03-25 16:15:42
Unity
Pavel Arutyunov, 2022-03-25 16:15:42

How to enable and disable Collider2D using the OnTriggerEnter2D/OnTriggerExit2D function?

Hello!
I want to make it so that when a player enters / exits the Trigger, Polygon Collider 2D turns on / off, I wrote a script, but error CS1002 pops up in lines 15 and 23, please tell me what this is connected with and how to fix it thanks in advance!
The Script itself:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TRUEFALSE : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Player")
        {
            Collider 2D = gameObject.GetComponent<PolygonCollider2D>;  /// CS1002
            PolygonCollider2D = false;
        }
    }
    void OnTriggerExit2D(Collider2D other)
    {
        if (other.tag == "Player")
        {
            Collider 2D = gameObject.GetComponent<PolygonCollider2D>; ///CS1002
            PolygonCollider2D = true;
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bogdan Erolskiy, 2022-03-25
@GLaWA_RaKoB

It's quite simple:
Consider this line

Collider 2D = gameObject.GetComponent<PolygonCollider2D>;  /// CS1002

It contains the following errors:
  • A variable name cannot start with a number. Variable name 2Ddoes not match
  • type PolygonCollider2Dis not convertible to type Collider. Specify the same type of the returned component that you want to get by the GetComponent. In this case, thisPolygonCollider2D
  • you didn't add parentheses at the end of the method callGetComponent

There are also errors in other lines, but I do not want to comment on them in detail - there is too much to explain, there is enough information on the Internet and books.
Finally, replace the current lines:
Collider 2D = gameObject.GetComponent<PolygonCollider2D>; ///CS1002
PolygonCollider2D = true;

To this one:
other.enabled = true;
I highly recommend turning to the Unity and C# tutorials, after reading the first chapters of any normal tutorial, these errors should not occur.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question