Destroy gameobject in Unity - unity3d

I want the enemy to be destroyed when the player touches the heart. what's wrong with my code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour
{
public GameObject player;
public float speed;
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, player.transform.position,
speed * Time.deltaTime);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (player.gameObject.CompareTag("haret"))
{
Destroy(gameObject);
}
}
}

You haven't provided an error code or anything so I don't have much to go off of ;-;
make sure the tag in the code is the same as the code in the project and put the tag on the heart.
make sure that the player gameobject has been assigned to the enemy.
make sure that the player and the heart both have a 2d collider not set to is trigger

Check your tag spelling. You have a spelling mistake there.

Without an error it is hard to figure out what the problem is. From the looks of it you might have misspelled gameObject.CompareTag("haret") where it should be gameObject.CompareTag("heart") instead.
Also make sure that the script is assigned to the enemy, that you have assigned the player gameObject in the inspector and that you have set the collider of the heart gameObject to isTrigger in the inspector.

Related

How to detect collision between moving rigidbody cube and static empty object?

I am new to unity and working on collision detection.
I have a rigidbody cube and an empty object with a cube mesh. The rigidbody cube moves with arrow keys and the empty object is static. Both have a box collider.
How do I detect collision between this empty object and the rigidbody cube?
I am wondering whether it should be OnCollisionEnter or OnTriggerEnter and how to use the correct command.
Thank you for your help.
First you need to set the box collider component to the cube and to the empty object with cube mesh. Then you can use this code:
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
public PlayerMovement movement;
public GAME_MANAGER GameManager;
private void OnCollisionEnter(Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Obstacle")
{
movement.enabled = false;
}
}
}
Make sure you have set the tag of the obstacle to “Obstacle” and add this script to the player or the cube. Here,
movement.enabled = false;
You can apply you own logic according to your need.
Thanks

Collision system not working. There are no errors, it just wont register that the projectile hit the player

Here is the code in which I was talking about. I can't figure out why my collider isn't working:
using System.Collections.Generic;
using UnityEngine;
public class SphereCollider : MonoBehaviour
{
GameObject obj;
void Awake ()
{
obj = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "Player")
{
obj.GetComponent<Health>().health -= 25;
}
}
}
}
Rather than using the code you have, make sure to change some code. This is what you should change: get rid of the obj variable and the awake function. Then instead of finding the object with that name, use tag. Also get rid of Update(){} and take the OnCollisionEnter(){} out of it.
A few more changes are shown in code:
void OnCollisionEnter(Collision collision){
var obj = collision.GameObject;
if (obj.Tag == “Player”){
obj.GetComponent<Health>().health -= 25;
}
}
This will work as long as: the script is called Health, the variable inside Health is called health, and it is set to a float, and the player’s tag is set to Player.
Not sure if the code pasted in the question is just copied over wrong, but OnCollisionEnter() is its own unique method and should not be nested in Update().
If the player will be colliding with this Sphere object often, it is good to cache a component rather than using GetComponent frequently. However I assume in your case this Sphere will be one of many obstacles, so calling the GetComponent in the collision is fine. The issue with your current code is the gameObject you are colliding with might not have the name exactly spelled as Player, which would make your collision check fail. Caching the object that has the tag of Player is a bit redundant when you can just check it inside of the collision check.
I will use your entire snippet of code so there is no confusion
using System.Collections.Generic;
using UnityEngine;
public class SphereCollider : MonoBehaviour
{
void OnCollisionEnter(Collision col)
{
// compare if the collider's gameObjects tag is equal to our target tag (Player)
if (col.gameObject.tag == "Player")
{
// get the component of Health on our gameObject that we collided with that has the tag of Player
obj.GetComponent<Health>().health -= 25;
}
}
}

Camera follow player around planet

I have a planet and a player moving on it using gravity. I would like to have a camera to follow the player around it. Using the Parent Constraint component works perfectly, but I want to delay the rotation follow, so I have to use a script. I just cannot figure out how to make it follow it around the globe. I either have a camera that completely freaks out, or a camera that sort of follows the player but doesn't move over the planet and always stays in front of it. And often the position following works, but as soon as I add something that changes rotation it only does that. I've tried many different scripts but nothing works. I'm grateful for any help.
EDIT
I'm sorry for not adding an example. At the moment I've tried this script attached to the camera:
public class CameraFollow : MonoBehaviour
{
public GameObject player;
private Vector3 offset;
void Start()
{
offset = transform.position - player.transform.position;
}
void LateUpdate()
{
transform.rotation = Quaternion.Slerp(transform.rotation, player.transform.rotation, 50f * Time.deltaTime);
transform.position = player.transform.position + offset;
}
The camera does mimic the rotation of the player, but the position isn't being follow correctly anymore. It seems mostly stuck in place, moving only very slightly.
In order to have a camera following a GameObject, you need to go to the camera you want following the GameObject, select Add component, write FollowPlayer, press New script, and then press select and add. Edit the script so it contains the following:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowPlayer : MonoBehaviour
{
public Transform player;
public Vector3 offset;
// Update is called once per frame
void Update()
{
transform.position = player.position + offset;
}
}
Then, you will need to drag and drop the GameObject you want the camera to follow, in the "Player" box.
Define the offset of the camera from the GameObject, and your'e good to go.

Unity collision not detected

I'm making a Unity game, in which player should push all "Enemy" object from the plane. So to be able to count the number of fallen objects I want to generally be able to tell when a collision occurred between the red cube and every other cube. The script seems to not detect a collision, how to fix it?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collide : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Enemy")
Destroy(gameObject);
Debug.Log("Hit Occured");
}
}
you need OnCollisionEnter
void OnCollisionEnter(Collision collision){
}
because your colliders aren't triggers.
You need to implement OnCollisionEnter(Collision collision) not OnTriggerEnter(Collider other) or check BoxCollider IsTrigger checkbox
There are 3 things to be checked
1. The OnCollisionEnter should be used in place of OnTriggerEnter
2. isTrigger checkbox should be enabled so that the event is triggered when the both bodies collide with other .
3. The most important thing which no one has mentioned is the tags given to the gameobject or the enemies because we need to define the gameobject that event should be triggered when hit to the specific body because the gameobject contains the collider and can collide to any wall or something so you need to define the tags properly

Collision callback function not called

i am bloody beginner with Unity and i am currently working on a 2D Brawler. The movement works perfectly but my colliders don't do what they should... I want to detect if two GameObjects Collide (Spear and Player2) and if the collide Player2s healthPoints should decrease by Spears AttackDamage.
The names of the GameObjects are also their tags. The Spears Prefab has following configuration: SpriteRendered(Material Sprites-Default), BoxCollider2D(Material None Physics Material 2D, IsTrigger(not activated), UsedByEffector(also not activated) Rigidbody2D(Kinematic, None Material, Simulated(Activated), KinematicContacts(activated), Standard configs for the rest))
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpearCtr : MonoBehaviour {
public Vector2 speed;
public float delay;
Rigidbody2D rb;
void Start ()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = speed;
Destroy(gameObject, delay);
}
void Update ()
{
rb.velocity = speed;
}
}
The Players Configurations
The Spears Configurations
This was the code i have tried before
OnCollision2D(Collision2D target);
{
if (target.gameObject.tag == "Spear")
{
hp = -1;
if (hp <= 0)
{
alive = false;
}
}
}
I hope someone can tell me how to get this working
Thanks for all the answers
(BTW sorry for my bad english I am austrian)
enter image description here
enter image description here
Reasons why OnCollisionEnter() does not work:
Collison:
1.Rigidbody or Rigidbody2D is not attached.
At-least, one of the two GameObjects must have Rigidbody attached to it if it is a 3D GameObject. Rigidbody2D should be attached if it is a 2D GameObject/2D Collider.
2.Incorrect Spelling
You failed to spell it right. Its spelling is also case sensitive.
The correct Spellings:
For 3D MeshRenderer/Collider:
OnCollisionEnter
OnCollisionStay
OnCollisionExit
For 2D SpriteRenderer/Collider2D:
OnCollisionEnter2D
OnCollisionStay2D
OnCollisionExit2D
3.Collider has IsTrigger checked. Uncheck this for the OnCollisionXXX functions to be called.
4.The script is not attached to any of the Colliding GameObjects. Attach the script to the GameObject.
5.You provided the wrong parameter to the callback functions.
For 3D MeshRenderer/Collider:
The parameter is Collision not Collider.
It is:
void OnCollisionEnter(Collision collision) {}
not
void OnCollisionEnter(Collider collision) {}
For 2D SpriteRenderer/Collider2D:
6.Both Rigidbody that collides has a isKinematic enabled. The callback function will not be called in this case.
This is the complete collison table: