I have a loop to create a variable sized grid of blocks. Think Final Fantasy Tactics.
I want to give each block a unique name (unless anyone has a better idea for identifying the blocks at runtime)
Ideally my first block is Block00, and then 01, 11, 12 and so on.
here is my code for pumping out the blocks.
using UnityEngine;
using System.Collections;
public class GameMaster : MonoBehaviour {
public int mapLength;
public int mapWidth;
public Transform tile;
public Transform player;
void Start () {
float scale = 0;
float heightadj = 0;
float height = 0;
for (var y = 0; y < mapLength; y++) {
for (var x = 0; x < mapWidth; x++) {
scale = Random.Range(0.5f,0.5f);
height = scale;
heightadj = scale / 2;
GameObject block = Instantiate(tile, new Vector3(x* 0.5f,heightadj,y* 0.5f), Quaternion.identity) as GameObject;
block.transform.localScale = new Vector3(0.5f, height,0.5f);
block.name = "block" + x + y;
if (x == 0 y == 0){
Instantiate(player,new Vector3(x* 0.5f,heightadj+height+0.07f,y* 0.5f), Quaternion.identity);
}
}
}
}
void Update () {
}
}
note: the blocks are of variable height with their bottoms at the same point, i already got random working so i made the range constant for the moment, just in case someone wants to point that out.
That works because you are modifying the prefab before you Instantiate it.
Try this way:
GameObject newTile = (GameObject)Instantiate(tile, new Vector3(x* 0.5f,heightadj,y* 0.5f), Quaternion.identity);
newTile.name = "block_" + x +""+ y;
newTile.transform.localScale = new Vector3(0.5f, height,0.5f);
//you can then add this to a list of tiles should you want
//tiles.Add(newTile);
i switched its type to GameObject to match your suggested code. Same error. Was that a bad plan?
using UnityEngine;
using System.Collections;
public class GameMaster : MonoBehaviour {
public int mapLength;
public int mapWidth;
public GameObject tile;
public Transform player;
// Use this for initialization
void Start () {
Camera.mainCamera.transform.position = new Vector3(-5,6,-5);
float scale = 0;
float heightadj = 0;
float height = 0;
for (var y = 0; y < mapLength; y++) {
for (var x = 0; x < mapWidth; x++) {
scale = Random.Range(0.5f,0.5f);
height = scale;
heightadj = scale / 2;
Debug.Log(x + " " + y);
GameObject newTile = (GameObject)Instantiate(tile, new Vector3(x* 0.5f,heightadj,y* 0.5f), Quaternion.identity);
//newTile.name = "block_" + x +""+ y;
newTile.transform.localScale = new Vector3(0.5f, height,0.5f);
//tile.name = "block_" + x +""+ y;
//tile.transform.localScale = new Vector3(0.5f, height,0.5f);
//Instantiate(tile, new Vector3(x* 0.5f,heightadj,y* 0.5f), Quaternion.identity);
if (x == 0 y == 0){
Instantiate(player,new Vector3(x* 0.5f,heightadj+height+0.07f,y* 0.5f), Quaternion.identity);
}
}
}
}
// Update is called once per frame
void Update () {
}
}
edit: nm. i somehow linked the tile to it in the script in assests and not the gameobject the script was linked too. that one said “type mismatch” from when i switched to gameobj