- Home /
How to Instantiate a game object at the same position where the previous is destroyed
I have multiple empty game objects that serves as the spawn points that spawns the game objects and I want the spawned game objects to be destroyed and Instantiate a new one on same spawn point if the condition to be tested is true.
I have 2 separate scripts, the on attached on the spawn points objects and another for the game manager that has the condition in it.
The Condition on the Game manager script:
public void checkword()
{
wordBuilded = displayer.text.ToString();
LetterTiles[] tiles = FindObjectsOfType<LetterTiles>();
foreach (LetterTiles item in tiles)
{
if (txtContents.Contains(wordBuilded))
{
if (item.gameObject.CompareTag("clicked"))
{
Destroy(item.gameObject);
FindObjectOfType<letterSpawner>().refresh();
}
}
else
{
if (item.gameObject.CompareTag("clicked"))
item.GetComponent<Button>().interactable = true;
}
}
}
}
The script attached to the spawn point objects that Instantiates the objects
using UnityEngine;
public class letterSpawner : MonoBehaviour {
public GameObject[] letterTiles;
GameObject tiles;
Vector3 scale = new Vector3(0.8f, 0.8f, 0);
void Start () {
refresh();
}
public void refresh()
{
int rand = Random.Range(0, letterTiles.Length);
tiles = Instantiate(letterTiles[rand], transform.position, Quaternion.identity);
tiles.transform.SetParent(gameObject.transform);
tiles.transform.localScale = scale;
}
}
Answer by R4y-GM · Nov 28, 2018 at 06:57 PM
i think it works but i don't know, am now on my phone
//get the destroyed item position
transformIT = item.GetComponent<Transform>();
istantiate(letterTiles[rand], transformIT.position, quaternion.identity)
Answer by mayur7garg · Nov 28, 2018 at 06:46 PM
Store the transform of the gameObject before you destroy it.
Add an optional (or mandatory if you like) parameter
Transform spawnTransform = transformin therefresh()method.Pass the stored transform to the refresh method.
In the Instantiate method in
refreshmethod, replacetransform.positionwith thespawnTransform.position(which is the argument which was passed to the refresh method).
I hope it works. @munggol97
Your answer