I’m getting an error with an scrpit. In the script I’ve got
public GameObject randomObject;
randomObject = Instantiate(randomModel, transform.position, transform.rotation);
So, Unity gives me the following error: Cannot implicitly convert type ‘UnityEngine.Object’ to UnityEngine.gameObject’. An explicit conversion exists (are you missing a cast?).
First of all, I didn’t even know that there was a difference between object and gameObject in Unity, I’d like to know the difference. Also, in order for my script to work, I need to know which type of variable does the Instantiate function return (I assume it’s an UnityEngine.Object variable), then, how can I access the transform for that variable (which is not a gameObject). I’ve found none of this in the documentation :S
Ok, as anybody posted an answer, but my question was completely answered at the comments, i’ll copy the answer that I was given and worked for me so I can mark this question as answered.
randomObject = Instantiate(randomModel,transform.position,transform.rotation) as GameObject;
You just have to cast the Object to be
a GameObject (the code doesn’t know
that Instantiate gives you a
GameObject unless you tell it).
Instantiate returns an Object because
it can be used to instantiate things
other than a GameObject. When you use
it for a GameObject though, you must
tell the compiler “The return value
from this function is a GameObject.”
Note that once you cast the return
Object from Instantiate, you will have
a GameObject and can access the
Transform component as usual.
randomObject.transform
PD: @Mizhuo, if you want to post your original answer as an answer so I can vote it I’ll delete this one, I don’t care about this karma system but as this is not my answer, I’m only posting it so other users can see this is actually answered.
This is not working .
public GameObject ball;
ball = (GameObject)Instantiate(cubeEffect, transform.position, transform.rotation);
Unity gives me the error “can’t convert from source type to destination type”. Plz help
You must feed the Instantiate method with a GameObject, if you want it to return a GameObject. The mistake many people make is to feed Instantiate with a Transform, and then expect Instantiate to return a GameObject. This is the wrong approach. For example @debthikana is feeding Instantiate a Transform called “cubeEffect”. Instead it should be a GameObject called “cubeEffect” that is fed into Instantiate. Then Instantiate will successfully return a GameObject back to you.