- Home /
Help with collision script
Hello, I am a new-comer to Unity and am currently working on a learning project. However scripting is something that I have trouble with. Currently I am trying to make a script to detect when two objects collide and remove both. However I can't get it to work? Help would be much appreciated.
function Update () {
function OnTriggerEnter (collision : Collision){ destroy (gameObject); destroy (wall); }
}
Answer by Peter G · May 12, 2010 at 11:20 PM
One issue that can be solve right away, is that you don't need to nest the OnTriggerEnter inside of the Update. So you can remove the Update right away. This and the next issue are the only things that make your code not work.
Another thing, You need to declare a variable wall. That way Unity knows what to destroy. That is probably what was keeping your script from compiling.
var wall : GameObject;
If you want some other advice for generally improving your code you can continue, otherwise, that is the answer to your problem.
Next, Your OnTriggerEnter, is combining 2 methods together. It should actually still work, but you see, OnTriggerEnter(col : Collider) requests the collider that entered the trigger (or the trigger depending on what gameobject has this script attached. Remember it returns the other of the two possibilities.) And, you have provided the Collision information which is used in OnCollisionEnter(). So your script could either read.
var wall : GameObject;
function OnTriggerEnter (col : Collider) { //If your collider is a trigger Destroy (gameObject); Destroy (wall); }
or
var wall : GameObject;
function OnCollisionEnter (col : Collision) { //If it is a normal collider destroy (gameObject); destroy (wall); }
or, since you are not using actually using any of that information, you can just take it out also. Which will save you memory if you are running low.
var wall : GameObject;
function OnTriggerEnter () { //If your collider is a trigger Destroy (gameObject); Destroy (wall); }
Answer by e-bonneville · May 12, 2010 at 11:13 PM
Your problem is in the destroy (wall)
line. How does the computer know what you're talking about? What you need to do is create a variable called wall and assign a gameObject to it in the inspector, like this:
var wall : GameObject;
function OnTriggerEnter (collision : Collision){ destroy (gameObject); destroy (wall); }
That should do the trick!