Hi
i am new to scripting and am desperatly trying to learn it.
I need a simple as possible script that:
when the object with the script collides with a specific object, the object that has the script does something
i need this script so I can learn how to use collisions!
any help would be much appreciated
thanks!
The Unity Script Reference gives a great explanation and a few examples of code: Unity - Scripting API: Collider.OnCollisionEnter(Collision)
To find out if a particular object collided with the object the script is attached to, try something like this:
public var go_collide_with : GameObject; //in the Inspector, drag the object you want to collide with into this variable
function OnCollisionEnter(collision : Collision) {
if (collision.gameObject == go_collide_with) { //did I collide with that object?
//do something here
}
I haven’t tested this code, but this is the concept!
thanks!
this script works perfectly!
much appreciated!
My pleasure! Does the script make sense to you?
And here’s an additional script that does basically the same thing, except it recognizes collisions with several different objects:
public var go_collide_with : GameObject[]; //in the Inspector, set the number of elements you want to collide with and then drag each one into a "slot" of this variable
function OnCollisionEnter(collision : Collision) {
var b_collision : boolean = false;
var go_one_object : GameObject;
// Set "b_collision" to true if I collided with ANY of the objects in the "go_collide_with" array
for (go_one_object in go_collide_with) {
if (collision.gameObject == go_one_object) { //did I collide with this particular object?
b_collision = true;
}
}
// So, now that I've checked for collision with all of them -- did I collide or not?
if (b_collision == true) {
//do something here
}
Also read up on Layers; these can be a useful tool to impose how different classes of gameObjects subscribe (or not) to things like Collisions and Raycasts.
thanks a million
both scripts do make sense and are incredibly useful!
and BoredKoi, i will take your advice and look into layers,
thanks!