Detecting collisions between Instances in Unity

Started by
3 comments, last by CubeUser 5 years, 7 months ago

Hello, I wonder how to detect collisions between two instances of 3D objects, say spheres, created using "instantiate" and destroying both of them upon detection, and creating a third different one?

Languages I have been in touch with: Unity3D, C#, Lua, VB, VB.net, Blitz3S, BlitzMax, DarkBasic, C++

Advertisement

Hi CubeUser,

you have to add a collider to the GameObjects and (if I remember correctly) at least one of them needs a rigidbody.
On the objects you set isTrigger to true (in the inspector) OnTriggerEnter /Exit etc is called when two trigger collide.
 


void OnCollisionEnter (Collision col)
{
	//Do your logic
}

Destroying is handled by


Destroy(col.gameObject);
Destroy(this);

After that you can create the new object with Instantiate. See: https://docs.unity3d.com/ScriptReference/Object.Instantiate.html

You might want to get the transform of the colliding objects before you destroy them to use it for the new object.

You will first make a prefab.

To do this drag the sphere into the scene. Attach the collision object. Attach a script to the sphere that tells it how to act when it collides. Then in the hierarchy window drag the sphere out of the level into the editor.

Now when you cal the instantiate() function, you use this already made prefab.

 

I made some tests of this before doing this post,similar to those in your answer, and I knew about the prefab stuff, I thought you had realized that. But no collision was detected, I had also activated physics. Could it be that?  By the way I am using Unity under Windows 10, I would like to make sure it works the exactly same way no matter what platform is used for developing. I intend to develop under Windows and for Windows to avoid any compatibility issues. [EDIT:] I managed to get it work by starting all over in a new project. I also after hours discovered that "constrain" should _not_ be used for fixed objects like walls, if collision is to be detected correctly. Check "Kinematic" to stop it from moving my physics. Thanks for the help ?

Languages I have been in touch with: Unity3D, C#, Lua, VB, VB.net, Blitz3S, BlitzMax, DarkBasic, C++

This topic is closed to new replies.

Advertisement