- Home /
Adding Force to a Rigidbody through OnTriggerEnter
This is compliling correctly. The object this is attached to (a boomerang) will go through the object with this script. The object it is hitting is not set to a trigger, and has a rigidbody. I am getting no console errors either. I've also tried this with enemy.gameobject.rigidbody.AddForce and so on... No luck. Thanks in advance!
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour {
void OnTriggerEnter (Collider enemy){
if (enemy.tag == "enemy") {
enemy.rigidbody.AddForce (8000, 2250, 0);
Destroy (enemy.gameObject, 2f);
}
}
}
First thing always with collisions and triggers is to Debug to see what is happening. Add this before your if conditional :
Debug.Log( gameObject.name + "'s trigger was entered by " + enemy.gameObject.name + " : tag = " + enemy.gameObject.tag );
Answer by RyanPaterson · Apr 12, 2014 at 10:01 AM
I tried it myself and got some results. Check your tag is set to 'enemy' instead of 'Enemy' incase there was a caps.
EDIT:Read the comment below about rigid bodies
Note that trigger events are only sent if one of the colliders also has a rigidbody attached. if one, so you only need a trigger one one object, not necessarily the object with the OnTriggerEnter script. Basic rule is 'if it moves, it needs a rigidbody'.
Thank you so much you two! I can't believe it was a due to case sensitivity >_<. I was positive it was the way I wrote the script and never even considered checking the case of enemy!
Your answer
Follow this Question
Related Questions
How do I add force in the on trigger 1 Answer
How to use OnTriggerEnter? (JS) 1 Answer
RigidBody falls through the ground 0 Answers
Why object goes sometimes through walls by adding force ? 2 Answers