- Home /
Static var health
I have a monster game where they chase you. On the raycast enter there health goes down by 5. Here is my script.
if(Input.GetButton("Fire1")){
var dir = transform.TransformDirection(Vector3.forward);
dir.Normalize();
var hit : RaycastHit;
Debug.DrawRay(transform.position, dir * distance, Color.blue);
print("You fired a ray");
if(Physics.Raycast(transform.position, dir, hit, distance))
{
if(hit.collider.gameObject.tag == "Monster")
{
health.Health -= 5;
print("You Hit Him");
}
}
}
the problem is all of the monsters have the health so if you kill one, they all die. What should I do to prevent this.
[EDIT] Here is my health script.
public var Health : int = 100;
function Update () {
if(Health <= 0){
animation.Play("die");
Destroy(gameObject, .4);
}
}
Monster Move Script :
var target : Transform;
var moveSpeed : int;
var myTransform : Transform;
var alive : boolean = true;
var stop : boolean = true;
var dead : boolean = false;
function Update () {
target = GameObject.FindWithTag("Player").transform;
if(health.Health <= 0)
{
alive = false;
}
if(alive == true && (stop == false))
{
transform.LookAt(target);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
if(target){
var dist = Vector3.Distance(target.position, transform.position);
if(dist >= 1.6){
stop = false;
}
if(dist <= 1.5){
stop = true;
}
if(stop == true){
animation.Play("attack");
playerHealth.health -= 1;
}}if(stop == false && (alive == true)){
animation.Play("run");
}
if(dist >= 2.4){
stop = false;
}
if(alive == false){
Cash.Cash += 100;
Destroy(gameObject, .5);
}
if(alive == false){
dead = true;
}
}
Answer by Piflik · Jan 04, 2013 at 08:56 PM
Don't use static variables unless you really need to (and know what you're doing)...there is only ever one instance of a static variable, because it belongs to the class itself, not to its members. Use standard public variables.
This in your enemy script: (called Enemy.js for this example, use whatever your script is actually called)
public var health : int = 10; //or whatever health you want them to have
This in your player script:
if(Physics.Raycast(transform.position, dir, hit, distance)) {
if(hit.gameObject.tag == "$$anonymous$$onster") {
hit.gameObject.GetComponent(Enemy).health -= 5;
print("You Hit Him");
}
}
var otherScript: OtherScript = GetComponent(OtherScript); otherScript.DoSomething();
what does it mean by DoSomething? I'm confused.
DoSomething() is simply an arbitrary method defined in the other script. You can't only access other scripts' variables, but also their methods, as long as they are public.
Your answer
Follow this Question
Related Questions
Why does the wrong enemy die with this raycast? C# 2 Answers
Enemy health script using raycast not destroying tagged object 1 Answer
Raycasting help, enemy damage 0 Answers
Dispenser Help 1 Answer
How can i make a ray cast take health from enemies 2 Answers