- Home /
How to check if car entered garage... then if true, do a specified function ?
I have a garage and a car in my scene, I Want to make a script "Javascript" to check if the car is inside the Garage then do a certain function
How to make a script to check if the car is inside or not ?!
Answer by HarshadK · Oct 09, 2014 at 01:39 PM
Add a trigger collider to your garage. And also there needs to be a rigidbody attached to your car. In your script define a bool variable. When the car enters the garage set the variable to true and when car leaves set it to false. Now whenever required check the value of this variable.
var isCarInside : bool = false; // We consider the car is not inside at first
function OnTriggerEnter(Collider col)
{
if(col.gameObject.name == "Car")
{
isCarInside = true;
}
}
function OnTriggerExit(Collider col)
{
if(col.gameObject.name == "Car")
{
isCarInside = false;
}
}
function Update()
{
if(isCarInside)
{
// Your car is inside and you can perform the required function here
}
}
In above script it is assumed that the name of your car game object is "Car". You can also check it using a tag, if required.
@Harshad$$anonymous$$ should I attach this script to the car itself or the garage ?!
@Harshad$$anonymous$$ first, It gives me an error "bool" I Saw it online written Boolean not bool.
Second, Unexpected token : col.
what's all that!
This is a screenshot.
I mistakenly wrote some C# into it. I don't use JS, so sorry for that.
var isCarInside : boolean = false;
function OnTriggerEnter(col : Collider)
{
if(col.gameObject.name == "GTR")
{
isCarInside = true;
}
}
function OnTriggerExit(col : Collider)
{
if(col.gameObject.name == "GTR")
{
isCarInside = false;
}
}
function Update()
{
if(isCarInside)
{
Debug.Log("Car is in the garage");
}
}
@Harshad$$anonymous$$ Don't worry man, Anyway thanks for even helping me :)
Look, Now I Have problem it's working but it works only "When Passing through the garage walls" I Don't want the car to pass through walls!
What should I Do ?!