I have an enemy that works exactly how I want it too. He looks at the player and moves towards him. Once close enough, it begins attacking. Perfect. But when I create a prefab for the enemy and player, and place the player's prefab into the transform slot in the inspector for the enemy to know what to look at it gets all jacked up. I put the new prefab into the scene and it turns to where the player's position was when I created the prefab, and begins to move there. Once there, even if i move the player to the other side of the level, it begins to deal damage to the player when he's not even there. It still happens when I bring in the prefab for the main character. But the original enemy always works great. Here is my enemy AI script:
var mainChar:Transform; //a link to our main character's transform component
var theShrimpHealthCount: int = 5;
var followRange:float = 3.0; //inside this range the shrimp will FOLLOW the player.
var attackRange:float = 0.75; //inside this range the shrimp will ATTACK the player.
var moveSpeed:float = 2.0; //how fast our shrimp moves
//for attacking
var shrimpAttackDelay:float = 0.15; //how long to wait between attacks in seconds
private var nextAttack:float = 0.0; //keeps track of the time in seconds the shrimp will be able to attack next
function Start()
{
transform.LookAt(mainChar);
}
function Update()
{
//get distance between shrimp.x and mainChar.x each frame
//Mathf.Abs returns the Absolute value so we always have a positive distance
var theDistance:float = Mathf.Abs(transform.position.x - mainChar.position.x);
//if within our attack range
if(theDistance <= attackRange)
{
Attack();
}
//else if within our follow range or if we have already been aggroed.
else
{
//have shrimp face character
transform.LookAt(mainChar);
//move forward at speed
transform.Translate(0,0,moveSpeed * Time.deltaTime);
}
}
function Attack() {
//Time.time returns the number in seconds since the game started (right now)
//if Time.time has passed the time we set for our next attack, go ahead and attack
if(Time.time > nextAttack && mainGamePlayScript.playerAlive == true)
{
//Reference main game play script and subtract 1 from the health count
mainGamePlayScript.theHealthCount --;
if(mainGamePlayScript.theHealthCount <= 0)
{
mainGamePlayScript.playerAlive = false;
}
//now that we have attacked, we need to reset our next attack variable.
//we want it to be (attackDelay) seconds from right now
nextAttack = Time.time + shrimpAttackDelay;
}
}
function hurtShrimp(Damage: int)
{
theShrimpHealthCount -= Damage;
if(theShrimpHealthCount <= 0)
{
Destroy(gameObject);
mainGamePlayScript.theScoreCount ++;
}
}