Spawning Multiple Robots - From FPS Tutorial

Hi,

Im fairly new to Unity. I finished the FPS tutorial and am trying to spawn a Robot every second at a spawn point. The problem is, when I spawn them they are doing nothing because they do not have a target set.

I am scripting this modification in C#, and I am unsure how to set the target for each robot instance after instantiating it.

I tried GetComponent(“AI”) with no luck. AI being the js script that has the variable for the target.

Thanks

FindObjectsOfType

choose any (except yourself) from the list

If you’re using Instantiate to create your robots, then you probably want to use the value returned by Instantiate. If you’re instantiating a prefab with a script called “AI” attached, you need something like this:

GameObject thisObj = Instantiate(Robot,  pos, rot);
AI thisAI = thisObj.GetComponent(typeof(AI));
thisAI.target = player;

or in javascript:

thisObj : GameObject = Instantiate(Robot, pos, rot);
thisAI : AI = thisObj.GetComponent(AI);
thisAI.target = player;

hope this helps!

(edit - updated to match the script name you mentioned!)

Hi. I’ve been struggling to get this to work, maybe you can help.
I have 2 scripts: one that spawns enemies (enemySpawner.js) and one that has AI (enemyAI.js).
The spawn script is on a gizmo that’s in the level (hierarchy). The AI script is on the enemy prefab in the project viewer.
The AI script has variable ‘leader’ that should point to the player prefab when instantiated. I also gave the player prefab the tag of ‘Player’.
So this is what my spawn script looks like:

function spawnEnemy()
{
	thisObj : GameObject = Instantiate(enemy, transform.position, Quaternion.identity); //line 35
	thisAI : enemyAI = thisObj.GetComponent(enemyAI); //line 36
	thisAI.leader = Player; //line 37
}

But I’m getting the following error:

Assets/myScripts/tkEnemySpawner.js(35,17): BCE0043: Unexpected token: :.
 
(Filename: Assets/myScripts/tkEnemySpawner.js Line: 35)

Assets/myScripts/tkEnemySpawner.js(35,18): UCE0001: ';' expected. Insert a semicolon at the end.
 
(Filename: Assets/myScripts/tkEnemySpawner.js Line: 35)

Assets/myScripts/tkEnemySpawner.js(36,16): BCE0043: Unexpected token: :.
 
(Filename: Assets/myScripts/tkEnemySpawner.js Line: 36)

Assets/myScripts/tkEnemySpawner.js(36,17): UCE0001: ';' expected. Insert a semicolon at the end.
 
(Filename: Assets/myScripts/tkEnemySpawner.js Line: 36)

I also tried this syntax:

function spawnEnemy()
{
	thisObj = Instantiate(enemy, transform.position, Quaternion.identity);	
	thisAI = thisObj.GetComponent(enemyAI);
	thisAI.leader = "Player";
}

but get this error:

InvalidCastException: Cannot cast from source type to destination type.
(wrapper dynamic-method) enemyAI.enemyAI$leader= (object,object[]) <0x0002e>