Diggs Diggs - 15 days ago 5
C# Question

convert vector3 to transform

i'm working on a spawner script but have a problem that I can't find a solution to...

I get an error that says


"Cannot implicitly convert type 'UnityEngine.Vector3' to 'UnityEngine.Transform'"


I can remove the error by adding .position to
spawningpos
but that won't work because it not an object's transform just a transform variable in a script

public GameObject[] spawningObj;
public GameObject[] insects;
public GameObject[] invierment;
public GameObject[] inviermentSingel;
public Transform player;
public int maxNPCsPerChunk;
public int maxInectsPerChunk;
public int maxInviermentalsPerChunk;
public int spawningAria;

private Transform spawningpos;

// Use this for initialization
void Start()
{
if (player == null)
player = GameObject.FindWithTag("Player").transform;

int max = Random.Range(0, maxInectsPerChunk);
for (int i = 0; i < max; i++)
{
spawningpos = new Vector3(Random.Range(-spawningAria, spawningAria) + transform.position.x, 2f, Random.Range(-spawningAria, spawningAria) + transform.position.z);
//Error on above line

Instantiate(insects[Random.Range(0, insects.Length)], spawningpos);
}

Answer

Your issue is explained very well by the error you're receiving, lets have a look

"Cannot implicitly convert type 'UnityEngine.Vector3' to 'UnityEngine.Transform'"

So where are you trying to set a Transform's value to a Vector3?

private Transform spawningpos;

spawningpos is a Transform

spawningpos = new Vector3(Random.Range(-spawningAria, spawningAria) + transform.position.x, 2f, Random.Range(-spawningAria, spawningAria) + transform.position.z);

But here you are clearly setting its value to a Vector3

Instantiate(insects[Random.Range(0, insects.Length)], spawningpos); 

On this line you then instantiate the object - using the Transform as input. As you will find here, the overload you are using for the method is actually asking for the parent's Transform, try this instead

private Vector3 spawningpos;

Followed by, as before

spawningpos = new Vector3(Random.Range(-spawningAria, spawningAria) + transform.position.x, 2f, Random.Range(-spawningAria, spawningAria) + transform.position.z);

And finally

Instantiate(insects[Random.Range(0, insects.Length)], spawningpos, Quaternion.Identity);

This code will call the correct overload of the Instantiate method, setting the object's rotation is mandatory when passing a Vector3