On the "project" Panel, click the triangle next to "CREATE" and select" Javascript "Create a JS named" Collision" File . Double-click it and the system starts monodevelop to edit the JS file.
Clear the default Code . Write.
Function Oncollisionenter (OBJ: collision)
{
DeBug . Log (obj. Game Object. Name );
}
Oncollisionenter: This function is called when the bound object collides with other objects.
OBJ parameter description: The parameter of the hit object. The type is collision. In this example, the parameter is "floor ". the variable gameobject is the name of the collision object, that is, the name we set for the floor.
Drag the script file to the ball for binding:
This step is easy to operate. On the "project" Panel, select the collision script and press Mouse Drag the left button to the hierarchie panel and place it Cube And the mouse is released to complete the binding.
Run in the triangle at the top of the vertexProgram:
Program running result. When the ball hits the floor, the status bar at the bottom of unity3d will output the name of the floor.
Done.
Oncontrollercolliderhit (), which is used for role collision. If an object is attached with a charactor controller (script for role control provided by unity), this function is used to detect collision, this does not require a rigid body. Generally, oncollisionenter () is used for collision between rigid bodies, and ontriggerenter () is used for range triggering. If you want to collision two cubes, make sure that one of them is attached with the Rigidbody,
collision is a variable that can be used to obtain the attributes of the target you are colliding with, as well as the collision point information and relative speed, for example, collision. collider. A component or script. Void oncollisionenter (collision) {If (collision. collider. Tag = "enemy") // tag is the object tag, which is equivalent to the object category name. You can find at the top of the component bar of each object (that is, the area where the script is added). The default value is untagged, that is, there is no tag, then, click a drop-down list, which has several tags by default. You can also add custom tags. Click Add
at the bottom of the drop-down list to add tags, finally, select a tag as the object name. {Destroy (collision. collider. gameobject); // if the opposite party is detected to be an enemy, destroy the other party .}}