Hello I’m following an example to instantiate. The example is in JavaScript and I’m trying to do the same in C# (because I have to work in C#), but I get an error.
My code is the following:
public GameObject thePrefab;
void Start () {
GameObject instance = Instantiate(thePrefab, transform.position, transform.rotation);
}
Could anybody help me? Thank you
The problem is that Instantiate can clone any kind of Object that is derived from UnityEngine.Object. That’s why the return type of the function is UnityEngine.Object. However when you pass a GameObject as source, it will return a GameObject, but the reference you get back is of type UnityEngine.Object so it has to be casted into the right type:
GameObject instance = (GameObject)Instantiate(thePrefab, transform.position, transform.rotation);
Most examples in the scripting reference has examples in both (or all three) languages. You can switch the language with the little dropdown field at the top left side of code samples.
edit
The cast i’ve used above is the usual c-style cast. The advantage is when the given reference can’t be casted into the type it will throw an exception. This is actually a good thing to notice something is wrong.
There’s also the as-cast:
GameObject instance = Instantiate(thePrefab, transform.position, transform.rotation) as GameObject;
It works a bit different. It tries to cast the reference into the type but when it fails it returns null. In some situations this comes in quite handy, however it can lead to other errors like a null reference exception when you try to access the object. Even the object is there the reference is null because the cast failed. Such errors are quite hard to spot.
For example this will result in null:
public Rigidbody thePrefab;
GameObject instance = Instantiate(thePrefab, transform.position, transform.rotation) as GameObject;
The instantiate source is a Rigidbody component. Unity will clone the whole gameobject with all components but instantiate will return the reference to the rigidbody component of the cloned gameobject. That’s why a cast to GameObject would fail.
You could try out this tutorial it has all sorts of examples: Unity 2d instantiate objects