Search Unity

Instantiated objects are not moving when they are supposed to?

Discussion in 'Scripting' started by GamesOnAcid, Sep 28, 2016.

  1. GamesOnAcid

    GamesOnAcid

    Joined:
    Jan 11, 2016
    Posts:
    283
    I am trying to create a shooting feature, where you have a pistol that shoots. Simple. My problem is, whenever a new bullet is created, it doesn't move.
    Here are the scripts that control the bullet:
    Bullets.cs
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Bullets : MonoBehaviour {
    5.  
    6.     public PlayerController player;
    7.     public float speed;
    8.  
    9.     void Start() {
    10.         player = GameObject.Find ("player").GetComponent<PlayerController> ();
    11.     }
    12.  
    13.     void Update() {
    14.         player.bullet.GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D>().velocity.y);
    15.     }
    16.  
    17.     void OnTriggerEnter2D(Collider2D col) {
    18.         Destroy (gameObject);
    19.     }
    20. }
    21.  
    This sets all the attributes of the pistol, which are all declared in the PlayerController script:
    Code (CSharp):
    1. public void Pistol() {
    2.         bulletSprite.sprite = pistolBullet;
    3.         gunSprite.sprite = pistol;
    4.         player.firerate = 2;
    5.         player.bulletSpeed = 100;
    6.         player.totalAmmo = 30;
    7.         player.damage = 10;
    8.     }
    This is in the PlayerController script in the Update method:
    Code (CSharp):
    1. if (Input.GetKeyDown (KeyCode.Space) && firerate != 0) {
    2.             Instantiate (bullet, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
    3.         }
    I cannot see the issue. I have a bullet preplaced in the scene so that I can spawn other bullets based off of it, but the new ones don't move at all even if their speed is over 0. Can anyone tell me why?
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,438
    Looks like you are referencing the original bullet prefab (in project folder),
    instead of taking reference to the instantiated bullet..

    so when you shoot, take reference to that gameobject, so that you can move it
    Code (CSharp):
    1.          
    2. createdBullet = Instantiate (bullet, bulletSpawnPoint.position, bulletSpawnPoint.rotation);
    Or just change the bullet script so that it keeps moving itself, without needing to reference player
    Code (CSharp):
    1.     void Update() {
    2.      
    3. //player.bullet.GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D>().velocity.y);
    4. GetComponent<Rigidbody2D> ().velocity = new Vector2 (speed, GetComponent<Rigidbody2D>().velocity.y);
    5.     }
    6.  
     
  3. GamesOnAcid

    GamesOnAcid

    Joined:
    Jan 11, 2016
    Posts:
    283
    That appears to function correctly! Thanks!