vendredi 28 août 2020

How to handle a random spawner of obstacles in unity?

I'm trying to handle a object spawner but it isn't work as i wish. It should create a new object every time my timer pass the maxTime of the object, but it does it just once and in the wrong position (out of my range). Here is my code:

public class Spawner : MonoBehaviour {

    public float maxTime = 10;
    private float timer = 0;
    public GameObject obstacle;
    private float width = (Screen.width)/2; //It doesn't recognize width as the variable that refeers the width of the screen, so i tried it
    private float maxTime0 = 10;
    public int pontos = 5;
    public float score;

    void Start() {
        GameObject new_obstacle = Instantiate(obstacle);
        new_obstacle.transform.position = transform.position + new Vector3(Random.Range(-width, width), 0, 0);
    }

    void Update()
    {
        if(timer > maxTime) {
            GameObject new_obstacle = Instantiate(obstacle);
            new_obstacle.transform.position = transform.position + new Vector3(Random.Range(-width, width), 0, 0);
            if(new_obstacle.transform.position.y < (Screen.height - 7)){
                DestroyImmediate(new_obstacle, true);
            }
            timer = 0; 
            maxTime = 0.9f * maxTime;
        }
        score += pontos; 
        timer += Time.deltaTime; 
    }
}



Aucun commentaire:

Enregistrer un commentaire