Detecting collision of two prefabs through code c#
Maybe I'm just dumb but I just can't figure it out. Say I've got two prefabs I'm initiating through code.
Object obj = Resources.Load("poke");
GameObject go = Instantiate(obj, new Vector3(), Quaternion.identity) as GameObject;
GameObject gos = Instantiate(obj, new Vector3(), Quaternion.identity) as GameObject;
How do I detect any collision? Do I have to add a RigidBody? Is there a way to create a Collider through code? I keep finding the OnCollisionEnter() or something but there's no info about binding that event to a gameobject. Thanks in advance guys.
Also, please don't redirect me to some other answer cos I think I've tried all of them and got nothing.
Answer by ElDo · Oct 31, 2015 at 10:57 PM
Collision detection happens Independent of your spawning method. But at least one of your Instantiated GameObjects must have an non-kinematic Rigidbody for the OnCollision Events to happen (see here) of course your GameObjects Need some Kind of collider. If you use MeshColliders you Need to know that 2 non convex MeshColliders also don't Trigger Collision Events afaik.
okay but how exactly do I refer the OnCollision event to a gameObject?
In your C# script you have something like:
void OnCollisionEnter(Collision collision){
}
void OnCollisionStay(Collision collision){
}
void OnCollisionExit(Collision collision){
}
These are called at the respective Events (just like Start() or Awake() or Update()). OnCollisionEnter as soon as something starts to collide, OnCollisionStay as Long as something collides and OnCollisionExit as something stops to collide.
I see. It just doesn't work for some reason. Both items have RigidBody, they collide alright. The events dont fire off
item.obj.gameObject.AddComponent<Rigidbody2D>();
item.obj.gameObject.AddComponent<Collider2D>();
also, the console says Cannot add component of type 'Collider2D' because it is abstract. Add component of type that is derived from 'Collider2D' ins$$anonymous$$d. UnityEngine.GameObject:AddComponent()
Is there a reason why you have to add them by code? If it can't add the Collider there can't happen collision Events so you Need to check why they don't get added. try to add one of the here mentioned BoxCollider2D, CircleCollider2D, PolygonCollider2D or EdgeCollider2D. Then it should work.
item.obj.gameObject.AddComponent<BoxCollider2D>();
Your answer