- Home /
help with if(hit.gameObject.tag)
Hey I try to add health at an ennemy
here is my enemy's scrip
var vie : int = 500;
function OnCollisionEnter (hit : Collision)
{
if(hit.gameObject.tag == "bullet")
{
vie -= 25;
Debug.Log (vie);
if (vie <= 0){
Destroy(gameObject);
}
}
}
and here's the shot script on my character
var bullet : Transform;
var speed = 650;
var Speed = 10;
var spawnPoint : Transform;
var rapidFire = false;
var counter = 0.0;
var rateOfFire = 0.25;
var ennemydeux : Transform;
function Update ()
{
CheckClick();
}
function CheckClick()
{
if(Input.GetButtonDown("Fire1") || (rapidFire && Input.GetButton("Fire1")))
{
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
// you can set the 100 to whatever distance you want :P
if (Physics.Raycast(ray,hit,100))
{
var enemy = hit.transform.GetComponent(ennemy);
if(hit.transform.GetComponent(ennemy))
{
transform.LookAt(ennemydeux);
HandleFiring();
}
}
}
}
function HandleFiring()
{
if(rapidFire)
{
counter += Time.deltaTime;
// I'm going to assume RateOfFireCounter is a variable that you've not shown here? Otherwise this won't do anything for you...
if(rateOfFire)
{
var shotRapid =Instantiate(bullet, spawnPoint.transform.position, Quaternion.identity);
shotRapid.rigidbody.AddForce(transform.forward * speed);
shotRapid.transform.LookAt(ennemydeux);
shotRapid.transform.Translate(Vector3.forward*Speed*Time.deltaTime);
Destroy((shotRapid.gameObject), 2);
Counter=0;
}
}
else
{
var shot = Instantiate(bullet, spawnPoint.transform.position, Quaternion.identity);
shot.rigidbody.AddForce(transform.forward * speed);
shot.transform.LookAt(ennemydeux);
shot.transform.Translate(Vector3.forward*Speed*Time.deltaTime);
Destroy((shot.gameObject), 2);
}
And the problem is, when the bullet hit my enemy, his life stay at 500. When I remove the part of my script: == "bullet" the enemy lose life when anything hit him.
are you 100% sure the tag of your bullet game object is exactly "bullet"?
Right before that if
, add Debug.Log("tag=" + hit.gameObject.tag);
What tag does it show when the bullet hits?
So now you should either close the question using the button near the edit, more, ... below the question or one of you the ones who commented convert their question to an answer so that you can accept it.
$$anonymous$$y first problem is solved. But now, when I kill my ennemy I have the error "The object of type "Transform" has been destroyed but you still try to access it"
How can I do ?
Your answer
Follow this Question
Related Questions
How to create Enemy Health Bar ? 4 Answers
One enemy triggers all the enemies 2 Answers
Change Health of a duplicated enemeis 1 Answer
Health to come above enemy when clicked 1 Answer
Problem with 2 scripts communicating 0 Answers