Collision not getting detected in unity3d - c#

I am making a 2D game. I have 2 game objects, a player, and some obstacles and I want the player object to be destroyed on collision. I have added box colliders to both the objects as well as tags but the collision is not taking place as there are no log messages in the console.
void OnCollisionEnter2D (Collision2D col)
{
Debug.Log("collision name = " + col.gameObject.name);
if (col.gameObject.tag == "cow") {
Destroy(gameObject);
}
}

As we discussed in comments:
Add Rigidbody2D component to at least one of colliding objects.

Related

Unity-2d: Why are two trigger colliders interacting?

I thought that trigger colliders were not meant to interact with each other, I have the following game object:
(The "AttackArea Game Object is a child of a "Player" Game Object)You can see I set it to be a trigger, the script "Attacks" only has the following code:
public int attackStrength;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.GetComponent<Health>() != null && collision.CompareTag("Enemy"))
{
Debug.Log("touched: " + collision.name);
Health health = collision.GetComponent<Health>();
health.ReduceHealthPoints(attackStrength);
}
}
The OnTriggerEnter2D method is getting called when this Polygon collider touches a Circle collider also set as a trigger:
Not sure why the two trigger colliders are interacting at all, I thought that wasn't possible.
These are the RigidBody settings on the game object that has the Polygon Collider 2D (it's parent):
With the isTrigger property set to true, the collider will not collide, but it will send trigger events.
If you do not want to interact with certain game objects you can add tags to the relevant game objects and compare the tags.
For example:
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("CircleCollider")) return;
}

Is there a way to make a hitbox ignore another one?

I was creating a multiplayer first-person medieval fighting game based on Skyrim and For Honor combat, with 3 different stances. In it, you can attack from 3 stances, and if the opponent is not holding the same stance, he takes the attack, otherwise he parries and the attacker takes a quick stun.
The problem starts when the Sword's Hitbox hits the player's own hitbox, causing unwanted results.
That's why I want to know if there is a way for making the player's sword ignore the collision with the player itself, so that he can't attack himself.
I also tried to put the method: Physics.IgnoreCollision(collider, selfCollider); Inside the OnTriggerEnter() function, Start() and Update(), and no solution worked.
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Enemy" || other.gameObject.tag == "Player")
{
//instant enemy combat
CombatManager enemy = other.gameObject.GetComponentInChildren<CombatManager>();
Debug.Log(enemy.currentStance);
//If enemy stance is not the same of the attacker
if(enemy.currentStance != this.currentStance)
{
//enemy is damaged
//Get enemy LifeManager and subtract its health
enemy.GetComponentInParent<LifeManager>().currentHealth -= swordDamage;
}
else
{
anim.SetTrigger("Parried");
}
}
Try:
if(other.transform.root != transform.root)
{
// NOT self collision
}
This basically checks if both objects belong to the same hierarchy. In other words if they have the same top-most GameObject or root.
Obviously I made some presumptions as to how your players avatars are rigged. Perhaps you will need to tweak this solution to suit your hierarchy.

Collision detection in Unity 2d

I'm working on my first Unity project. It's a little game where you have to move your planet to dodge incoming asteroids.
I have set up a simple collision detection system but it's not working at this moment and I'm not entirely sure why.
These are the lines of codes, they're on the movement script for the planet, attached to my gameobject planet:
private void OnTriggeredEnter2D(Collider2D collision)
{
if (collision.tag == "Asteroid")
{
restartPanel.SetActive(true);
}
}
The asteroids are a prefab spawned dynamically in this manner in a script attached to an invisible gameobject:
void Update()
{
float interval = Time.deltaTime;
random = Random.Range(0f, 1f);
Debug.Log(interval);
Debug.Log(random);
if (interval > random) {
GameObject newAsteroid = Instantiate(asteroidPrefab, GetRandomPosition(), Quaternion.identity);
newAsteroid.GetComponent<Gravity>().planet = planet;
}
}
Nothing happens when planet collides with any asteroid, or when asteroids collide with each other, if that matters, and I'm not entirely sure why.
Thank you for your help.
The method name was not correct, I messed up, it should have been OnTriggerEnter2D, not OnTriggeredEnter2D.
Yikes.

Disable specific game object

So, I'm making a coin system. When a player collides with trigger collider, i want it to disable only the object it collided with.
this.SetActive(false);
Finding object by name
void OnTriggerEnter (Collider other)
{
if (other.tag == "Coin")
{
this.SetActive(false);
}
}
/
You were very close with your original solution, but you may be misunderstanding what is actually happening here. So I've documented my solution to show the difference.
/* The following script is called when a Rigidbody detects a collider that is
* is set to be a trigger. It then passes that collider as a parameter, to this
* function.
*/
void OnTriggerEnter (Collider other)
{
// So here we have the other / coin collider
// If the gameObject that the collider belongs to has a tag of coin
if (other.gameObject.CompareTag("Coin"))
{
// Set the gameObject that the collider belongs to as SetActive(false)
other.gameObject.SetActive(false);
}
}
If you want the coin to be removed from the scene, because you don't expect it to ever be reactivated, then you can amend this code to the following:
void OnTriggerEnter (Collider other)
{
if (other.gameObject.CompareTag("Coin"))
{
// Removes the coin from your scene instead
Destroy(other.gameObject);
}
}

How to check collision between the player and a specific TileBase object in Unity?

I have a couple of tilebase variables that are set using the unity inspector:
public TileBase obstacle; //obstacle tile
public TileBase spikes; //instant death tile
I'm using OnCollisionEnter2D in a script that is set to the tilemap asset.
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "Player")
{
PlayerPrefs.SetInt("Collision", 1);
}
}
I want to be able to detect when the player has collided with the spikes TileBase as that should trigger a game over. The asset name that is set to the spikes variable through the inspector is also called Spikes or Spikes (Tile) in the palette.
I tried using adding collision detection to a script that is used on the player asset to check what objects it collides with
void OnCollisionEnter2D(Collision2D col)
{
Debug.Log(col.gameObject.name);
}
But all it comes back with is the name of the tilemap.
First you should add Layers to your objects. An easy example is to add a "TileBase" or "Tile" Layer to your TileBase objects.
You can then allow your Player to only collide with certain things and NOT your tilemap. See the collision matrix for this.
Then alter your code like this:
void OnCollisionEnter2D(Collision2D col)
{
var tilebase = col.GetComponent<TileBase>();
if (tilebase != null)
{
Debug.Log(tilebase.gameObject.name);
}
}

Categories