Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

374
Views
Unity: Unable to get GameObject to spawn

I am trying to get my GameObject (asteroid) to spawn continuously in the game. I looked up and followed this tutorial: https://pressstart.vip/tutorials/2018/09/25/58/spawning-obstacles.html. To make the asteroid move, I created this script (AsteroidObject) and to spawn the objects, I created this script (DeployAsteroids). There are no errors and the Debug.Log appears in the console. But the asteroid game object cannot be seen and will not spawn. Anyone can help? Thanks in advance!

Asteroid Object Codes:

public class AsteroidObject : MonoBehaviour
{
    public float speed = 10.0f; //how fast the asteroid will move 
    private Rigidbody2D rb;
    private Vector2 screenBounds; //screenbounds calculation 

    // Start is called before the first frame update
    void Start()
    {
        rb = this.GetComponent<Rigidbody2D>(); //find rigidbody 2d and  set it to rb reference by using the getcomponent
        rb.velocity = new Vector2(-speed, 0); //moving the asteroid from right to left by setting the x value, leaving the y value 0 so that it will not move up and down 
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z)); //defines the boundaries of the screen on the x and y axis
    }

    // Update is called once per frame
    void Update()
    {
        //transform.position = new Vector3(Mathf.Clamp(transform.position.x, -9f, 9f),
        //Mathf.Clamp(transform.position.y, -4f, 4f), transform.position.z);

        if (transform.position.x < screenBounds.x) //check if it is moving to the left of the screen
        {
          Destroy(this.gameObject);
          Debug.Log("hello world");
        }
    }
}

DeployAsteroid codes:

public class DeployAsteroids : MonoBehaviour
{
    public GameObject asteroidPrefab;
    public float respawnTime = 1.0f;
    private Vector2 screenBounds;

    // Start is called before the first frame update
    void Start()
    {
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
        StartCoroutine(asteroidWave());
    }

    private void spawnEnemy()
    {
        GameObject a = Instantiate(asteroidPrefab) as GameObject;
        a.transform.position = new Vector2(screenBounds.x * -2, Random.Range(-screenBounds.y, screenBounds.y));
    }

    IEnumerator asteroidWave()
    {
        while (true)
        {
            yield return new WaitForSeconds(respawnTime);
            spawnEnemy();
            //Debug.Log("Hello World");
        }
    }
}
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You even say it yourself

the Debug.Log appears in the console.

Well, you log in the moment you destroy your object => it is already gone.

Destroy(this.gameObject);
Debug.Log("hello world");

Unless you mean the out commented log after the spawn method. You still immediately destroy the object. I think you would spot it immediately if you would use useful logs and not twice the same one

Debug.Log("Spawned a new object");

and

Debug.Log("Destroyed an object");

So what exactly is happening then?

You immediately destroy the new spawned objects!

  1. you do

     screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
    

    which stores the position at the right border of the screen.

    Let's say e.g. somewhere at x = 2; (total random imaginary example number).

  2. Then right after spawning you set it to

     a.transform.position = new Vector2(screenBounds.x * -2, Random.Range(-screenBounds.y, screenBounds.y));
    

    So for the x you set it to (using our example value) x = -4;

    This is not even the left boarder of the screen but even beyond!

  3. Additionally you tell the asteroid to move

     rb.velocity = new Vector2(-speed, 0);
    

    so assuming the value speed is positive even more into negative x direction.

  4. And finally you do

     // Even without the Rigidbody this is already comparing
     // if(-2 * screenBounds.x < screenBounds.x)
     // Or with our example numbers
     // if(-4 < 2)
     if (transform.position.x < screenBounds.x)
     {
         Destroy(this.gameObject);
         Debug.Log("hello world");
     }
    

    => This condition will always be true and immediately destroys your objects in the next frame.


So what should I do instead?

I assume you are trying to spawn the asteroid at the right boarder.

And want to destroy it after it passed the left boarder. So it should probably be

private void spawnEnemy()
{
    GameObject a = Instantiate(asteroidPrefab);
    Vector3 rightEdgeWorldPoint = Camera.main.ScreenToWorldPoint( 
            new Vector3(Screen.width, Random.Range(0, Screen.height), 
            Camera.main.nearClipPlane);
    rightEdgeWorldPoint.z = 0f;
    a.transform.position = rightEdgeWorldPoint;
}

And in the asteroid

if (Camera.main.WorldToScreenPoint(transform.position).x < 0)
{
    Destroy(this.gameObject);
    Debug.Log("Left the screen -> destroyed");
}

Note: Typed on smartphone but I hope the idea gets clear

over 4 years ago · Santiago Trujillo Report

0

Go to the scene hierarchy and check if the asteroids can be seen there. May be you do not see them within the game or the scene camera, but if they are in the scene they are spawn somewhere. It would be interesting info to update in the question.

I did not dig into the code but if they are there, you need to check or set the position in which they are spawned respect to the camera, for the asterioids to be in the field of view.

Check the posistion given in this line: a.transform.position = new Vector2(screenBounds.x * -2, Random.Range(-screenBounds.y, screenBounds.y)); and if it fits in the camera field of view.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!