- Home /
Ai finding target after spawning
Edit* Updated the code with the now Working code for others to look at. )
ok, basically the problem I'm having is that there seems to be no way of getting the AI to target the player after it spawns. I've tried having it find the player tag, but unity always says that transform and gameobject can't work together. basically i just need the enemy to automatically find the player and attack. If anyone could help it would be greatly appreciated.
heres the code
static var health : float = 100.0; var player = transform; var speed = 5.0; var chaseRange = 50.0; var force = 1; private var controller : CharacterController;
function Awake(){
player = GameObject.FindWithTag("Player").transform;
}
function Start() { controller = GetComponent(CharacterController); }
function Update() { if (player == null) animation.CrossFade ("Idle"); else;
var range = Vector3.Distance(player.position, transform.position);
if (range <= chaseRange)
{
transform.LookAt(player);
var moveDirection : Vector3 = transform.TransformDirection(Vector3.forward);
controller.Move(moveDirection * Time.deltaTime * speed);
animation.CrossFade ("Walk");
}
}
function OnTriggerEnter(collision : Collider) { if(collision.gameObject.tag == "Player"){ transform.Translate(0, 5, -3); animation.CrossFade ("Lunge"); //print("push back"); } }
function OnCollisionEnter(collision : Collision){ //If it collides with the player's bullet, run the apply damage function if(collision.gameObject.tag == "BulletPlayer"){ ApplyDamage(); print("hit"); } }
var hitPoints = 10;
function ApplyDamage(){ //subtract 5 hitPoints hitPoints -= 5; //if the remaining hitPoints are more than zero, do nothing if(hitPoints > 0){ return; } //if the remaining hitPoints are less than zero, run the die function if(hitPoints <= 0){ Die(); } }
function Die(){ Destroy(gameObject); }
Answer by Persona · May 03, 2011 at 06:34 PM
Add a function Awake to search for the tag player:
function Awake(){
player = GameObject.FindWithTag("Player").transform;
}
That way, the moment it spawns, the player is set.
Thanks, i was really tired that day and kept putting this in a start function.
Answer by red 2 · May 03, 2011 at 03:11 PM
check the FPS tutorial, it features an AI that moves around til it sees the player, then attacks. you might want to use it as a base for your own
Your answer
Follow this Question
Related Questions
random target selection 2 Answers
Can't make enemy respawn 0 Answers
Can't do spawning 0 Answers
AI moving forward without spawnpoints? 2 Answers
What would be the best way to setup Target priority 1 Answer