Instantiate and save it to a variable


I have a problem with instantiating my object as rigidbody into my clone variable :frowning:

I tried also … = (Rigidbody2D)Instantiate(…)

Nothing happens. Every time he is printing Null ( so the var is empty ).

using UnityEngine;
using System.Collections;

public class playerSpawn : MonoBehaviour 
    public FollowingCamera followingCamera;
    public GameObject playerPrefab;
    public Transform spawnPoint01;
    public Rigidbody2D clone;

	// Use this for initialization
	void Start () 
        clone = Instantiate(playerPrefab, spawnPoint01.position, spawnPoint01.rotation) as Rigidbody2D;

    void sendToCam(Transform playerName)
        followingCamera.player = playerName;



Hey there

First up, a lesson on casting as its very important. I see a lot of people using the ‘as’ keyword. As you probably know, objects in c# have a specific type and if a function such as ‘Instantiate’ returns a plain ‘Object’, you can cast it to the type you believe it to be. However there are 2 key forms cast:

  • the static cast: clone = (Rigidbody2D)Instantiate(bla) will throw an exception (i.e. report an error in the console) if Instantiate doesn’t return an object of type RigidBody2D. Use this when you know you are expecting a specific type, and it is an error if you don’t get one.
  • the dynamic cast: clone = Instantiate(bla) as Rigidbody2D will just silently return null if Instantiate doesn’t return an object of type RigidBody2D. It’s useful when you want to test what type of object is actually returned (see also the ‘is’ keyword) and take action based on the result.

Incidentally, the dynamic cast is also slower, so if you’re building for mobile its worth avoiding where possible.

In general though, if you are specifically expecting an object of a given type then the static cast is the one to use because it’ll actually report an error if something unexpected happens.

Now in your case the playerPrefab is a GameObject, so Instantiate is going to create and return a GameObject. You’ve done that right - this is how Instantiate should be used.

However, you are then using a dynamic cast to try and convert it to a Rigidbody2D. Because Rigidbody2D is not derived from GameObject, the dynamic cast fails and returns null. Had you used a static cast you would have got an exception instead.

I suspect that you want to make ‘clone’ a GameObject as well. You can still access its rigidbody2d component using the builtin rigidbody2d property. i.e.: clone.rigidbody2d

Hope that helps.