0
\$\begingroup\$

I my game, I am trying to create a door/loading zone system, in which a GameObject has several loading zones as children, each with triggers as components. Also attached to each of the loading zones is a script that gives details for where it leads. What is supposed to happen is, when the player touches any of the loading zones, a script on the parent GameObject checks to see which of the loading zones was entered, in order to figure out to which other loading zone the player should be taken to. However, I am having trouble figuring out how to detect which of the loading zones was touched. This is my code so far:

private void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.name == "Player")
        {
            EnteredDoor = Collision2D.otherCollider;

            Debug.Log("enter door");

            Player.controls.Disable();
            FadeBlack();

            StartCoroutine(EnterDoor());
        }
    }

Most everything seems to be working, except that, when writing Collision2D.otherCollider, an error appears, saying that "CS0120: An object reference is required for the nonstatic field, method, or property 'Collision2D.otherCollider'". Does anyone know how I might go about clearing this error, or potentially an alternative way to figure out which of the object's colliders was touched during the collision?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$
EnteredDoor = Collision2D.otherCollider;

Collision2D is a class name, when you access its member variables directly using the class name, you are trying to access a static member of that class.

See: Static Classes and Static Class Members (C# Programming Guide)

Maybe this is what you want:

EnteredDoor = collider.otherCollider;

This will cause a new error because otherCollider is a member of Collision2D ,not Collider2D.

So you should use it like this:

private void OnTriggerEnter2D(Collider2D collider)
{
    if (collider.name == "Player")
    {
        EnteredDoor = collider;

        Debug.Log("enter door");

        Player.controls.Disable();
        FadeBlack();

        StartCoroutine(EnterDoor());
    }
}

Or

private void OnCollisionEnter2D(Collision2D col)
{
    var collider = col.otherCollider;
    if (collider.name == "Player")
    {
        EnteredDoor = collider;

        Debug.Log("enter door");

        Player.controls.Disable();
        FadeBlack();

        StartCoroutine(EnterDoor());
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ How does this code detect which of the loading zones the player touched? \$\endgroup\$
    – DMGregory
    Jul 6, 2023 at 10:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .