- Home /
Enemy spawn then select target?
Hello I have a game where the enemies spawn from a point, but when the enemy spawns it needs to know the player prefab so it can chase and attack it. Heres my script
var speed : int = 5;
var rotationSpeed : int = 7;
var distance : int = 20;
var enemy : Transform;
function Update(){
var victim = enemy;
var dist = Vector3.Distance(victim.position, transform.position);
if(dist < distance){
target = victim;
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(target.position - transform.position),rotationSpeed * Time.deltaTime);
transform.position += transform.forward * speed * Time.deltaTime;
}
}
How can I make it so that when my enemy spawns the variable player is set to my player?
Thanks.
Answer by SirGive · May 29, 2011 at 08:04 AM
This happens a lot. The easiest way that I have found to solve this problem is to create a gameobject and set it equal to the player on the start or awake function. These are called either when the object is created or when the scene starts. Which ever the object exists in first.
var plyr : GameObject;
function Start()
{
plyr = GameObject.FindWithTag("Player");
//plyr = GameObject.Find("Player"); //or find the name of the object
}
Just make sure you set the tag on your player object to "Player".
Now you have full access to your player (not the scripts however) and can move toward him.
I've already tryed that it says BCE0019: 'position' is not a member of 'UnityEngine.GameObject'. and when I make it
var enemy : Transform;
and
enemy = transform.Find("Player")
it says NullReferenceException UnityEngine.Transform.get_position ()
But thanks any way
thats because enemy needs to be a GameObject, not a transform.
var enemy : GameObject
NOT
var enemy : Transform;
Alternatively, enemy.position might just work