- Home /
error CS0266: Cannot implicitly convert type `UnityEngine.Object' to `UnityEngine.Transform'. An explicit conversion exists (are you missing a cast?)
Hi, I have this code here (please consider I'm new to C#)
using UnityEngine;
using System.Collections;
public class cloneAndDestroy : MonoBehaviour {
private UdpReceive udpRec;
//Object to be instantiated
Transform prefabToSpawn;
//One can only create 3 waypoints at a time
int maxAmt = 3;
// circular list: private
Transform[] maxAmtList;
private int curPos = 0;
void Start (){
Application.runInBackground = true;
//using find //
udpRec = GameObject.Find("OSC receiver").GetComponent(typeof(UdpReceive)) as UdpReceive;
maxAmtList = new Transform[maxAmt];
}
void Update (){
if (udpRec.maxValues.Length <= 0) {
return;
}
float cloneYes = udpRec.MaxValue(3);
if (cloneYes == 1){
if (maxAmtList[curPos]){
// if some object already in curPos...
Destroy(maxAmtList[curPos].gameObject); // delete it
}
//create a new waypoint and store it in curPos:
maxAmtList[curPos] = Instantiate(prefabToSpawn, transform.position, Quaternion.identity);
//increment curPos in a circular fashion:
curPos = (curPos + 1) % maxAmt; }
}
}
I get this error: error CS0266: Cannot implicitly convert type UnityEngine.Object' to
UnityEngine.Transform'. An explicit conversion exists (are you missing a cast?)
the line where the error seems to occur is: maxAmtList[curPos] = Instantiate(prefabToSpawn, transform.position, Quaternion.identity);
any idea why/ what should i do for solve this? thanks!!!
Answer by tanoshimi · Nov 26, 2015 at 07:49 PM
Instantiate() returns an object. but maxAmtList[] is an array of Transforms. The error is telling you that you cannot implicitly convert type Object (returned by Instantiate) to Transform (expected by maxAmtList). But, good news, an explicit conversion exists, and it helpfully suggests that you might be missing a cast, which indeed you are:
maxAmtList[curPos] = (Transform)Instantiate(prefabToSpawn, transform.position, Quaternion.identity);
O$$anonymous$$G! thank you so much! just a little question more: when i put your line, then the cloners are not taking the rotation of the empty object my script is in.. is there a way to make it different?
Well, you pass as rotation to Instantiate "Quaternion.identity" which means the object is aligned with the world axis. Just pass transform.rotation ins$$anonymous$$d. Alternatively you can change the position / rotation after you have instantiated the object
So either:
maxAmtList[curPos] = (Transform)Instantiate(prefabToSpawn, transform.position, transform.rotation);
or
maxAmtList[curPos] = (Transform)Instantiate(prefabToSpawn);
maxAmtList[curPos].position = transform.position;
maxAmtList[curPos].rotation = transform.rotation;