- Home /
2d AI: enemy targeting c#
Hi
I'm developing a 2d game where I spawn ally units from left to right. I'm trying to get my enemy units to fire a projectile at the ally units once they come within range on the x axis. My script works fine if I have an ally unit already placed in the scene but if I start the scene without a pre-spawned ally there is an error that says: UnassignedReferenceException: The variable target of 'Enemy' has not been assigned. Here is my enemy script:
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("AllyTag");
target = go.transform;
SetPositionAndSpeed();
}
// Update is called once per frame
void Update () {
float amountToMove = currentSpeed * Time.deltaTime;
transform.Translate(Vector3.left * amountToMove);
StopAndShoot();//if target comes within range
}
public void SetPositionAndSpeed(){
//getting speed
currentSpeed = Random.Range(MinSpeed, MaxSpeed);
}
void StopAndShoot(){
x = transform.position.x;
c = target.position.x;
if(c>=x-6){
currentSpeed = 0;//stop
Instantiate (BulletPrefab,transform.position,Quaternion.Identity);//fire bullet
}
}
}
If anyone can help it would be great. Regards Vinny
Answer by kgoswami · Oct 04, 2011 at 10:11 PM
If there is no object int the game scene with "allytag" tag, then the Find will return a NULL. Put an if statement checking fora NULL first. If it is not Null then do ur thing.
Also when u spawn an enemy, check its name in the haeirarchy, it could have a (Clone) attached behind its name. You can check for the name as well and assign it a new name when it is spawned.
Null checking is always a good idea; but note this wont help your underlying problem;
You assign the GO to a variable at Start(), so any other time a new ally thing spawns, your enemies wont pick it up.
You would have to loop a co-routine to query the current ally things in scene, and choose one to target onto. You would turn off the loop at this point until the enemy is ready to search for a new ally thing.
$$anonymous$$atty
Answer by VinnyG · Oct 07, 2011 at 12:01 AM
Thanks for the advice guys. I have it working now using the co-routine method.
Your answer
Follow this Question
Related Questions
Simple AI In 2D - C# 1 Answer
[C#] Raycasts and Object Tags 1 Answer
Basic 2d AI follow? 1 Answer
A* pathfinding for 2D top Down 0 Answers
Check lenght from player? 2 Answers