OnCollisionEnter2D(Collision collision) isn't triggering despite collision - c#

I am new to Unity and having problems with this method. Any help would be appreciated.
Currently, I have one box gameObject (customer) that falls down onto another box gameObject (table). The script with theOnCollisionEnter2D method is attached to the tableBox object and checks using tags if the customerBox has collided with it. The problem is that despite colliding, OnCollisionEnter2D does not seem to be getting called at all, as nothing is appearing from Debug.Log. Both boxes have Rigidbody2D and a boxCollider2D.
I have tried changing the Rigidbody2D property to dynamic and also double checking the tags are correct. It is also possible that the script for the tableBox is not running at all, which if is the case I am not sure how to fix and would appreciate suggestions.
Here is the method:
void OnCollisionEnter2D(Collision2D collision){
Debug.Log("in the method.");
if(collision.gameObject.tag == "customer")
{
Debug.Log("Collision detected!");
}
}

Your code seems to be good. Check the following
Both the Rigidbodys are set to dynamic.
Both the bodies have 2D colliders.
They are not colliding already.
Both Colliders are not set as trigger.
Check the layer collision matrix.(Edit>Project settings>Physics2D)

is the "IsTrigger" checkbox unchecked on your collider component ?
Check if the gameobjects are correctly configured (layers, colliders, tags, your script...) and if you got layers, check the physics settings ;)

Related

OnCollisionEnter unity3D

i have a trouble with a collision, i know this is not the way to do "bullets" , but for now im very new and I'm exploring and trying some stuff. I have in my little "bullet" a script with the "onCollisionEnter" function, but when i shoot to make the cube dissapear I have to take 2 shots(two fasts) instead one to that occur, and i do not understand why.
my code says:
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.name == "Cube")
{
Destroy(collision.gameObject);
}
Debug.Log(this.gameObject.name);
}
VIDEO
THANKS!
Here two things you need to check for the collision to work properly in Unity3D.
1. The two objects that are being collided in your case the bullet and the cube that the bullet is gonna collide with should have a collider (box or capsule) anything. And make sure isTrigger is off.
2. This is very important. Either one of the gameObject i.e., your bullet or the cube should have rigidbody component for collision to actually take place. If you dont have a rigidbody in the one of the components your collision wont work. So, I would suggest you to add rigidbody component to your bullet and that should do the magic for you.
Let me know if these worked or if you have any other problem.
And to which gameObject have you attached the following script to?

Unity OnTriggerEnter2D not registering

I am new to using unity and am having a real problem getting trigger collisions to register.
public void OnTriggerEnter2D(Collider2D other)
{
print("collide");
if (other.CompareTag("Fish"))
{
print("Caught");
}
}
I have 2D polygon colliders and a rigid body on both items. I have also got 1 set a trigger(have tried having both as trigger). However one UI item is a sprite and the other is an image.
Both items are also tagged with "fish"
Would really appreciate any help.
Thanks
There are four things I can think of which need to happen so that OnTriggerEnter gets called:
The two objects' colliders need to actually be overlapping. Just because their rendered pixels are overlapping, doesn't mean their colliders are overlapping. This can be checked in the editor. Their colliders are indicated with a green outline in the Scene tab. If you don't see anything, make sure the button labeled Gizmos is turned on.
The two objects need to be in physics layers which are set to collide with each other. You can check this in Edit > Settings > Physics2D > Layer Collision Matrix.
Both objects need to have Rigidbody2D components attached. Make sure these aren't Rigidbody components, as those are for 3D physics.
The object which contains the OnTriggerEnter2D event needs to have isTrigger = true.
I've tried several things to do.
First I've checked recommendations from another post.
In nutshell:
Checked if I have rigid body at least for one of objects
Checked layers
Checked tags
Played with "is trigger".
Finally, the solution was to add script to object via create and add component button and not to drop written script to it. Have no idea, but for me that was the solution. Even it was same script.
Both a Sprite and an Image can collide with another Image. What might be wrong is that your sprite may look like touching the image however in the scene the canvas might be far away, so camera may deceive you. Here is the sample code for my tests:
Script that moves the Sprite:
private Rigidbody2D _rigidbody;
private void Awake() => _rigidbody = GetComponent<Rigidbody2D>();
private void FixedUpdate()
{
if (Input.GetKey(KeyCode.A))
{
var movement = -transform.right * Time.fixedDeltaTime * 250;
_rigidbody.MovePosition(transform.position + movement);
}
if (Input.GetKey(KeyCode.D))
{
var movement = transform.right * Time.fixedDeltaTime * 250;
_rigidbody.MovePosition(transform.position + movement);
}
}
Trigger script on image:
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log(other.name);
}
Nothing helps for me, but in my case I didn't know there was a place in code that breaks collision layers (that is do not change the collision matrix settings visually):
Physics2D.IgnoreLayerCollision(...
Check that too and make sure it is not called.

How to log game objects colliding in Unity

This is my first unity project so I am fairly unfamiliar with everything the platform has. I am trying to log a message to the console when I have a my player game object run into a finish line. Both objects have Box Colliders on them and I have attached a C# script to the player object. Below is the code I have currently.
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Finish")
{
Debug.Log("Finish");
}
}
The problem is that when I move the player into the "Finish" object no logging appears inside the console.
Thanks in Advance!
This is the main player inspector tab
This is the finish line inspector tab
Your script attached to the player checks for a collision with an object with the tag "Finish". Your Object "Finish Line" has tag "untagged". You have to add a tag "Finish" to it to see it working.
With the updated question and screenshots, the problem is that you're checking for the "Finish" tag but the "Finish" GameObject's tag is set to "Untagged" so the if (col.gameObject.tag == "Finish") statement will not evaluate to true.
You have two options:
1. Select the "Finish" GameObject, click the tag that says "Untagged" and create new tag named "Finish". If you already have this tag, change the tag of the "Finish" GameObject from "Untagged" to "Finish" and your if (col.gameObject.tag == "Finish") code should work.
2. If you did not intend to use tag then just compare the GameObject by name instead of tag by simply replacing if (col.gameObject.tag == "Finish") with if (col.gameObject.name == "Finish").
If none of the two options above worked for you then OnCollisionEnter2D is not being called at-all. Put a Debug.Log outside the if statement like below and leave a comment about if there is a log or not.
void OnCollisionEnter2D(Collision2D col)
{
Debug.Log("Finish: " + col.gameObject.name);
}
Just first idea that came in mind:
- Did you add colliders on both of objects that should collide?
Without them engine will not generate events of colliding at all.

Unity collider OnTriggerEnter not getting called

I've made many colliders before and that I used was (collider otherOnTriggerEnter(collider other)) and then check if the other collider is the one I want by comparing TAG. But this time I'm not triggering the canMelee boolean. My code:
ArrayList Enemy;
public StatData stat;
[SerializeField]
private bool canMelee = false;
/// <summary>
/// OnTriggerEnter is called when the Collider other enters the trigger.
/// </summary>
/// <param name="other">The other Collider involved in this collision.</param>
void OnTriggerEnter(Collider col)
{
if (col.tag == "Enemy")
{
Debug.Log("Now you can do melee attack!");
canMelee = true;
}
}
So I wrote this code but somehow this doesn't work I checked the tag and added it to the player game object but it still doesn't work.
I tried to add another debug to check if OnTriggerEnter() is happening just above the if branch : Debug.Log("Triggered"); and it gets triggered.
I can't just figure put what's wrong. Please help me.
First double check that your enemy game objects have the tag "Enemy". Next make sure that your player collider has the "Is Trigger" option selected in the Unity inspector.
Next try using
col.gameObject.CompareTag("Enemy")
instead of: col.tag == "Enemy" in your if statement.
Check out the Unity documentation as well on Colliders:
Unity Collider documentation
Unity Component.CompareTag method with example
Hope this helps!
The first advice I can give you, is ALWAYS, when writting a code Debug it, just make always sure that every step in your code is beeing executed. Inside every if just debug what it is supposed to check and if its true, inside your void, make sure its running the void, etc...
Next:
-Check if you have your object tagged as "Enemy", this can be on of the most common errors, and its so easy to solve, you may have written it wrong, or just not set it up.
-Here is the trigger documentationdocumentation.
-After this, make sure your gameobject is market as triggered.
-If you want you can use also colliders, and this also shows you how to check the tag.
Make sure you set all of this up, if this doesn't helped you, comment bellow, with prints, your gameobjects, codes, etc related to this.

Trying to load a new scene when I enter a cube in Unity

So i have this code to enter a new scene:
using System.Collections;
using UnityEngine;
// add this line to use the SceneManagment library
using UnityEngine.SceneManagement;
public class LoadScenes : MonoBehaviour {
[SerializeField] private string loadLevel;
void onTriggerEnter(Collider other) {
if (other.CompareTag ("Player")) {
SceneManager.LoadScene (loadLevel);
}
}
}
I then add this script to the cube and select it a trigger. I then type in the scene that I want it to send me too, but when i walk into it nothing happens at all. I have tried different variations but it just doesnt seem to work.
My character that I am using is a unity asset called man in suit but I have selected its tag as "Player". Any suggestions would be great!
The Handler for your trigger won't be invoked
As Sunimal allready noted you need to fix the typo.
void OnTriggerEnter(Collider other) {
if (other.CompareTag ("Player")) {
SceneManager.LoadScene (loadLevel);
}
}
Ensure your Scene is included and checked in the Build Settings
As you can see in the Screenshot below i have added a SampleScene to my build settings. There are 2 ways of adding scenes into the build
By clicking "Add Open Scenes" you can add the scene which is
currently open to that list.
Drag & Drop the scene from your ProjectView into the List
Ensure your SceneName is set correctly
Your loadLevel field would in my case need to have the value "Scenes/SampleScene".
[SerializeField] private string loadLevel;
The player needs a collider
As you use the OnTriggerEnter method, your Player object needs to have some sort of Collider attached to it. This can be a BoxCollider, SphereCollider or some other Collider. Note that the "Is Trigger" checkbox needs to be checked. Else it won't act as trigger.
Edit: Thanks Eddge for correcting me. See this answer for a deeper explanation about Triggers.
Programatically ensure you have a BoxCollider component beside your LoadScenes component
You can add the RequireComponent Attribute at your class. It basically ensures you have the given type added as a component. This will also automatically add a box collider to an object, when you add this script.
[RequireComponent(typeof(BoxCollider))]
public class LoadScenes : MonoBehaviour {
/// your other code is here
}
Thanks to Sunimal for this hint!
What if that did not solve the problem?
If all this does not help, please provide an screenshot of the inspector of your Playerobject. That way we can see what components are attached to that object and how they are "configured"
SceneManagement
To use the SceneManager to load a scene you must ensure that your scene is in the build settings, per Tobias's answer.
Triggers
In all software development case does matter and it is incredibly important. OnTriggerEnter is not the same as onTriggerEnter, also note OnTriggerEnter(Collider col) is not the same as OnTriggerEnter(Collision col)
In order to use any of the trigger methods there are 3 things that are a must:
Both Objects have to have colliders.
One of the colliders have to be marked as a trigger.
One of the objects have to have a rigidbody.
The trigger event is sent to the object with the rigidbody and whatever object is the trigger, in the circumstance that both objects are triggers both will receive it.

Categories

Resources