Passing variable from one script to another and making an enemy flee

Ive seen a few questions similar to mine but I can’t get it working for my particular need.

I have 2 scripts both in JavaScript, EnemyHealth.js and BasicAI.js . In EnemyHealth.js I have an int variable called Health. I want to pass this over as a variable within BasicAI.js so that I can check whether the enemies health is below a certain range. Both scripts are attached to a game object ‘Enemy’.

The second part of my question is, if var Health is below a certain amount (say, 20) I want a function flee() to be called. How would I make the enemy turn away from the player and proceed to move away ?

I think this is what you want. In your basicAI script, you should put the following script. In update, enhealth is being set constantly, because it is in update. If it is less than 20, then the flee function will run. The first part of flee sets the rotation, and the second part moves the object.

function Awake(){
var enhealth : int;
}

function Update(){
enhealth = gameObject.GetComponent(EnemyHealth).health;
if (enhealth <= 20){
flee();}
}

function flee(){
gameObject.transform.localEulerAngles = new Vector3(0,180,0);
transform.Translate(Vector3.forward * Time.deltaTime);
}

Keep in mind that this is off the top of my head, so here are some other questions to further your research.
http://forum.unity3d.com/threads/rotate-180.18874/

Lastly, I answered this with a written script because I think you weren’t able to find exactly what you needed. Learn to combine the answers you see, do trial and error and think outside of the box. That’s what code is all about.

Don’t really do js but the theory is the same for C#.

Reference the script

var BasicAI : BAIscript;

assuming they’re both on the same GameObject you could reference the script with

BAIscript = Component.GetComponent(BasicAI);

Then when you want to call the function

BAIscript.flee();

As for the second part that really depends on how your working your game. Do you have a NavMesh for you characters?

If you do just pick a random x and z offset from your current location make sure it’s further away from the player than you currently are and tell it to move there. I could post my random movement script but it’s in C#.

It’s not perfect as it can occasionally pick somewhere where it effectively runs past the player but I’ve seen similar behavior on big production games.

Sorry if my java isn’t spot on.