0
\$\begingroup\$

I have been banging my head against this one for a while. I am trying to implement a pickup mechanic, using OnTriggerEnter2D, however I cannot get it to work, my player just runs past the coin.

Code:

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using TMPro;
using UnityEngine;

public class gemMovement : MonoBehaviour
{
    // variables
    private Vector2 startPosition;
    private Vector2 endPosition;
    private int speed = 4;
    private float maxDistance = 0.15f;
    private int count = 0;
    public TextMeshProUGUI countText;

    private void Start()
    {
        startPosition = transform.position;
        endPosition = transform.position;
    }

    private void Update()
    {
        endPosition.y = startPosition.y + (maxDistance * Mathf.Sin(Time.time * speed));
        transform.position = endPosition;
    }

    void SetCountText()
    {
        countText.text = "Count: " + count.ToString();
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Pickup"))
        {
            Debug.Log("Pickup");

            other.gameObject.SetActive(false);
            count++;

            SetCountText();
        }
    }
}

Gem Component View

Player Component View

A little bit of help would be very much appreciated, thank you.

\$\endgroup\$
2
  • \$\begingroup\$ Post a screenshot of the inspector for the player as well. \$\endgroup\$
    – Kevin
    Commented Nov 2, 2023 at 18:24
  • \$\begingroup\$ I have just uploaded the Player component view. \$\endgroup\$ Commented Nov 2, 2023 at 18:35

2 Answers 2

2
\$\begingroup\$

You said that you used OnTriggerEnter2D() in your description, but your code actually uses OnTriggerEnter(), which isn't compatible with 2D colliders.

\$\endgroup\$
2
  • \$\begingroup\$ Remember to change the function parameter from Collider to Collider2D as well. The entire function signature needs to exactly match what Unity looks for, or your code will not be invoked. \$\endgroup\$
    – DMGregory
    Commented Nov 2, 2023 at 19:59
  • \$\begingroup\$ Hi guys, I have changed it to OnTriggerEnter2D and changed the Collider2D, I am still having the same results. I tried with OnCollisionEnter2D as well without a trigger, but no luck :(. Any ideas? \$\endgroup\$ Commented Nov 2, 2023 at 20:23
2
\$\begingroup\$

This seems like a rather easy fix. On your gemMovement you check if the other tag is Pickup but if a collision happens, this is going to be the player. So either the method should go as it is on the player or you need to check if the coin is colliding with the player.

You probably do not want to deactivate the player on collision as well.

\$\endgroup\$
1
  • \$\begingroup\$ Thank you, it worked :)! \$\endgroup\$ Commented Nov 3, 2023 at 8:18

You must log in to answer this question.

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