I have a problem with my script, and need someone to help me with it.
Script written below is attached to game object called Ball and what I want is that script counts number of collision that happen in specific order (Box, Cube, Floor…First hits Box, then Cube and finally Floor).
My script doesn’t do a thing. pointsPlayer1 is 0 all the time.
Anyone who can help me?
static var pointsPlayer1 = 0;
var MetalGUISkin : GUISkin;
function OnCollisionEnter(hit : Collision) {
if (hit.gameObject.name == "Box" ) {
if (hit.gameObject.name == "Cube"){
if (hit.gameObject.name == "Floor"){
pointsPlayer1++;
}
}
}
}
function OnGUI(){
GUI.skin = MetalGUISkin;
GUI.Label(Rect(25,200,35,25),pointsPlayer1.ToString());
}
You will never reach the second “if” statement.
OnCollisionEnter() is called each time an object enters the collider found on the same GameObject as the script you are calling OnCollisionEnter().
You are checking if the name of the object that hit yours, is “Box”, and only if it, do you check if that exact game Object is named “Cube”.
This is not logical and will never happen.
You need to keep track of what was hit, and each time a new hit is listed, you need to check the track and keep at it or reset it if the order is wrong.
For instance:
The simple to understand solution (there is a much nicer one, but it might be too complicated for you to understand at this point):
var hitList : int = 0;
function OnCollisionEnter(hit : Collision)
{
if (hit.gameObject.name == "Box" )
{
hitList = 1;
}
else if (hit.gameObject.name == "Cube")
{
if ( hitList == 1 )
hitList = 2;
else
hitList = 0;
}
else if (hit.gameObject.name == "Floor")
{
if ( hitList == 2 )
pointsPlayer1++;
hitList = 0;
}
}