- Home /
Need Help with Shooting Script c#
I am a beginner so please explain thoroughly on what i am doing wrong <3
I am making a Little simple platformer. I have a plain square that can move left, right, and can jump and shoots only to the right
(Once this problem is out of the way i will make it shoot left too).
I found a tut on youtube on how to make a Space invaders type game. I flipped the Code around for the shooting part so it would shoot horizontally.
As soon as the prefab bullet reaches 8 on the 'x' axis it is destroyed. But as soon as my character is past 8 on the 'x' axis he is not able to shoot anymore because the character is past 8 on the 'x' axis not allowing it to shoot.
Is there a way where the bullet will be destroyed 8 units in front of the player? instead of on the main 'x' axis? Also the player is able to run past the bullets.
how can i make it just like a gun??
Here is My Code that destroys the Bullet once it hits 8 on the x axis
using UnityEngine;
using System.Collections;
public class Shooting : MonoBehaviour {
public int BulletSpeed = 5;
public GameObject Bullet;
private Transform myTransform;
void Start () {
myTransform = transform;
}
void Update () {
myTransform.Translate(Vector3.right * BulletSpeed * Time.deltaTime);
if (myTransform.position.x >8) {
DestroyObject(this.gameObject);
}
}
}
I hope you understand!!
Thank you<3
just store the x value you start on and destroy when it's past the stored value + 8
Answer by DiligentGear · Dec 28, 2013 at 08:15 AM
First of all, you need to prepare the following things:
1) A bullet prefab. you can create a prefab by dragging an object in the scene to your project panel.
You can try to create a cube by clicking Create button on the top of your hierarchy. Then you can rename the cube and drag it into your project panel. You can see your cube's name become blue. That means this object has became a prefab.
2) A script attached to the bullet prefab. This script will be in charge of moving your bullet, and detect collision. I didn't write collision code here because you haven't got any enemy yet. The bullet will "destroy"(deactivate) itself when it goes out of the camera.
// BulletScript.cs
using UnityEngine;
using System.Collections;
public class BulletScript : MonoBehaviour {
public float bulletSpeed = 5f;
void Update () {
transform.Translate(Vector3.right * bulletSpeed * Time.deltaTime);
}
void OnBecameInvisible () {
this.gameObject.SetActive(false);
}
}
3) A script attached to your character/space ship.
using UnityEngine;
using System.Collections;
using System.Collections.Generic; // Remember to add this line, otherwise the List won't work
public class Shooting : MonoBehaviour {
public float bulletSpeed = 5f;
public GameObject bullet; // Drag and drop your x axis bullet here
List<GameObject> bulletList; // This is a List of bullets, you can just think it as an array at this point
// For more information of List, check the tut here:
// http://unity3d.com/learn/tutorials/modules/intermediate/scripting/lists-and-dictionaries
// It's short (5 mins) and informative
public int maxBulletOnX = 8; // The limit of bullet on x axis
// You can always adjust the limit in inspector without going into the code
void Start () {
bulletList = new List<GameObject>();
for (int i = 0; i < maxBulletOnX; i++)
{
bulletList.Add(Instantiate(bullet,Vector3.zero,Quaternion.identity));
// What this line does is to "instantiate" the prefab (aka. your bullet you want to shoot)
// Instantiate is good for cloning duplicated object like bullet
// For more information of Instantiate, check here:
// http://docs.unity3d.com/Documentation/Manual/InstantiatingPrefabs.html
// It's usually bad to instantiate/destroy at runtime, but you don't have to worry about it at this point
bulletList[i].GetComponent<BulletScript>().bulletSpeed = bulletSpeed;
// This line will access your bullet's script and set the speed for it.
// For more information of accessing another script, check here:
// http://unitygems.com/script-interaction1/
bulletList[i].SetActive(false);
// This will de-activate your bullet when started up
}
}
void Shoot () {
GameObject temp = bulletList.Find(go => go.activeInHierarchy == false});
// This is called lambda expression. You don't have to know what this is now.
// What it does is to find bullet that is waiting to be used.
if (temp != null)
{
temp.transform.position = transform.position + offset;
// You might want modify the position value by yourself
// What this does is to set the bullet at right place, aka where you shoot
// Now it shoots from the center of your character
temp.SetActive(true);
}
}
void Update () {
if (Input.GetMouseButtonDown(0)) // 0 means left click
{
Shoot();
}
}
}
It might be too complex for a beginner, but I think you can google a huge amount of beginner tutorial for a shooting game.
It didn't work i'm getting an error saying "The variable player of Shooting has not been assigned."
Hi there, very cool script DiligentGear, how would you go about reusing the activation of the deactivated prefab, i tried and failed to do so. Would weneed to code a proper pool with queue or dequeue or is there another way to manage it ? THX
Answer by OrbitSoft · Dec 28, 2013 at 08:06 AM
You need to replace the destroy part with this:
if (myTransform.position.x > Player.transform.position.x+8 || myTransform.position.x < (Player.transform.position.x+8)*-1)
{
DestroyObject(this.gameObject);
}
Which basically gets the player position x and adds 8 to it and it checks both left and right side, of course you need to add
public Transform Player;
To make it shoot both sides you need to use a bool and control it with Input.GetKey to know if the player is going left or right.
bool facingRight;
void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
facingRight = false;
} else if (Input.GetKeyDown(KeyCode.RightArrow))
{
facingRight = true;
}
}
I hope you know what this code does, next thing is to finally move the bullet the right direction.
void Update()
{
if (facingRight)
{
myTransform.Translate(BulletSpeed*Time.deltaTime,0,0);
} else myTransform.Translate(BulletSpeed*Time.deltaTime*-1,0,0);
}
The final result looks like this:
using UnityEngine;
using System.Collections;
public class Shooting : MonoBehaviour {
public int BulletSpeed = 5;
public GameObject Bullet;
public Transform Player;
private Transform myTransform;
// variables are private by default in C# so you don't need it
bool facingRight;
void Start ()
{
myTransform = transform;
}
void Update ()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
facingRight = false;
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{
facingRight = true;
}
if (facingRight)
{
myTransform.Translate(BulletSpeed*Time.deltaTime,0,0);
} else myTransform.Translate(BulletSpeed*Time.deltaTime*-1,0,0);
if (myTransform.position.x > Player.transform.position.x+8 || myTransform.position.x < (Player.transform.position.x+8)*-1)
{
DestroyObject(this.gameObject);
}
}
}
I'm sorry the code formatting messed up at the end..
I get and error
"The variable Player of 'Shooting' has not been assigned"
But in the inspector i assigned it the player.
Answer by mnmwert · Apr 21, 2016 at 11:04 PM
The problem inlies where you have
if (myTransform.Position.x >8)
{ destroyObject (this.gameobject) }
Form what you are trying to accomplish I do not think you need that piece of code. What it is actually saying is if the object is beyond 8 on the x axis the object will be destroyed. when your player goes past 8 and you try to fire the object is destroyed instantly.
If you are trying to destroy the object when it hits a player i am lost as i myself am a beginner at C# (i'm tying to figure out how to do that very thing!) but i do hope this helps some
Answer by Spartan_Boy · May 12, 2017 at 09:54 AM
Hi there, very cool script @DiligentGear, how would you go about reusing the activation of the deactivated prefab, i tried and failed to do so. Would weneed to code a proper pool with queue or dequeue or is there another way to manage it ? THX
Answer by surajvimap · May 14, 2017 at 04:41 PM
void Fire() //for Guns.... {
GameObject goli = Instantiate(Bullet, new Vector3(bulletpos.transform.position.x, bulletpos.transform.position.y, bulletpos.transform.position.z), BulletRotation.rotation) as GameObject;
goli.GetComponent<Rigidbody>().velocity = goli.transform.forward * speed;
// Destroy the bullet after 5 seconds
Destroy(goli, 5.0f);
}
just call this function and give the position to generate bullet.......... hope it's help you..