Network.Instantiate returning a transform?

Hey, I’m playing around with the iphone multiplayer tutorials. Now I’m trying to keep track of objects I instantiate on the network in order to be able to destroy them using Network.Destroy()
Anyway, here is what i do in C#:

Object o=Network.Instantiate(obj, pos, rot, 0);
Debug.Log("instantiated object is "+o.ToString());
GameObject go=(GameObject)o;

This compiles all right, and when I run the game, my prefab is instantiated on the network properly.
Using the debug log, I can see that ‘o’ is of the expected type UnityEngine.Transform.

I’m getting a runtime error on the cast:
Cannot cast from source type to destination type

What am I doing wrong here? Can I not get a Transform of the instantiated object this way?

What is that supposed to do ? (I am still not familiar with C# syntax)

Try o.gameObject instead.

Well if o’s a Transform it’s not a GameObject so you can’t cast it to a GameObject.

So cast o to a Transfrom and get the GameObject reference from the Transform.

Transform tform = (Transform)o;
GameObject go = tform.gameObject;

instantiate returns what you throw in.

if you throw a transform handle in, it will return a transform handle. if you throw a gameobject in, it will return a game object

in both cases you need to cast it to the corresponding class

Hey thanks Dreamora,

I’m new to unity so I guess I must have overlooked checking the class hierarchy in the documentation precisely :slight_smile:

Anyway, so far so good, this product really rocks!!

Also, you are going to run into problems using Network.Instantiate (or Object.Instantiate) on mobile because it dynamically allocates memory. Unless its just for the player, you should probably create a pool. I say to you 3 years later.

Tip: you also need to have 3 types Instantiating

  • one for yourself (the player) to enter the scene,
  • one for the NPCs you might have on the scene and
  • for other players.
  1. Yourself - has camera + controller
  2. NPCs - no camera + collider + network controller.
  3. Other player - no camera + collider + network controller linked to other player.