So I'm trying to clone gameobjects however I keep getting the following error:
BoxDuplication.cs(18,60): error CS1503: Argument 2: cannot convert from 'UnityEngine.Vector2' to 'UnityEngine.Transform'
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxDuplication : MonoBehaviour
{
public GameObject boxOriginal;
void Start()
{
CreateBox(3);
}
void CreateBox(int boxNum)
{
for (int i = 0; i < boxNum; i )
{
GameObject boxClone = Instantiate(boxOriginal, new Vector2(boxOriginal.transform.position.x, i));
}
}
}
I've tried putting instantiate standalone with set co-ordinates:
GameObject boxClone = Instantiate(boxOriginal, new Vector2(1, 1));
but this doesn't work either so there's something wrong with my method
I've tried to figure out what I'm doing wrong by looking through videos and other stack-overflow posts but due to not really knowing much c# I'm at a loss. There are a few similar posts like this but I don't think they answer my problem. If they do, then I guess I don't understand the concept.
Thanks, Any help is much appreciated!
CodePudding user response:
From the Unity Docs, the Instantiate Decelerations are:
public static Object Instantiate(Object original);
public static Object Instantiate(Object original, Transform parent);
public static Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
So in your case, the Instantiate method expects a parent Transform
. You will have to include the rotation and parent as well.
So your line becomes:
GameObject boxClone = Instantiate(boxOriginal, new Vector2(1, 1), Quaternion.identity, transform);
EDIT:
The transform
is used as a parent. It can be omitted as needed. It is always a good idea to spawn objects as a child. To make a hierarchy clean.
CodePudding user response:
Your issue is that you are not setting the rotation of the new GameObject.
If you want to use Instantiate(boxOriginal, transform)
that would set it as a child of the object that your script is attached to. That would work, you would just need to add boxClone.transform.position = Vector3(1,1);
to move it to the desired position. Note boxClone.transform.localPosition
may be what you want instead.
If you use GameObject boxClone = Instantiate(boxOriginal, new Vector2(1, 1), Quaternion.identity);
then you should have no issues.