Unity collider OnTriggerEnter not getting called - c#

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.

Related

OnCollisionEnter2D(Collision collision) isn't triggering despite collision

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 ;)

unity 3D collider

i am trying to develop a melee combat game i am using edge collider and below code
i noticed that when i move or enable and disable the collider from the inspector everything goes but when i stand in my palace and use AttackCol.enabled = !AttackCol.enabled;
i cannot hit and the trigger function do not called
the only difference i see is the collider color when i add it from the inspector or while i am moving its color is normal but when i enable and disable it by code its color goes pale and do not do anything
public virtual void OnTriggerEnter2D(Collider2D collision)
{
if (DamageSources.Contains( collision.tag ))
{
StartCoroutine(TakeDamage());
}
}
Make sure that your Trigger Game Object is not marked as Static.
Remove virtual from function definition.
Create another Game Object for Trigger Component and try to change activation of whole the Game Object, not collider component
Stuff like AttackCol.enabled = !AttackCol.enabled; is clever, but it can go wrong when that one is called (accidentally) more than once. I suggest trying it out in the simplest form AttackCol.enabled = true; to make sure the error is not there. Later you can still make it more elegant again! :)
i added AttackCol.isTrigger = AttackCol.enabled;
after AttackCol.enabled = !AttackCol.enabled;
and everything geos ok right now
but i think it is a work around
but i need to know why the color goes pale ?

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.

Unity minus extra number when I just want minus one

What I'm trying to do is when it hits a triggered collider I want it to minus an int, but what unity does is minus it with 3 instead, and I have it attached to the player itself
lifecontroller lves;
public GameObject gm;
CoinScript coins;
// Use this for initialization
void Start () {
gm = GameObject.FindGameObjectWithTag("GM");
coins = gm.GetComponent<CoinScript>();
lves = gm.GetComponent<lifecontroller>();
}
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Evil")
{
lves.lives -= 1;
Debug.Log("U hit it");
}
}
// Update is called once per frame
void Update () {
if(lves.lives == 0)
{
Debug.Log("u died");
}
}
Judging from the screenshot, your script is attached to the Player GameObject multiple times. Select your Player GameObject, and remove the duplicate Script.
Make sure there is only one script attached to it. It is probably attached there 3 times.
This problem can also happen if you are instantiating multiple Player GameObjects during run-time as this will duplicate your script too.
EDIT:
With the updated Image in your comment, the problem is that you have 3 Colliders on your Player. It is true that only one of them is made IsTrigger but this is a problem if the GameObject with the Evil tag is marked as IsTrigger too.
You have 2 options to fix this:
1.Select the GameObjects with the Evil tag and make sure that no Collider attached to it is marked as IsTrigger. Unceheck all IsTrigger properties on the Collider of all Evil tagged GameObjects only. This should fix your problem.
2.Only have one Collider on Player GameObject. Remove the other 2. This again should fix your problem.
The trigger is definitly happening 3 times, your screenshot shows that (there is a 3 on the right since duplicate logs get collapsed).
This might occur because of the collider shape I think (circle). Try using a bool that us set on trigger enter and clear on trigger exit (or even Update should be ok for clearing).
This is what I suggested to debug your problem:
void OnTriggerEnter2D(Collider2D other)
{
if(other.tag == "Evil")
{
lves.lives -= 1;
Debug.Log("U hit it", other.gameObject);
}
}
And by looking at your screenshot you are getting 3 log messages.
Always use don't collapse in console window to see whats happening

c# OnTriggerStay with Collider Variables

So I'm making a simple "puzzle" using lights. Simply, there are 3 buttons with lights on them (red, blue, green). Each button has it's own trigger volume but when I go to play, nothing prints that I even enter, stay, or leave the trigger. I've never used Collider Variables before so I feel like I'm doing something wrong (obviously or it would be working!). But then I just did "Collider entity" in the OnTriggerStay/Enter/Exit Method and it still didn't print to the console that my player was entering. Why are my Triggers not working?
Click here for the code I'm trying
Click here to see how I have it in the Unity Scene
Triggers only respond to other colliders that have rigid bodies on them.
Try adding a Ridgidbody component to your player and set it to kinematic.
OnTriggerEnter/Stay/Exit works when the Object has a Collider Component and BluePuzzle2 doesn't have that.
Also OnTrigger function gets a Collider as parameter. Check the reference page
So in order to make that work put a script on every light and on that script copy this function
void OnTriggerEnter(Collider col) {
if (col.CompareTag("Player")) {
print("Entered the trigger");
}
}
Hope it helps.

Categories

Resources