user10388389
user10388389

Reputation:

When i destroy my object create new one in diffrent position

When i click on my mouse button and destroy GameObject i want to create new one on random position, i try instatiate and other methods but it didn't work can someone help me whit this?

public GameObject tapObject;
private float respawnTime = 1f;
public float xMin;
public float xMax;
public float yMin;
public float yMax;

void Start()
{     
    StartCoroutine(spawnEnemyTime());
}
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {           
        Destroy(tapObject);
    }      
}
private void RandomSpawnObject()
{      
    tapObject.transform.position = new Vector2(Random.Range(xMin, xMax), Random.Range(yMin, yMax));
} 
IEnumerator spawnEnemyTime()
{
    while (true)
    {
        yield return new WaitForSeconds(respawnTime);
        RandomSpawnObject();
    }
}

Upvotes: 0

Views: 78

Answers (2)

Hamza Tahir
Hamza Tahir

Reputation: 92

The simple way to resolve your problem is to create a method and call it with a timer and in that method just use following code

Code

Vector3 position = new Vector3(Random.Range(-10.0f, 10.0f), 0, Random.Range(-10.0f, 10.0f)); Instantiate(prefab, position, Quaternion.identity);

Note

Instead of using the prefab use you can use the gameobject you are using in the application

Upvotes: 0

Kokolo
Kokolo

Reputation: 260

If you want to keep the same GameObject you can avoid destroying it, instead you can control if it's active or not. It should look like this:

Edit:

Using GameObject.SetActive()

public GameObject tapObject;
private float respawnTime = 1f;
public float xMin;
public float xMax;
public float yMin;
public float yMax;

void Start()
{

}
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        tapObject.SetActive(false);
        StartCoroutine(spawnEnemyTime());
    }
}
private void RandomSpawnObject()
{
    tapObject.SetActive(true);
    tapObject.transform.position = new Vector2(Random.Range(xMin, xMax), Random.Range(yMin, yMax));
}
IEnumerator spawnEnemyTime()
{
    yield return new WaitForSeconds(respawnTime);
    RandomSpawnObject();
}

Using GameObject.Instantiate()

public GameObject prefab;
public GameObject tapObject;
private float respawnTime = 1f;
public float xMin;
public float xMax;
public float yMin;
public float yMax;

void Start()
{

}
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Destroy(tapObject);
        StartCoroutine(spawnEnemyTime());
    }
}
private void RandomSpawnObject()
{
    tapObject = GameObject.Instantiate(prefab, new Vector2(Random.Range(xMin, xMax), Random.Range(yMin, yMax)), Quaternion.identity);
}
IEnumerator spawnEnemyTime()
{
    yield return new WaitForSeconds(respawnTime);
    RandomSpawnObject();
}

Note that when using GameObject.Instantiate(), you need to have a prefab attached.

Upvotes: 2

Related Questions