Hi,
I am trying to instantiate 6 different players from the same prefab. On Awake() I am spawning them and assigning them different stats. The code below works, but for some reason, they are all named “Charlotte de Beer”. What am I doing wrong?
var player : GameObject[];
var numberOfPlayers : int = 6;
function Awake() {
for(var x=0; x < numberOfPlayers; x++){
Instantiate(player[x], Vector3(x * 2.0, 1.38, 3), Quaternion.identity);
player[x].name = "player" + x;
}
player[0].GetComponent(playerScript).setStats("Harry", "Blotten");
player[1].GetComponent(playerScript).setStats("Henk", "Bats");
player[2].GetComponent(playerScript).setStats("Maria", "Hernandez");
player[3].GetComponent(playerScript).setStats("Fritz", "Bats");
player[4].GetComponent(playerScript).setStats("Karel", "Kaas");
player[5].GetComponent(playerScript).setStats("Charlotte", "de Beer");
}
In playerScript (this is attached to the prefab):
var firstName : String;
var lastName : String;
function setStats(fname , lname)
{
firstName = fname;
lastName = lname;
}
Hi,
I would suggest you that you use the i variable for an for iteration and to name the player variable to players because there are multiple players in that array.
Now to your problem, you have to set the instantiate call into a variable, which you then can access and set the name of the object. This is comparable when you get an GameObject by it’s tag.
var theObject : GameObject = GameObject.FindWithTag("TheTag");
theObject.name = "TheName";
Anyways I correvted your code, as I think it should be achieved.
Code:
var players : GameObject[];
function Awake() {
for(var i = 0; i < players.Length; i++) {
var playerInstance = Instantiate(players[i], Vector3(i * 2.0, 1.38, 3), Quaternion.identity);
playerInstance.name = "player" + i;
}
players[0].GetComponent(playerScript).setStats("Harry", "Blotten");
players[1].GetComponent(playerScript).setStats("Henk", "Bats");
players[2].GetComponent(playerScript).setStats("Maria", "Hernandez");
players[3].GetComponent(playerScript).setStats("Fritz", "Bats");
players[4].GetComponent(playerScript).setStats("Karel", "Kaas");
players[5].GetComponent(playerScript).setStats("Charlotte", "de Beer");
}
realm_1