- Home /
How to Apply a script During collison?
So, I have a car game, and i have a tornado in that car game. I also have a randomflying script. What I want is to have the randomflying script to be applied to the car while the car is touching the tornado, and to have the script deactivated when the car is not touching the tornado. I know that I would Probably have to Use OnTriggerEnter..... but im not really good at js. can anyone give me an accurate script or any tips?
Answer by J.D. · Aug 20, 2011 at 10:08 PM
There is a lot of ways to do that in Unity.
I would use this:
Tag your Tornado as "Tornado".
The OnTriggerEnter function has a parameter that you have to use to check what is the collider object.
(I use C#, but just look at the LOGIC, and not the syntax)
//This should be attached to your car
void OnCollisionStay(Collision obj){
//obj will be the Tornado, right?
if(obj.gameobject.tag == "Tornado"){
YouCarFlyAwayHere();
}
}
You could also use OnCollisionEnter(). But that way you maybe should implement OnCollisionExit() as well.
I hope I helped.
Good Luck.
Answer by diddykonga · Aug 21, 2011 at 05:50 AM
Here try this.
void OnTriggerEnter (Collider info) {
if(info.gameObject.tag == "Car")
{
info.gameObject.AddComponent("RandomFlying");
}
}
void OnTriggerExit (Collider info) {
if(info.gameObject.tag == "Car")
{
info.gameObject.GetComponent<RandomFlying>().Destroy();
}
}
There we go, now all you need to do, is to set your tornado's collider to isTrigger. Then give your car, the Car tag, and your all set :)
I tried this but it gave me tons of errors that i couldnt figure out how to fix. :(
Answer by sketchers1 · Aug 25, 2011 at 02:55 AM
So, I tagged the tornado as Player, and here is the script I used:
function Update () {
//This should be attached to your car
void; OnCollisionStay("Tornado");{
//obj will be the Tornado, right?
if(obj.gameobject.tag == "Player");{
info.gameObject.AddComponent("RandomFlying");
}
}
}
This gave me these errors:
Assets/Scripts/TornadoScript.js(6,1): BCE0043: Unexpected token: if.
Assets/Scripts/TornadoScript.js(7,46): BCE0044: expecting :, found ';'.
ummmmm these are the 2 errors I cant figure out??? any help?
As I said, this is just the Logic. And is in C#. Your script has .js extention.
Just Understand what i meant in code, and write in Javascript. Its really easy, if you read carefully.
Good luck!
Your answer
Follow this Question
Related Questions
Why would OnTriggerEnter get called, but not OnTriggerExit? 0 Answers
Problem with OnTriggerExit 1 Answer
Weird OnTriggerEnter / Exit behavior 1 Answer
OnTriggerExit doesn't work when scaling collider 0 Answers
Why is OnTriggerEnter2D executing multiple times before I get an OnTriggerExit2D? 1 Answer