This question was
closed Apr 28, 2018 at 07:18 AM by
HamzaAlrawi for the following reason:
The question is answered, right answer was accepted
Question by
HamzaAlrawi · Apr 28, 2018 at 10:06 PM ·
collisioninstantiateoncollisionenterinstantiating
Adding OnCollisionEnter to instantiated object not working properly!
Hello,
Basically I am instantiating an object in a 2D game and adding a On Collision Enter script to it. However it is not triggering for some reason. Both objects have a Rigidbody2D component and a box collider
Script 1:
.......
GameObject firedArrow =(GameObject) Instantiate (Arrow, firePointPosition, Quaternion.FromToRotation(Vector3.right,firePointPosition));
firedArrow.AddComponent<ArrowDamageScript> ();
if (playermiddleposition.x - firePointPosition.x >= 0) {
speed = -speed;
firedArrow.GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, 0f);
speed = -speed;
} else {
firedArrow.GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, 0f);
}
........
Script 2:
void Start(){
Debug.Log ("Script added!");
}
void OnCollisionEnter(Collision col) {
ContactPoint contpoint = col.contacts[0];
Debug.Log ("We hit " + col.collider.name + " and did " + Damage + " damage.");
Destroy (col.gameObject);
}
I do get the debug message that the script was added. However, nothing is happening upon collision. Any ideas?
Comment
dude if it's a 2d game you should change
void OnCollisionEnter(Collision col) {
ContactPoint contpoint = col.contacts[0];
Debug.Log ("We hit " + col.collider.name + " and did " + Damage + " damage.");
Destroy (col.gameObject);
}
to
void OnCollisionEnter2D(Collision2D col) {
ContactPoint contpoint = col.contacts[0];
Debug.Log ("We hit " + col.collider.name + " and did " + Damage + " damage.");
Destroy (col.gameObject);
}
also you have to attach a boxCollider2D to your object ,not boxCollider
Oh I feel so stupid!
Thank you very much!
*Note: the ContactPoint should also be ContactPoint2D
I really appreciate your help!