WHY IT ISNT WORKING?!

Script is working fine, soldier is destroying its self if i am hitting a car to him,
but it isn’t working if i shoot him with bullets(“Sphere”).
(soldier is colliding bullets)
here is script i am using:

var speed:float=2;
var life = 20;
function Update () {

animation.Play();
transform.Translate(Vector3.forward * speed * Time.deltaTime);

 
}


function OnCollisionEnter(theCollision : Collision){
 if(theCollision.gameObject.name == "car"){
  Destroy(gameObject);
 }
 
 if(theCollision.gameObject.name == "Sphere(clone)")
 {
  life -= 20;
  
   if (life <= 0)
  {
  Destroy(gameObject);
  }
 }
}

2 Answers

2

I think clone should be Clone but to prevent this kind of problem, you should tag your object and use the tag instead.

function OnCollisionEnter(theCollision : Collision){
   if(theCollision.gameObject.name == "car"){
      Destroy(gameObject);
    }
 
    if(theCollision.gameObject.name == "Projectile"){
       life -= 20;
       // Rest
    }
}

BECAUSE CORRECT CAPITALISATION IS IMPORTANT.

As you’ve already discovered:

if(theCollision.gameObject.name == "car"){ ... }

is working. But:

if(theCollision.gameObject.name == "Sphere(clone)") {...}

is not. Look carefully at the names of clones instantiated in your hierarchy and you’ll see why not.

If you do not feel like answering don't bother. This is not bringing anything to the thread. I think your karma allows you to edit content, just do so and place a comment. This "answer" would deserve a great deal of downvote. Same here, I could just delete your answer and not say anything.

Fair comment, and you're right to point out that my "answer" is somewhat obtuse. However, it does actually point out to the OP the cause of their error. You don't get better at programming by having all your errors corrected and handed to you on a plate. You get better at programming by getting assistance in knowing what to look for in order to solve your own problems.... Nevertheless, I'll amend to make it somewhat clearer.