- Home /
Assigning id to instantiated objects
Hi Im trying to make a multiplayer game wherein a number of enemies have to spawn when a player enters a trigger box and I need to assign each enemy a unique ID for later use. The spwaning enemies can be one of two different prefabs. The prefabs have both a script attachted called EnemyID which stores an int called 'ID' and another script for controlling their behavior.
The code for instantiating the prefabs is: public GameObject aISmallPrefab; public GameObject aIMediumPrefab;
public void SpawnAI(int id, NetworkTransform ntransform, string aIType) {
GameObject aIPrefab = null;
if (aIType == "AISmall") {
aIPrefab = aISmallPrefab;
}
else if (aIType == "AIMedium") {
aIPrefab = aIMediumPrefab;
}
GameObject aIObj = GameObject.Instantiate(aIPrefab) as GameObject;
aIObj.transform.position = ntransform.Position;
aIObj.transform.localEulerAngles = ntransform.AngleRotationFPS;
aIObj.GetComponent("EnemyID").ID = i
}
The SpawnAI is called everytime an enemy is to be spawned and recieves an interger (the id), a transform and a string (what type of enemy to be spawned).
I really can't get unity to assign the ID so i can access it in the behavior scripts for the enemies.
This is my first time using unity and I can never really seem to get GetComponent working.
Answer by dweitkunat · Nov 23, 2011 at 05:29 PM
This all looks good but in C# you must use typecasting with GetComponent. So,
aIObj.GetComponent<EnemyID>().ID = i;
If this doesn't work, show me any errors or warnings Unity throws that are specific to this problem.
Your answer
Follow this Question
Related Questions
Instantiate ID 2 Answers
GetComponent don't work (i am desperate) 0 Answers
Instantiate And GetComponent 1 Answer
Change a variable of an Instantiated object 2 Answers
How do I instantiate at a certain point? 2 Answers