- Home /
OnCollisionEnter doesn't work if enemies and allies have rigidbody ?
Hello unity forums, i'm actually making a game a bit like total war: there is your units and enemy units.
I want that when sword collide on a opponent body, it gets damage, so here is my sword script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponScript : MonoBehaviour {
public GameManager gameManager;
public UnitScript unitScript;
public int damage;
public string opponentTag;
// Use this for initialization
void Start () {
unitScript = GetComponentInParent<UnitScript>();
opponentTag = unitScript.targetTag;
gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>();
damage = unitScript.damage;
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.tag == opponentTag)
{
Debug.Log("Hit " + "Ally");
other.gameObject.GetComponent<UnitScript>().health -= damage;
if (other.gameObject.GetComponent<UnitScript>().health <= 0)
{
gameManager.KilledOpponent(other.gameObject);
Destroy(other.gameObject);
}
}
}
}
This code works if only the allies or the ennemies have a rigidbody, but if both of them have a rigidbody equipped, no collision are detected anymore :/ I don't understand why. Thank you for your answers !
Answer by TanselAltinel · Apr 29, 2018 at 02:42 PM
Collision and Trigger events will be fired if and only if one of the game objects has RigidBody component.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnCollisionEnter.html
Notes: Collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached. Collision events will be sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions.
So make sure they have a non-kinematic rigidbody attached. Setting rigidbody to Kinematic will disable it.
Your answer
Follow this Question
Related Questions
OnCollisionEnter but have colliding object not move the object it collides with 1 Answer
Rigidbody magnitude comparison is not working correctlly? 2 Answers
Collision detection only half working. 1 Answer
Collsion without ririgibody 1 Answer
What is causing my object to spin around and act funky when it hits another collider? 0 Answers