I’m trying to instantiate 16 objects (in a grid 4x4) and assign each object a value and ID dependent on the random number that is generated when the object is instantiated.
The code below is present on each prefab. The timer on the same object calls the function below and it generates the number to assign a texture to that object, id and value.
The problem that I am having is that when I click on any block that’s instantiated, I get the value and ID of the last block only. I have printed out when all values are assigned so I know that the blocks are getting different values set, but they seem to be getting over written some where.
I think it is because I am instantiating the objects all called the same name, but I’m a beginner and not 100% certain.
Can anyone tell me my mistake? And is there a more efficient way to do this?
Are you running this as a calling this method from either your setupGame or setupBoard scripts? Because you don’t appear to be making this a coroutine of Update. Also, I believe you should be instantiating as an instance of the prefab … so as in a new variable. This may be why you’re getting the same values. Anyway, this is how I would do it:
var cube : GameObject;
function SwitchBlock(){
setupBoard.randomNumber = Random.Range(0, setupGame.textureArray.length);
var cubeInst : GameObject = Instantiate(cube, transform.position, transform.rotation) as GameObject;
cube.renderer.material.mainTexture = Resources.Load("Textures/" + setupGame.textureArray[setupBoard.randomNumber], Texture2D);
cubeInst.GetComponent(setLetter).points = setupGame.setLetters[setupBoard.randomNumber, 1];
cubeInst.GetComponent(setLetter).id = setupGame.setLetters[setupBoard.randomNumber,0];
print(cubeInst.GetComponent(setLetter).points);
}