Adding Tag

Hello this script is very amazing you guys can use it freely, but I want to add tag in it. So when it spawns as a prefab with would know what to find and follow. Because if I spawn the enemy then the target will not obviously magically appear there. And the function OnCollisionEnter is supposed to be like that.

So How do I add tag functionality in the script.

Heres the script

var distance;
    var health : int = 10;
    var target : Transform;    
    var lookAtDistance = 15.0;
    var attackRange = 10.0;
    var moveSpeed = 5.0;
    var damping = 6.0;

    private var isItAttacking = false;

    function Update () 
    {
    distance = Vector3.Distance(target.position, transform.position);

    if(distance < lookAtDistance)
    {
    isItAttacking = false;
    renderer.material.color = Color.black;
    lookAt ();
    }   
    if(distance > lookAtDistance)
    {
    renderer.material.color = Color.black; 
    }
    if(distance < attackRange)
    {
    attack ();
    }
    if(isItAttacking)
    {
    renderer.material.color = Color.black;
    }
}

function lookAt ()
{
var rotation = Quaternion.LookRotation(target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
}

function attack ()
{
    isItAttacking = true;
    renderer.material.color = Color.black;
    transform.Translate(Vector3.forward * moveSpeed *Time.deltaTime);
}

function OnCollisionEnter(col : Collision) {
      if(col.gameObject.name == "Player"){
      gameObject.Find("Player").SendMessage("DecreaseHealth");
      }
}

function TakeDamage(Damage : int)
{
   health -= Damage;

   if (health <= 0)
   {
      Destroy(gameObject);
   }
}
  • Felipe

right now you’re checking the name, rather than the tag:

 function OnCollisionEnter(col : Collision) {
          if(col.gameObject.name == "Player"){
          gameObject.Find("Player").SendMessage("DecreaseHealth");
          }
    }

to check by tag, you would use:

function OnCollisionEnter(col : Collision) {
      if(col.gameObject.tag == "Player"){
      col.gameObject.SendMessage("DecreaseHealth");
      }
}

notice I send the message to the actual object that collided (“col”), no need for GameObject.Find

to add the tag to your player, just select the object and use the tag dropdown at the top of the inspector (you can choose “Add Tag” to make a new tag if you want)

but I think what you want is for the enemy to set it’s var “target” to the player, if so, add this to the script:

function Awake(){
target = GameObject.Find("Player").GetComponent(Transform);
}

note that this finds the object by the name of the object, by tag you would say

target = GameObject.FindWithTag(“Player”).GetComponent(Transform);

hope that answers your question