统一编译此脚本以在十个生成器之一中随机生成敌人时,它给了我一条错误消息

问题描述 投票:0回答:1

我的想法是一个 2D 游戏,其中玩家在中心有一个基地,敌人在 10 个生成点之一生成,然后向中间移动。我写了这段代码,但有一个错误。有人可以帮忙吗??

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

public class EnemySpawn : MonoBehaviour
{
    private float spawnRate = 2f;
    private float timer = 0f;

    public GameObject enemy;
    public int spawnerNumber;
    public GameObject[] spawner;

    void Update()
    {
        timer += Time.deltaTime;

        if(timer > spawnRate)
        {
            timer = 0f;
            Spawn();
            if(spawnRate > 0.1f)
            {
                spawnRate -= 0.01f;
            }

        }
    }

    void Spawn()
    {
        spawnerNumber = Random.Range(0, 10);
        Instantiate(enemy, new Vector3(spawner[spawnerNumber].transform.position), Quaternion.identity);
    }
}

它给我的错误是:

vector 3
does not contain a constructor that takes in 1 arguments

c# unity3d game-engine game-development
1个回答
0
投票

错误是告诉你做不到

new Vector3(spawner[spawnerNumber].transform.position)
.

new Vector3()
是构造函数。它可以为空并默认为 [0, 0, 0] 或者它可以采用 3 个参数来表示 x、y 和 z 分量,例如
new Vector3(1, 5, 3)
.

没有只接受一个参数的构造函数版本。您正试图将 Vector3 作为单个对象传递给它,这是不允许的。 spawner[spawnerNumber].transform.position 是一个 Vector3.

解决方案:嗯,严格来说,你根本不应该在这里创建一个新的 Vector3。你的台词应该是:

// Best way to solve your problem
Instantiate(enemy, spawner[spawnerNumber].transform.position, Quaternion.identity);

Monobehaviour 对象上的 transform.position 始终是 Vector3。

如果您确实需要为 x、y 和 z 创建一个具有不同组成部分的新向量,您需要做更多类似的事情:

// Example of how to use a constructor, do not do this in your case
Instantiate(enemy, new Vector3(spawner[spawnerNumber].transform.position.x, spawner[spawnerNumber].transform.position.y, spawner[spawnerNumber].transform.position.z), Quaternion.identity);

但是在你的情况下不要那样做。

© www.soinside.com 2019 - 2024. All rights reserved.