0
\$\begingroup\$

I am having trouble spawning some obstacles from some prefabs. The aim is to make and endless runner (like normal) with obstacles to go through that spawn as the sprite goes up. But my prefabs don't spawn at the top?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RandomSpawn : MonoBehaviour
{    
    public GameObject B1, B2;    
    public float spawnrate = 2f;    
    float nextSpawn = 0f;    
    int whatToSpawn;     

    void Update()
    {
        if (Time.time > nextSpawn)
        {   
            whatToSpawn = Random.Range(1, 3);
            Debug.Log (whatToSpawn);

            switch (whatToSpawn)
            {
                case 1:
                    Instantiate(B1, transform.position, Quaternion.identity);
                    break;    
                case 2:
                    Instantiate(B2, transform.position, Quaternion.identity);
                    break;
            }

            nextSpawn = Time.time + spawnrate;
        }
    }
}
\$\endgroup\$
0
\$\begingroup\$

Your code spawns the obstacles at transform.position which refers to the position of the game object this script is attached to.

So you just have to move the game object with this script to the location where you want the objects to spawn.

I am not sure what exactly you mean with "go through that spawn as the sprite goes up". But if it means that you want the spawn location to somehow change throughout the game, then you would either have to add some code to move the position of this game object or you would have to stop using transform.position as the instantiation location and instead create a new Vector3 with the spawn coordinates you want.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.