0

My idea is a 2D game where the player has a base in the center and enemies spawn in one of 10 spawn points and then move towards the middle. I wrote this code but there is an error. Can someone help??

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);
    }
}

The error it gives me is:vector 3does not contain a constructor that takes in 1 arguments

Jan
  • 9

1 Answers1

1

The error is telling you that you can't do new Vector3(spawner[spawnerNumber].transform.position).

new Vector3() is a constructor. It can be empty and default to [0, 0, 0] or it can take 3 arguments representing the x, y and z components, e.g. new Vector3(1, 5, 3).

There is no version of the constructor which takes only one argument. You are trying to pass a Vector3 into it as a single object which is not allowed. spawner[spawnerNumber].transform.position is a Vector3.

The solution: Well, strictly speaking, you should not be creating a new Vector3 here at all. Your line should read:

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

transform.position on Monobehaviour objects is always a Vector3 anyway.

If you absolutely needed to create a new vector with different component parts for x, y, and z you would need to dto do something more like:

// 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);

But DO NOT DO THAT in your case.

Rocketman Dan
  • 300
  • 2
  • 8