Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I want to make my coin dissapear when my player collides with it but code doesn't work

I just started coding so i still have so much to learn. Unity doesn’t give any error when I play the game but also nothing happenes when the player touches the gold. I want the gold to dissapear when the playes touches it but I don’t know why it doesn’t work. (collision part is the last part)

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

public class Player : MonoBehaviour
{

    private Rigidbody2D myRigidbody;
    private Animator anim;

    [SerializeField]
    private int speed;
    private bool lookright;


     void Start()
    {
        myRigidbody = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        
        lookright = true;
    }

    
    void Update()
    {

        float horizontal = Input.GetAxis("Horizontal");
        movements(horizontal);
        changedirection(horizontal);

    }
    private void movements (float horizontal)
    {
        anim.SetFloat ("Walk", Mathf.Abs(horizontal));
        myRigidbody.velocity = new Vector2 (horizontal*speed, myRigidbody.velocity.y);

    }
    private void changedirection(float horizontal)
    {

        if (horizontal > 0 && !lookright || horizontal < 0 && lookright)
        {
            lookright = !lookright;
            Vector3 direction = transform.localScale;
            direction.x *= -1;
            transform.localScale = direction;
        }

    }

    void OnCollisionEnter2D(Collision2D other)
    {

        if (other.gameObject.tag == "gold")
        {
            other.gameObject.SetActive(false);
        }
        
    } }

This is the Unity inspector of the gold

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

OnCollisionEnter2D(Collision collision) won’t fire when you have its IsTrigger set to true. Change it to OnTriggerEnter2D(Collider2D collider) and it will work.

Take a look at the documentation for colliders.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading