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
Related
I'm new to Unity and I was wondering if anyone knows how to make the player pick up a weapon and shoot it in Unity 2D. I have already made the sprite for the gun and I've been trying to pick it up with this code:
public GameObject player;
void Update() {
void OnTriggerEnter2D(Collider2D col) {
if (col.tag == "Player") {
gameObject.transform.position = new Vector3(player.transform.position.x + 2, player.transform.position.y, player.transform.position.z);
}
}
}
The gun is set as a trigger and has no rigidbody. All the youtube tutorials show how to pick up an object and then destroys it, but don't show how to "hold" the object.
If you do player.transform.position.x + 2, that sets the gun to the x position of the player + 2. This is not a good way of doing it.
My advice is to do it this way instead.
Copy the gun.
Parent the copy to the camera
Place the gun somewhere on your player.
Disable the gun
In your player script add this line
public GameObject weapon;
Now, in your weapon pickup script, change the player reference to whatever your player script is called instead of a GameObject.
For example, lets assume your player script is called PlayerScript.cs, instead of
public GameObject player;
You should do
public PlayerScript player;
Now, we have a reference to the player script. We can now access the weapon.
Change the OnTrigger to the following:
void OnTriggerEnter2D(Collider2D col) {
if (col.tag == "Player") {
// Set the weapon active
player.weapon.SetActive(true);
// Destroy this pick-up
Destroy(gameObject);
}
}
Also, in your code you have ontriggerenter inside the update method. That is not how it works. Make sure the method is outside of the update method.
Now when you touch the gun on the floor. It should now enable the gun in the players hand and destroy the one on the floor.
In the editor, drag the players gun to the weapon field in the player script.
Also, drag the player to the player field of the gun on the ground.
Hope this helps, feel free to ask more questions if this doesn't work. Keep us updated. :)
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.
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;
}
}
}
I was wondering how I can switch scenes in my 2D Unity game. I put the scenes in the build and the objects are entering in colison. I used this code but it didn't worked:
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneSwitch : MonoBehaviour
{
[SerializeField] private string WhatScene;
void OnTriggerEnter(Collider2D other)
{
if (other.CompareTag("Player"))
{
SceneManager.LoadScene(WhatScene);
}
}
}
Can you help me?
https://i.stack.imgur.com/rpg3t.png
https://i.stack.imgur.com/HoOfl.png
https://i.stack.imgur.com/9GEgi.png
Note that there is
OnTriggerEnter2D(Collider2D) which as parameter takes a Collider2D, not Collider. This one is for 2D physics using Rigidbody2D and Collider2D components.
OnTriggerEnter(Collider) which takes a Collider, **not Collider2D. This one is for 3D physics using Rigidbody and Collider components.
Since you are talking about 2D your method should look like
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
SceneManager.LoadScene(WhatScene);
}
}
If you are using OnTriggerEnter method in unity2D there is a problem, you need to set collision as a trigger and use "OnTriggerEnter2D" method.
In build settings you have to add scenes, there will be a different index attributed to every scenes.
private void OnTriggerEnter2D(Collider other)
{
if (other.CompareTag("TAG"))
{
SceneManager.LoadScene([INDEX OF THE SCENE YOU WANT TO USE]);
}
}
If you want to detect a collision use OnCollisionEnter2D.
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: