Search Unity

I NEED HELP

Discussion in 'Scripting' started by The_Devils_Games, Aug 15, 2019.

  1. The_Devils_Games

    The_Devils_Games

    Joined:
    Aug 15, 2019
    Posts:
    2
    so im making a game and I've tried scripting the guns (im a new dev) and the script aint working because it won't move forward can anyone help

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Shooting : MonoBehaviour {

    public GameObject bullet;
    public float speed = 100f;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
    if(Input.GetKeyDown(KeyCode.Space)){
    GameObject instBullet = Instantiate(bullet, transform.position, Quaternion.identity) as GameObject;
    Rigidbody instBulletRigidbody = instBullet.GetComponent<Rigidbody>();
    instBulletRigidbody.AddForce(Vector3.forward * speed);

    }

    }
    }
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    Forum etiquette: 1) Use a better post title so that people with relevant knowledge will know to click your post (literally everyone posting here "needs help". 2) Use [code ]code tags[/code] when posting code.

    When you say "it won't move forward", you mean the bullet, I assume. Is it possible the bullet is colliding with something as soon as it's shot (such as the player's rigidbody)?

    This probably isn't your main issue, but rigidbody.AddForce should not be used during Update(). It adds force across the length of the frame, and since frames may be different lengths of time, it will shoot bullets at unpredictable speeds. You can either a) set rigidbody.velocity directly, or b) separate the input and the shooting parts of your code (move the AddForce call into FixedUpdate, but you shouldn't do input checks in FixedUpdate, so that should stay in Update). In this situation A is far easier and more sensible.
     
  3. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Disable all bullet colliders to see if collisions at the point of instantiation are the problem. Otherwise everything @StarManta said. Also, try adjusting speed to higher values to see if that changes anything.