InvalidCastException: Cannot convert from source type to destination type using a Rigidbody2D

I’m trying to move the clones but for some reason I’m getting this error when I’m trying to convert the instantiated bullet clone into a Rigidbody2D. How should I go about fixing this?

using UnityEngine;
using System.Collections;

public class Shooting : MonoBehaviour {
	public Rigidbody2D bullets;
	public int speed;
	Rigidbody2D bulletClone;
	Vector2 playerPos;
	// Use this for initialization
	void Start () {
		speed = 10;
	}
	
	// Update is called once per frame
	void Update () {
		playerPos = GameObject.Find ("Player").transform.position;
		if(Input.GetButtonDown("Fire1")){
			bulletClone = (Rigidbody2D)Instantiate (bullets, transform.position, Quaternion.identity);


		}
	}
}

Cast to GameObject, then get the rigidbody2D member:

bulletClone = ((GameObject)Instantiate(bullets,transform.position,Quaternion.identity)).rigidbody2D;

Hi

I don’t think you can just instantiate a ‘rigidbody2d’, as the rigidbody2d is a component that is part of a game object. You need to create a prefab for your bullet, then instantiate that. So the a basic way of doing it might be:

  1. In the editor, create a bullet how you want it - a game object with its mesh, a rigid body 2d and whatever other parts you need
  2. Create a new prefab
  3. Drag the bullet onto the prefab (to turn the blank prefab into one that represents your bullet type). You can now delete the bullet itself if you don’t want it in the world any more.
  4. Add a member to your script which is public with the code ‘public GameObject bullet_prefab’
  5. Now in the editor when you select the shooting object you will see a property called ‘bullet prefab’. Drag your bullet prefab into that property
  6. In your code you can now do ‘GameObject newbullet = (GameObject)Instantiate(bullet_prefab)’

The new bullet object will be a full game object that now exists in the world that has a rigid body which you can access via its rigidbody2D property if you need to.

(correction) According to the docs it looks like you should be able to just instantiate the rigid body by itself. However instantiate would still return a GameObject with a rigid body attached so you’d still need to get the game object and then access its rigidbody2D member.

-Chris