How do i take a grab of clone from prefab and change his velocity
im creating2d ufo game and im trying to make the spaceship fire i created a prefab of bullet and add a rigidbody component. created an empty object in the hierarchy and attached the script to it. the creation of bullets from the prefab succeded but i cant write the right code in order to manipulet each cloneBullet velocity. they stay static on the screen i tried in my code to make each bullet move the same direction just for testing it. it doesnt work. and can u give some direction how to manipulet all bullets in each frame
this is my code: using UnityEngine; using System.Collections;
public class FireController : MonoBehaviour { public Transform Bullet; public GameObject player; private GameObject Bulletclone; string direction; // Use this for initialization void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.F))
{
Bulletclone = Instantiate(Bullet, player.transform.position, Bullet.rotation) as GameObject;
Bulletclone.GetComponent<Rigidbody2D>().velocity = new Vector2(0, 20);
}
Answer by FortisVenaliter · Jan 27, 2016 at 06:16 PM
You should use RigidBody's AddForce() function rather than setting the velocity directly. Also, make sure there aren't other colliders where it spawns that will block it from moving.
tried it. and he still saynig the error: "object reference not set to an instance of an object" on the line im getting the rigidbody2d component of the clone
Oh, well a Null Reference Exception is a whole different thing. That means that you don't have a Rigidbody2D attached to the bullet. Do you have one on the prefab?
yea i did. you can see it in the image. i dont have a clue why it saying that
tried it. and he still saynig the error: "object reference not set to an instance of an object" on the line im getting the rigidbody2d component of the clone
Just out of curiosity... Could you try instantiating Bullet.gameObject ins$$anonymous$$d of Bullet and see if that makes a difference?
Answer by henbarlevi · Jan 29, 2016 at 03:10 PM
the problem was that i decleared Bullet as Transform instead of a gameobject. Fixed it!. thx for the help!