Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

cant get this shooting code to work

Discussion in 'Scripting' started by Marco___, Jun 24, 2016.

  1. Marco___

    Marco___

    Joined:
    Jun 24, 2016
    Posts:
    1
    i started making a fps and i made the script for the projectile to shoot, but its not working, any suggestion (im using c# btw)

    using UnityEngine;
    using System.Collections;

    public class ProjectileShooter : MonoBehaviour {


    GameObject prefab;
    void Start () {
    prefab = Resources.Load("projectile") as GameObject;
    }

    // Update is called once per frame
    void Update () {
    if (Input.GetMouseButtonDown(0))
    {
    GameObject projectile = Instantiate(prefab) as GameObject;
    projectile.transform.position=transform.position+Camera.main.transform.forward * 2;
    Rigidbody rb=projectile.GetComponent<Rigidbody>();
    rb.velocity=Camera.main.transform.forward * 40;
    }
    }
    }
     
  2. Simplified

    Simplified

    Joined:
    May 28, 2016
    Posts:
    19
    I would make the GameObject public and drag the prefab onto the script in the inspector. Then I would do something like:

    Code (CSharp):
    1. Instantiate(prefab, thePositionYouSet.transform.position, Quaternion.identity);
    Also, get the rigidbody in the start function of the script, don't do it in the Upadte function.

    Code (CSharp):
    1. rb = prefab.GetComponent<Rigidbody>();
    As a note, try to organize your code so you don't get lost in it ;).
     
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    getting it from a resources load is perfectly reasonable; having it set in the inspector prevents changes to the assets after the game is released (i.e. asset bundles).

    no. That would give the rigidbody on the prefab, which is useless in the context. He is quite rightly getting the rigidbody on the newly created instance of the projectile in the scene.
     
  4. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    any errors? what is it actually doing?

    first hiccup point would be the resources load not working (the prefab should be in a folder in the project called "Resources"?)

    have you try adding in some debug.log lines to see whats going on?


    also: http://forum.unity3d.com/threads/using-code-tags-properly.143875/