- Home /
Instantiate ground/enemies
I'm making a 2D side scroller game, and I'm trying to instantiate the pieces of ground in front of character, and to destroy them after a few seconds, but I don't know how to do. This code I use for the enemies and for the ground, but they are instantiated sometimes up, and sometimes down. How can I fix it and instantiate both in the same X position? I'm new in this.
(Sorry bad english! Hope you understand!)
using UnityEngine;
using System.Collections;
public class SpawnScript : MonoBehaviour {
public GameObject[] obj;
public float spawnMin = 6f;
public float spawnMax = 7f;
// Use this for initialization
void Start ()
{
Spawn ();
}
void Spawn ()
{
Instantiate(obj[Random.Range (0, 0)], transform.position, Quaternion.identity);
Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
}
}
Answer by HammerCar · Mar 13, 2015 at 08:53 PM
I am guessing that the SpawnScript is on your player. You are using transform.position and so it takes the y value of your player too. To fix this replace the transform.position with new Vector3 (x, y, z). x is your x value, y should be the y value that you want and z should be 0.
if you want to instantiate your objects in front of the player you should do something like transform.position.x + 2f for the x value. Adjust the value to be what you need.
To destroy the ground you can do something like this:
void Spawn ()
{
GameObject ground = (GameObject)Instantiate(obj[Random.Range (0, 0)], new Vector3 (x, y, z), Quaternion.identity); // Cast it as a GameObject and making it a variable
StartCoroutine (DestroyGround (ground)); // here we are calling the DestroyGround method
Invoke ("Spawn", Random.Range (spawnMin, spawnMax));
}
IEnumerator DestroyGround (GameObject ground) {
yield return new WaitForSeconds (s); // s should be the time after the ground is destroyed
Destroy (ground); // here we destroy the ground
}