Don Subert
Don Subert

Reputation: 2676

Unity C# Instantiating from prefab and casting to GameObject

In Unity with C#, I am trying to Instantiate from a prefab and assign a script to the new object. To do this, I believe that I need to have the new object cast as a GameObject. However, the return type of Instantiate is UnityEngine.Object

From the Unity manual:

public GameObject wreck;
...
void KillSelf () (
...
GameObject wreckClone = (GameObject) Instantiate(wreck, transform.position, transform.rotation);

This, however, results in an InvalidCastException. I have seen it mentioned on this forum to try this instead:

UnityEngine.Object uo = Instantiate(...
GameObject go = (GameObject)go;

This, however, results in the same exception.

I have seen some posts suggesting trying to cast with:

...Instantiate(...) as GameObject;

This syntax does not, however, appear to be supported by the compiler.

This is pretty confusing. I'm copying small bits of code out of (presumably correct) manuals and stack overflow answers, and they just don't seem to function.

I'm not sure what information would be necessary to help solve this puzzle, so just ask me for what you need.

So far i have tried logging the object instantiated before trying to cast it. It shows up as ThrownFood(clone)(UnityEngine.transform). I don't know why it would say transform though. I don't have anything telling it to be cast as a transform.

Upvotes: 1

Views: 11975

Answers (1)

marsh
marsh

Reputation: 2740

What version of Unity are you using? These two examples both compile for me:

    public GameObject wreck;

    GameObject testObj = new GameObject();
    GameObject go = Instantiate(testObj, transform.position, transform.rotation) as GameObject;
    GameObject go2 = (GameObject)Instantiate(testObj, transform.position, transform.rotation);

Instantiate returns what you throw in.

If you throw a transform handle in, it will return a transform handle. if you throw a game object in, it will return a game object. You do seem to be passing it a game object though. You could try casting it to a gameobject in your first parameter like so:

GameObject wreckClone = (GameObject) Instantiate((GameObject)wreck, transform.position, transform.rotation);

The simplest answer to your problem would be getting the GameObject from your transform with the transform.gameObject command like so:

GameObject go = wreckClone.gameObject;

If the above code does still error you may want to restart or reinstall Unity as it is working code.

Upvotes: 2

Related Questions