How to set gameobject dynamically in script?
I am a newbie in unity i don't even know if my question is very clear but please try to help me im really trying hard anyway. I am making a checker like game so i already have a board and a checker piece that can move anywhere on the board but my problem is my gameObject selectedUnit is fix and i don't know how to dynamically change it in run time. This is my code.
public GameObject selectedUnit; //<--------------This is my problem i think I want this to be assign depending on what checker piece i click on the board how can i do that?
public TileType[] tileTypes;
int[,] tiles;
int boardSizeX= 8;
int boardSizeY= 8;
void Start() {
GenerateBoardData ();
GenerateMapVisual();
}
void GenerateBoardData(){
//Declare board size.
tiles = new int[boardSizeX, boardSizeY];
//Initialize board tiles
for(int x=0; x < boardSizeX; x++){
for(int y=0; y < boardSizeY; y++){
//Initializing the color of the board.
if ((y % 2) == 0) {
if((x % 2) ==0)
tiles [x, y] = 0;
else
tiles [x, y] = 1;
} else {
if((x % 2) ==0)
tiles [x, y] = 1;
else
tiles [x, y] = 0;
}
}
}
}
//This code is just for displaying the board for the game.
void GenerateMapVisual(){
for(int x=0; x < mapSizeX; x++){
for(int y=0; y < mapSizeY; y++){
TileType tt = tileTypes [tiles [x, y]];
GameObject go = (GameObject)Instantiate( tt.tileVisualPrefab, new Vector3(x, y, 0), Quaternion.identity);
TileClickHandler ct = go.GetComponent<TileClickHandler> ();
ct.tileX = x;
ct.tileY = y;
ct.map=this;
}
}
}
public void MoveSelectedUnitTo(int x, int y){
selectedUnit.transform.position = new Vector3 (x, y, 0);
}
I think i need to make a script for all of my pieces but i dont know what i should i do please help.
Although i didn't got your question, but tried to understand, if you want to keep a track of an item/selected item... you can create one/two variables (selectedX, selectedY) and then set their values whenever you alter them or something like this... hope this will help :) or can you explain a little bit what exactly you want to do....
Thank you for replying. Sorry if my question is unclear but this is what i reallly want to happen. So i have a public GameObject selectedUnit how can i make this dynamic? What i did first is i drag the piece in the hierarchy to the inspector but that doesn't do the job because i can only move 1 piece and not the other on the game mode.
Your answer
Follow this Question
Related Questions
Freezing Prefab or deactivating its script in another? 0 Answers
How to Respawn an gameObject when it touch another gameObject 1 Answer
Object reference not set to an instance of an object when trying to instantiate 0 Answers
Disable 2 Scripts during Countdown 1 Answer
How do i make a game object grow by absorbing another game object ? 0 Answers