Question by
Pendleburt · Apr 23, 2016 at 08:17 PM ·
scripting problemaienemy
Attaching objects to scripts without dragging and dropping
I'm working on a game and I'm currently stuck with trying to get objects and scripts attached without dragging them into the inspector. Basically I have enemy prefabs that start spawning on Start (); and I need them to target the player that is in the scene.
Here is my code for my Enemy AI.
using UnityEngine; using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public static float speed = 4f;
public float minDistance = 1f;
public float range;
void Start ()
{
target = GameObject.Find("Player");
}
void Update ()
{
range = Vector2.Distance(transform.position, target.position); //Sets the range for the enemy to find and follow the player
if (range > minDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime); //Moves the enemy towards the player
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Trouble making jumping spider enemies 0 Answers
AI Enemy Goomba Style (Super Mario 1 Answer
How do I get my enemy to flip to face the direction he is moving? 3 Answers
Ai sprite animation 8 directional movement 0 Answers
Enemy Chasing player? 0 Answers