jai
jai

Reputation: 51

How to spawn objects in Unity?

I am trying to build a flappy bird like game and I am trying to spawn enemy birds and gold coins so I have written the C# code and the made the prefabs, but when I run the bird and the coins are not respawning.

This is the respawn code:

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

public class SpawnPlayer : MonoBehaviour
{
    public GameObject GameObjectToSpawn;
    private GameObject Clone;
    public float timeToSpawn = 4f;
    public float FirstSpawn = 10f;


    // Update is called once per frame
    void Update()
    {
        FirstSpawn -= Time.deltaTime;
        if (FirstSpawn <= 0f)
        {
            Clone = Instantiate(GameObjectToSpawn, gameObject.transform.localPosition, Quaternion.identity) as GameObject;
            FirstSpawn = timeToSpawn;

        }
    }
}

screenshot of unity: enter image description here

This where i am respawning the first enemy bird:

enter image description here

Upvotes: 2

Views: 6526

Answers (1)

derHugo
derHugo

Reputation: 90852

From your second screenshot it seems to be spawned but way off the screen! You can still see the tiny little island in the bottom left corner.

You thought seems to be that you have to spawn it in the Canvas pixel space using the spawn point's localPosition. But this is not the case since Instantiate places it into the scene root (without any parent) with absolute world-space position into the scene.

You should rather actually place the spawn point to the absolute world position where the spawn should happen and rather use

Clone = Instantiate(GameObjectToSpawn, transform.position, Quaternion.identity);

Btw no need for the as GameObject since Instantiate already returns the type of the given prefab.

Upvotes: 3

Related Questions