Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by rondonron · Dec 28, 2013 at 06:52 AM · prefabbeginnerbulletgun script

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

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Benproductions1 · Dec 28, 2013 at 08:00 AM 0
Share

just store the x value you start on and destroy when it's past the stored value + 8

5 Replies

· Add your reply
  • Sort: 
avatar image
0

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.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image hallsb · Apr 27, 2017 at 02:55 PM 0
Share

It didn't work i'm getting an error saying "The variable player of Shooting has not been assigned."

avatar image Spartan_Boy · May 11, 2017 at 09:01 PM 0
Share

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

avatar image
0

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..

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image rondonron · Dec 28, 2013 at 05:38 PM 0
Share

I get and error

"The variable Player of 'Shooting' has not been assigned"

But in the inspector i assigned it the player.

avatar image
0

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

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

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..

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

25 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

my prefab images dont appear in my scene view but are in my camera view 2 Answers

Beginner needs help with Pathfinding 2 Answers

How can I make an in-game search engine similar to Scribblenauts 1 Answer

Im still confuse. any help or guide? 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges