- Home /
remove and replace item in grid
Hello all. I have code set up which builds a 4X4 grid, after one item is touched on the grid, it is destroyed/ removed from the grid. I want my code to identify where the item was destroyed/removed on the grid and automatically replace it with a new prefab clone after one second. Can someone help me with this? Here is my code and an image to assist :
import System.Collections.Generic;
var circles : List.<GameObject> = new List.<GameObject>();
var gridheight : int = 4;
var gridwidth : int = 4;
var circle : GameObject;
function Start () {
}
function Update () {
if ( circles.Count < 16){
for ( var y = 0; y<gridheight; y++){
for (var x=0; x<gridwidth; x++){
var g : GameObject = Instantiate(circle, Vector3(x,y,0), Quaternion.identity);
g.transform.parent = gameObject.transform;
circles.Add(g);
}
}
gameObject.transform.position =new Vector3(-1.47,-1.41,0);
}
}
Answer by matthewbauer · Dec 26, 2014 at 06:11 AM
It looks like you are just replacing the object with an exact copy, so instead of Instantiating a new one, just move the circle below the map/offscreen. If that will work, then you could add a script to the circle prefab like the following. Then only instantiate the circles once. You will also have to add a BoxCollider or something do your circle prefab.
You could also use a similar method if you want to instantiate different objects, but it would probably have to be done in a central script like you are trying now.
This is going to be in C# :p
static float respawnTime = 1; // time to respawn in seconds
bool wasClicked = false;
Vector3 originalPosition;
float clickedTime = -1;
void Start(){
originalPosition = transform.position;
}
void OnClick(){
wasClicked = true;
transform.position = new Vector3(-300,-300,-300); //Offscreen
clickedTime = Time.now;
}
void Update(){
if (wasClicked && Time.time > clickedTime + respawnTime){
transform.position = originalPosition;
wasClicked = false;
}
}