Problem with OnCollisionEnter function

As my previous question, the OnCollisionEnter function has a problem. And this is my code:-

function OnCollisionEnter(collision : Collision)
{
   if(collision.gameobject1.tag=="tag1")
   {
      print("YOY");
   }
   if(collision.gameobject2.tag=="tag2")
   {
      print("TROY");
   }
}

My problem is: Despite not having collision with the “gameobject2”, the line “TROY” is printing. However the line “YOY” is also printing, since the 3rd person controller having collision with the “gameobject1”. Both the if-conditions are running at the same time. Why is this happening?

As syclamoth point out, gameObject1 and gameObject2 does not exist. What you're trying to access is gameObject. The compiler should warn you but without #pragma strict it does not, which is kinda odd - or rather inconvenient. Your code should look like this:

function OnCollisionEnter(collision : Collision)
{
   if(collision.gameobject.tag=="tag1")
   {
      print("YOY");
   }
   else if(collision.gameobject.tag=="tag2")
   {
      print("TROY");
   }
}

I suspect gameObject1 and gameObject2 exists elsewhere in your code but they have nothing to do with the collision - and the '.' operator means accessing a child member. The Scripting Reference shows all public member; if its not there, it doesn't exist unless you cache it in your own variable, for example:

var gameObject1:GameObject;
function OnCollisionEnter(collision : Collision)
{
   gameObject1 = collision.gameObject;
   if(gameObject1.tag=="tag1")
   {
      print("YOY");
   }
}