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
CodePudding user response:
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.