简体   繁体   English

如何在 Unity 中生成对象?

[英]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.我正在尝试构建一个像游戏一样飞扬的鸟,我正在尝试生成敌方鸟类和金币,所以我编写了 C# 代码并制作了预制件,但是当我运行鸟时,硬币没有重生。

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:统一截图: 在此处输入图像描述

This where i am respawning the first enemy bird:这是我重生第一只敌鸟的地方:

在此处输入图像描述

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 .您似乎认为您必须使用生成点的localPosition在 Canvas 像素空间中生成它。 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.但情况并非如此,因为Instantiate将其放置到场景根(没有任何父级)中,绝对世界空间 position 进入场景。

You should rather actually place the spawn point to the absolute world position where the spawn should happen and rather use您应该将生成点实际放置在应该发生生成的绝对世界 position 上,而不是使用

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

Btw no need for the as GameObject since Instantiate already returns the type of the given prefab.顺便说一句,因为Instantiate已经返回给定预制件的类型,所以不需要as GameObject

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM