- Home /
Instantiate prefab with different tag
Is it possible to instantiate same prefab but with different tag based on position in game. Like if prefab(clone) x position is between 0 and 64 it would have tag "first", prefab(clone) between 64 and 128 would have tag "second"..
I'm using for loop for instantiating prefabs. It just instantiate cubes one beside other (128* 16) length and width.
Some tips on how could I achive that if it is even possible would be appreciated.
dang it! those two beat me to it while i was typing my answer! good job with the quick replies.
Answer by rednax20 · Apr 14, 2014 at 08:41 PM
sure, you can access a prefab after you instantiate it by setting it's value to another gameobject
var clone : GameObject; //you don't need to asign this to anything in the inspector
for(var i = 0; i < 128; i++){ //i'm assuming this is how you are doing it, if not just apply the clone accessing to your code
if(i < 65){
clone = Instatantiate(prefab, Vector3(0,0,0), Quaternion.Identity
clone.tag = "first"
}
if(i > 64){
clone = Instatantiate(prefab, Vector3(0,0,0), Quaternion.Identity
clone.tag = "second"
}
}
this give sort of an example of what you want to do, except that person wanted to get a component while you just wanted to change the tags of the object
good luck!
What I do Wrong ? I have code and code doesnt tagged new object until i didnt have tagged my prefabs. Why ?
for (int y = 1; y < 2; y++)
{
for (int x = 0; x < 6; x++)
{
GameObject block = Instantiate(blocks, new Vector2(x, y), Quaternion.identity) as GameObject;
block.transform.parent = this.transform;
GameObject positionOfNumber = block.transform.Find("PositionOfNumber").gameObject;
GameObject number = Instantiate(numbers[x], positionOfNumber.transform.position, Quaternion.identity) as GameObject;
number.transform.parent = block.transform.GetChild(0) ; // rodic objektu number bude dieta objektu block
block.gameObject.tag = x.ToString(); //otagovanie objektu
}
}
}
Answer by robertbu · Apr 14, 2014 at 08:34 PM
Just assign the tag at runtime. Something like:
var go : GameObject = Instantiate(prefab, pos, Quaternion.identity);
if (pos.x < 64) {
go.tag = "first";
}
else if (pos.x < 128) {
go.tag = "second";
}
else {
go.tag = "third";
}
Note your position values sound like they might be screen positions. If so, you'll need to convert the world position for the instantiate into a screen position using Camera.WorldToScreenPoint().
Answer by MasterPDON · Apr 14, 2014 at 08:35 PM
Remember that you can change the tag of Game Objects during runtime.
public GameObject newPrefab;
public GameObject prefab;
void Start(){
newPrefab = (GameObject)Instantiate (prefab, transform.position, Quaternion.identity);
newPrefab.tag = "NewTag";
}
Answer by trane294 · Apr 14, 2014 at 08:47 PM
You can do gameObject.tag or change prefab(clone) name gameObject.transform.name
gm = Instantiate(prefab, prefab.transform.position, Quaternion.identity);
gm.tag = "second";