Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

I Need Help C#

Discussion in 'Scripting' started by Elinoch, Mar 30, 2017.

  1. Elinoch

    Elinoch

    Joined:
    Mar 28, 2017
    Posts:
    9
    I'm Trying To Shoot My Projectile It Doesn't Come Back & Also Duplicates When I Click The Button!

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class LaserProjectile : MonoBehaviour {
    6.  
    7.     public LaserProjectile projectile;
    8.  
    9.     // Use this for initialization
    10.     void Start () {
    11.        
    12.     }
    13.    
    14.     // Update is called once per frame
    15.     void Update () {
    16.  
    17.         if (Input.GetMouseButtonDown(0)) {
    18.  
    19.             LaserProjectile bullet = Instantiate(projectile, transform.position, Quaternion.identity) as LaserProjectile;
    20.  
    21.             bullet.GetComponent<Rigidbody>().AddForce(transform.forward * 1000);
    22.  
    23.         }
    24.        
    25.     }
    26. }
    27.  
    Please Help!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    Assuming the object this script is located on is in Quaternion.identity world rotation, then AddForce(transform.forward * 1000); will apply the force to your new projectile directly into the screen (away from you).

    If you have gravity, it would then begin to accelerate in the direction of the Physics.gravity vector, probably downwards.

    This all assumes your camera is facing along the +Z vector (default Unity camera direction).

    If you want to understand more, put this statement on around line 22:

    Debug.Break();

    This will kick the editor into pause mode when you fire the bullet, and then you can single-step the editor (far right button at center top) and look in the scene view to see what your projectile is doing. You can search for the projectile in the hierarchy, select it, then press F to focus on it in the scene view, then step along to see it move.
     
  3. Elinoch

    Elinoch

    Joined:
    Mar 28, 2017
    Posts:
    9

    Helped Me Know What Was Happening But Now I Need A Script To Stop the dupilicating!
     
  4. Elinoch

    Elinoch

    Joined:
    Mar 28, 2017
    Posts:
    9

    Nevermind But Thank You :)