I am trying to make a space shooter game and I have gotten to the point where I am trying to get the player to be able to push the spacebar and a lazer fires from the ship. As soon as I push play it automatically fires a bunch of the lazer(clones) without me even pushing spacebar and it doesn’t destroy them after they pass the point I have indicated. Here is the script.`using UnityEngine;
using System.Collections;
public class LazerFab : MonoBehaviour {
private Transform myTransform;
public int projectileSpeed = 7;
void Start (){
myTransform = transform;
}
// Update is called once per frame
void Update () {
myTransform.Translate (Vector3.up * projectileSpeed * Time.deltaTime);
//Destroy lazer when it reaches the top of the screen
if (myTransform.position.y >= 7)
{
DestroyObject (this.gameObject); //destroys lazer
}
}
}`
is the lazer sript and the player script is this
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
private Transform myTransform;
public int playerSpeed = 5;
public GameObject LazerFab;
// Use this for initialization
void Start () {
myTransform = transform;
//start point x y z
//position at -3 -3 -1
myTransform.position = new Vector3 (-3, -3, -1);
}
// Update is called once per frame
void Update () {
//move player left and right along x axis
myTransform.Translate (Vector3.right * playerSpeed * Input.GetAxis("Horizontal") * Time.deltaTime);
//if the player is at -11 on the right of the screen then the player should appear at 11 and vice versa
if (myTransform.position.x >= 10) {
myTransform.position = new Vector3 (-10, myTransform.position.y, myTransform.position.z);
}
else if (myTransform.position.x <= -10)
{
myTransform.position = new Vector3 (10, myTransform.position.y, myTransform.position.z);
}
//press spacebar to fire weapons
//if the player presses the spacebar a projectile will fire from certain points
if (Input.GetKeyDown ("space"))
Debug.Log ("spacebar was pressed");
//fire weapons
{
Instantiate(LazerFab);
}
}
}