Search Unity

  1. We've closed the job boards. If you're looking for work, or looking to hire check out Unity Connect. You can see more information here.
    Dismiss Notice
  2. Unity 2017.2 is now released.
    Dismiss Notice
  3. The Unity Gear Store is here to help you look great at your next meetup, user group or conference. With all new Unity apparel, stickers and more!
    Dismiss Notice
  4. If you're a macOS 10.13 High Sierra user take be sure to read this before updating Unity.
    Dismiss Notice
  5. Introducing the Unity Essentials Packs! Find out more.
    Dismiss Notice
  6. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice
  7. Unity 2017.3 beta is now available for download.
    Dismiss Notice

Space Shooter Tutorial Q&A

Discussion in 'Community Learning & Teaching' started by Adam-Buckner, Mar 26, 2015.

  1. Jonberia

    Jonberia

    Joined:
    Dec 2, 2017
    Posts:
    5
    Good Afternoon!

    I’m having difficult time trying to figure out how to make enemy and player bolt not destroy each other but pass through each other.

    Also, I notice that the boundary is not destroying all of the enemy’s bolts when they exit the boundary as the game progress. Some of them manage to slip through without being destroy. I added destroy by time to ensure any stubborn enemy bolts get destroy, yet I’m unsure if that the best way to solve it. Any explanation why it happening would be most appreciated.

    Edit: Alright, I did a bit of experimenting to test my theory why some of the enemy bolt manage to slip over the boundary. I would like to add that I had set enemy fire rate at random. When an enemy ship reaches to -5 on the x-axis near the boundary where all things get destroy onTriggerExit. If an enemy ship manages to fire on the -5 x-axis, the bolt will spawn on the other side of the boundary and into the void. Again, I’m uncertain if destroy by time is the best method to destroy any lucky enemy bolt that manage to escape the boundary of death. I’m zuper open to suggestions.
     
    Last edited: Dec 3, 2017
  2. unity_Ab56OhQt2R4Idg

    unity_Ab56OhQt2R4Idg

    Joined:
    Dec 1, 2017
    Posts:
    2
    Hello,

    I am new to Unity. I am now on my second tutorial (after finishing the Rolling Ball one) and I am having some difficulties on making the bolt firing.

    I am using this C# script on the Bolt prefab:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Mover : MonoBehaviour {
    6.  
    7.     private Rigidbody rb;
    8.     public float speed;
    9.  
    10.     // Use this for initialization
    11.  
    12.     void Start () {
    13.         rb = GetComponent<Rigidbody>();
    14.  
    15.         rb.velocity = transform.forward * speed;
    16.     }
    17.  
    18. }
    What I find curios is that when I instanciate the Bolt prefab on the Scene, the bolt moves on the Y axis, instead of the Z axis. I have managed to work around this by specifing the bolt to move precisely on the Z axis using:

    Code (CSharp):
    1. rb.velocity = new Vector3(0f, 0f, 1f) * speed;
    It works perfectly now. I have added a Rigibody on my prefab and Use Gravity is NOT checked.

    What I also find curios is something on my Capsule Collider Compnent:
    The direction is set on the Y-Axis and it looks like on the Direction.png file

    When setting the Direction on the Z-Axis as specified in the tutorial it will end up looking like on the Direction2.png file.

    Am I doing something wrong? Even if I managed to correct it by using Vector3, I still wish to know what is wrong here. Thanks in advance. :)
     

    Attached Files:

  3. JxBalance

    JxBalance

    Joined:
    Dec 4, 2017
    Posts:
    3
    need help...
    i'm creating shots as the video told me, and there is no error with my code
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Mover : MonoBehaviour
    6. {
    7.     public float speed;
    8.     private Rigidbody rb;
    9.  
    10.  
    11.     void Start()
    12.     {
    13.         rb=GetComponent<Rigidbody>();
    14.         rb.velocity= new Vector3(0.0f, 0.0f, 1f) * speed;
    15.     }
    16. }
    but whenever i drag in the shot, it stuck on the screen.

    could someone find whats wrong with it?
     
  4. Jonberia

    Jonberia

    Joined:
    Dec 2, 2017
    Posts:
    5
    @unity_Ab56OhQt2R4Idg
    I'm curious, have you figure out your problem yet?

    @JxBalance
    Did you set your speed in the inspector window. It might be set at 0.
     
  5. unity_Ab56OhQt2R4Idg

    unity_Ab56OhQt2R4Idg

    Joined:
    Dec 1, 2017
    Posts:
    2
     
  6. GorkemP

    GorkemP

    Joined:
    Aug 29, 2013
    Posts:
    1
    Hi,

    When creating the shooter why do we need the 'shot spawn' GameObject exactly?

    Bolt prefab has already includes transform component, we can get the position and rotation from bolt prefab itself, why the following codes are not sufficient?

    Code (CSharp):
    or

    Code (CSharp):
    1. Instantiate(shot, shot.transform.position, shot.transform.rotation);
    When these codes are used, when fire is pressed prefabs are created and they are moved, it can be seen in the hierarchy window.

    Yet, it is not visible in the Game or Scene window. Why it is not visible?

    On the other hand, in play mode, if I just drag and drop prefab into hierarchy, it is created and visible in the Scene and Game windows.

    If answer to this question is that prefab's own transform component can not be used because the prefab's itself is not instantiated, why it works when we drag and drop prefab into the hierarchy? where does it takes its position and rotation?
     
    Last edited: Dec 5, 2017
  7. JxBalance

    JxBalance

    Joined:
    Dec 4, 2017
    Posts:
    3
    it is twenty:confused: i change it in to 20000000, the shot is still stuck
     
  8. JxBalance

    JxBalance

    Joined:
    Dec 4, 2017
    Posts:
    3
    ooooooooh I get it!!!
    i added the rigidbody to the VFX rather than the Bolt, so it doesn't work:)
     
    Jonberia likes this.
  9. Jonberia

    Jonberia

    Joined:
    Dec 2, 2017
    Posts:
    5
    @JxBalance
    Great work on figuring that one out!


    @GorkemP

    The prefab of bolt takes its position and rotation from transform in your inspector window, which is probably set to 0,0,0. As for your script, it will always instantiate Bolt position and rotation which is probably set to 0,0,0.

    Edit
    : When you move Bolt prefab into the hierarchy, did you disable Player Ship? There is a chance Bolt is at the same origin with Player Ship, 0,0,0; therefore it appear to be inside the Player Ship. Try disabling Player Ship or change Bolt position.
     
    Last edited: Dec 7, 2017
  10. arnhmail

    arnhmail

    Joined:
    Oct 14, 2017
    Posts:
    10
    Thank you, I figured it out as follows:

    turns out my randomrotator.cs and asteroidmover.cs scripts were locking each other up when both were trying to modify the same rigidbody from two different scripts, so I compiled them into one script and it seems to be running well.

    Don't know if that explains it, but by taking the same code and copying it into one file, it fixed the problem.
     
  11. Jonberia

    Jonberia

    Joined:
    Dec 2, 2017
    Posts:
    5
    I have resolved my issue with enemy and player bolt destroying each other on contact. While I was digging around for more information, I have come across layer. This have produce the desirable result I been looking for. For those of you who are curious, create a layer to hold both your Enemy Bolt and Player bolt. Then go into Edit > Project Setting > Physic, on Layer Collision Matrix, unchecked layer that is assign to Enemy Bolt and Player Bolt. This will allow anything under Bolt layer not to collide with each other. Although I’m still curious how would I accomplish this in code.
     
    Last edited: Dec 9, 2017
  12. BlackKnife12

    BlackKnife12

    Joined:
    Dec 8, 2017
    Posts:
    1
    Hi there,Adam

    I'm currently working on the Space Shooter game and I'm nearly done with the project.
    However,I'm having issues with the GUIText. I've followed the tutorials but the texts ('Score','Restart', and 'Game Over') don't appear. I even have the the Transform positions between 0 and 1,they still don't show up on my screen.
     
  13. Jonberia

    Jonberia

    Joined:
    Dec 2, 2017
    Posts:
    5
  14. p4hv1

    p4hv1

    Joined:
    Tuesday
    Posts:
    1
    Not sure has anyone else had this but I have two asteroids spawning simultaneuosly and exploding each other.
     
  15. unity_W2AoiuwCs31TpA

    unity_W2AoiuwCs31TpA

    Joined:
    Nov 18, 2017
    Posts:
    3
    Here are what i found in unity manual and Scripting API:
    Transform.forward: The blue axis of the transform in world space.
    Direction :The axis of the capsule’s lengthwise orientation in the object’s local space.
    Maybe you have changed the rotation of the bolt and the blue axis is now the Y axis in world space .This change also results in the second problem.
    I am new to unity too,i hope this is helpful.
     
  16. unity_W2AoiuwCs31TpA

    unity_W2AoiuwCs31TpA

    Joined:
    Nov 18, 2017
    Posts:
    3
    Hi,guys..
    I have done my Space Shooter game but i find something interesting.

    When i finish the enemy ship object and drag it to the Hazards array of the game controller object,hit the play button and it works fine.But the enemy ship doesn't move forward at all if you directly drag the enemy ship to the hierachy and play it .it seems the Mover script doesn't work in the latter situation.

    In order to figure out this ,i compare the mover script and the EvasiveManeuver script and come up with a hypothesis.First let 's take a glance at these two scripts.
    Mover:
    Code (CSharp):
    1. public class Mover : MonoBehaviour
    2. {
    3.     private Rigidbody rb;
    4.     public float speed;
    5.     void Start()
    6.     {
    7.         rb = GetComponent<Rigidbody> ();
    8.         rb.velocity = transform.forward * speed;
    9.         Debug.Log ("velocity set!");
    10.     }
    11. }
    EvasiveManeuver:
    Code (CSharp):
    1. void Start ()
    2.     {
    3.         rb = GetComponent<Rigidbody> ();
    4.         currentSpeed = rb.velocity.z;
    5.         Debug.Log ("currentSpeed set!");
    6.         StartCoroutine (Evade ());
    7.  
    8.     }
    9.    
    10.     IEnumerator Evade()
    11.     {
    12.         yield return new WaitForSeconds (Random.Range (startWait.x,startWait.y));
    13.         while (true)
    14.         {
    15.             targetManeuver = Random.Range (1,dodge)*-Mathf.Sign(transform.position.x);
    16.             yield return new WaitForSeconds (Random.Range (maneuverTime.x, maneuverTime.y));
    17.             targetManeuver = 0;
    18.             yield return new WaitForSeconds (Random.Range (maneuverWait.x, maneuverWait.y));
    19.         }
    20.     }
    21.  
    22.     void FixedUpdate()
    23.     {
    24.         float newManeuver = Mathf.MoveTowards (rb.velocity.x, targetManeuver, Time.deltaTime * smoothing);
    25.         rb.velocity = new Vector3 (newManeuver, 0.0f, currentSpeed);
    26.         rb.position = new Vector3
    27.             (
    28.             Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax),
    29.             0.0f,
    30.             Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)
    31.         );
    32.         rb.rotation = Quaternion.Euler (0.0f, 0.0f, rb.velocity.x * -tilt);
    33.     }
    As you can see ,the final velocity.z of enemy ship is determined by the value of currentSpeed in EvasiveManeuver script.the currentSpeed is assigned to rb.velocity.z in the Start function.We set rb.velocity.z to a specific value in the mover script.

    The hypothesis is that 'currentSpeed = rb.velocity.z;' sentence executes before 'rb.velocity = transform.forward * speed;' sentence in the latter case,so the currentSpeed will always be zero and the enemy ship can't move forward.

    To verify this i added two debug sentences in the mover script and EvasiveManeuver script respectively and the output in console proved the guess.

    Anyone knows what makes the defference?
    Thanks in advance.
     
  17. lorenfitts

    lorenfitts

    Joined:
    Nov 20, 2017
    Posts:
    1
    I have not seen an answer on this and I need it figured out. being on the unity website and so outdated, they need to just create a new Tutorial for Space Shooter.

    When I write in my script for ship movements via the "w,a,s,d" keys, I get no reaction from my ship when I play the game and the error is this:
    NullReferenceException: Object reference not set to an instance of an object
    PlayerController.FixedUpdate () (at Assets/Scripts/PlayerController.cs:22)

    my Script:
    public class PlayerController : MonoBehaviour
    {
    void FixedUpdate()
    {

    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

    GetComponent<Rigidbody>();
    Rigidbody rigidbody = new Rigidbody();
    Rigidbody.velocity = movement;
    }

    }
     
  18. Bluesky_93

    Bluesky_93

    Joined:
    Thursday
    Posts:
    3
    I think my UNITY Engine is broke^^

    It all worked really really well until the video 14.

    I checked now everything for at least 6hours.
    I compared my script to the "Done" scripts - everything is perfect but it does not work.

    Even when I try to play the "Done_Main" game - it does not work.
    The console replys with compiling errors (see the screenshot).
    Thats so frustrating... if someone finds the error - please tell me.

    Funny thing is: my game does work - but now the asteroids are missing. they do not spawn anymore.
    Also sometimes Unity reads my "GameController1.cs" script and sometimes it doesnt (I do not change anything)
    When it doesnt, I says "the associated script can not be loaded." wich ist total BS, because 2 minutes earlier it did.
    Also - when I play the game, the "Score Text" stays as a place holder.
     

    Attached Files:

    Last edited: Dec 14, 2017 at 11:32 PM
  19. Doni16

    Doni16

    Joined:
    Dec 11, 2017
    Posts:
    2
    I recently started Space Shooter Tutorial with Unity 2017.2 and I have problem regarding player explosion. I wrote my code exactly as shown in the tutorial and everything is happening in the same way but when I hit the asteroid with my player they don't explode; just the player gives a strong force to asteroid and asteroid is moving as a result. What can be the reason?
     
  20. Bluesky_93

    Bluesky_93

    Joined:
    Thursday
    Posts:
    3

    I agree, they have to make a new one - but your issue was posted in the YT commentary section about 20times and all the top comments are full with it^^ AND they also wrote the solution as an overlay into the video. xD
    I'm not judging but...yeah.

    you need to get your Rigidbody in void Start.


    private Rigidbody rb;

    void Start
    {
    rb = GetComponent<Rigidbody>();
    }

    .
    .
    .

    rb.velocity = movement;
     
  21. Bluesky_93

    Bluesky_93

    Joined:
    Thursday
    Posts:
    3
    You need to post a screenshot. It's not possible to see the issue otherwise. :)
     
  22. Doni16

    Doni16

    Joined:
    Dec 11, 2017
    Posts:
    2
    Here is are the details:
    DestroyByForce:

    using System.Collections;
    using UnityEngine;

    public class DestroyByContact : MonoBehaviour
    {
    public GameObject explosion;
    public GameObject playerExplosion;

    void OnTriggerEnter(Collider other)
    {
    if (other.tag == "Boundary")
    {
    return;
    }
    Instantiate (explosion, transform.position, transform.rotation);
    if (other.tag == "Player")
    {
    Instantiate (playerExplosion, other.transform.position, other.transform.rotation);
    }
    Destroy(other.gameObject);
    Destroy(gameObject);
    }
    }

    Player Controller:

    using UnityEngine;
    using System.Collections;

    [System.Serializable]
    public class Boundary
    {
    public float xMin, xMax, zMin, zMax;
    }

    public class PlayerController : MonoBehaviour
    {
    public float speed;
    public Boundary boundary;
    public float tilt;

    public GameObject shot;
    public Transform shotSpawn;
    public float myTime = 0.0F;
    public float fireDelta = 0.5F;

    private float nextFire = 0.5F;

    void Update ()
    {
    myTime = myTime + Time.deltaTime;

    if (Input.GetButton ("Fire1") && myTime > nextFire)
    {
    nextFire = myTime + fireDelta;
    Instantiate (shot, shotSpawn.position, shotSpawn.rotation);

    nextFire = nextFire - myTime;
    myTime = 0.0F;
    }
    }

    void FixedUpdate ()
    {
    float moveHorizontal = Input.GetAxis ("Horizontal");
    float moveVertical = Input.GetAxis ("Vertical");

    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
    GetComponent<Rigidbody>().velocity = movement * speed;

    GetComponent<Rigidbody>().position = new Vector3
    (
    Mathf.Clamp (GetComponent<Rigidbody>().position.x, boundary.xMin, boundary.xMax),
    0.0f,
    Mathf.Clamp (GetComponent<Rigidbody>().position.z, boundary.zMin, boundary.zMax)
    );

    GetComponent<Rigidbody>().rotation = Quaternion.Euler (0.0f, 0.0f, GetComponent<Rigidbody>().velocity.x * -tilt);
    }
    }
     

    Attached Files:

  23. unity_P_E6_wAQcwWw2g

    unity_P_E6_wAQcwWw2g

    Joined:
    Friday
    Posts:
    1
    Hi I have a problem when play the game, if i shot to asteroid, the game crash.

    This is the error:
    NullReferenceException: Object reference not set to an instance of an object
    DestroyByContact.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/DestroyByContact.cs:35)

    C# Script:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class GameController : MonoBehaviour {
    public GameObject hazard;
    public Vector3 spawnValues;
    public int hazardCount;
    public float spawnWait;
    public float startWait;
    public float waveWait;
    public GUIText scoreText;
    private int score;

    // Use this for initialization
    void Start ()
    {
    score = 0;
    UpdateScore ();
    StartCoroutine (SpawnWaves ());
    }

    IEnumerator SpawnWaves ()
    {
    yield return new WaitForSeconds (startWait);
    while (true)
    {
    for (int i = 0; i < hazardCount; i++) {
    Vector3 spawPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
    Quaternion spawnRotation = Quaternion.identity;
    Instantiate (hazard, spawPosition, spawnRotation);
    yield return new WaitForSeconds (spawnWait);
    }
    yield return new WaitForSeconds (waveWait);
    }
    }

    public void AddScore (int newScoreValue)
    {
    score += newScoreValue;
    UpdateScore();
    }

    void UpdateScore()
    {
    scoreText.text = "Score: " + score;
    }
    }
     

    Attached Files:

  24. JGrace

    JGrace

    Joined:
    Nov 25, 2017
    Posts:
    1
    Hi I'm new, I've made the Space Shooter up to adding the explosions. I get no errors but no explosions are appearing. Here's my script:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    public class DestroybyContact : MonoBehaviour
    {
    public GameObject explosion;
    public GameObject playerExplosion;
    void OnTriggerEnter(Collider other)
    {
    if (other.tag == "Boundary")
    {
    return;
    }
    Instantiate(explosion, transform.position, transform.rotation);
    if (other.tag == "Player")
    {
    Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
    }
    Destroy (other.gameObject);
    Destroy (gameObject);
    }
    }

    There's a pencil next to the DestroybyContact script...does that matter? It says 'Default references will only be applied in edit mode"
    upload_2017-12-17_11-39-40.png

    I've also tried unticking Play on Awake* in the asteroid VFX inspector as that was mentioned in another Q&A...to no avail
     
  25. thesixx

    thesixx

    Joined:
    Yesterday
    Posts:
    1
    Hey guys!

    im working on the spaceshooter project but:
    for some reason my spaceship goes down on the Z value and wont slide left or right and shoot once its builden till the end with no problems but suddenly this came up and i can't find the error!
     
  26. peteowl

    peteowl

    Joined:
    Saturday
    Posts:
    3
    I'm not there yet in the tutorial, I'll reply later if I have the same issue when I get there (I'm new to Unity but I'm a seasoned coder so I can still answer some not-too-unity-related questions).

    These two scripts are different, so there will be an order of execution. In your case it seems that the Start() for the mover gets executed before the Start() for the Evasive maneuver.
    To solve this I suggest you put the code for getting the current speed in your EvasiveManeuver.FixedUpdate code, it will make more sense I think, to get the current speed at the moment of the evasive maneuver and not at the object spawn. [Edit]: I just did that part and actually got rid of currentSpeed entirely, I'm just using rb.velocity.z directly - my suggestion still stands, it will have the same effect.

    The error suggest that one of the references in your script is not set, you need to make sure all your references are properly set.
    Check at line 35 to see which reference seems to be unset.
    Attaching to Unity, bebugging and using a breakpoint might help (Visual Studio can do it, not sure about the built in editor).

    @All, a general remark: please use the CODE tags when posting code, it makes it much easier if anyone wants to help.

    Cheers - P
     
    Last edited: Dec 18, 2017 at 4:02 AM
  27. peteowl

    peteowl

    Joined:
    Saturday
    Posts:
    3
    I think the message with the pencil indicates you did some changes in play mode and these changes will be lost when exiting play mode. Only changes done in edit mode are saved.
    If the script is correct with respect to the tutorial video, check the references, you can review your project to verify if the references are set or maybe put some debug code at the beginning of the trigger:
    Code (CSharp):
    1.  
    2. if (explosion == null)
    3.     Debug.Log("explosion is NOT set!");
    4. else
    5.     Debug.Log("explosion is set");
    6. if (playerExplosion == null)
    7.     Debug.Log("playerExplosion is NOT set!");
    8. else
    9.     Debug.Log("playerExplosion is set");
    10.  
     
  28. peteowl

    peteowl

    Joined:
    Saturday
    Posts:
    3
    It looks like your collider is not a trigger collider. Try changing the asteroid's collider in the inspector, check "Is Trigger"
     
  29. unity_W2AoiuwCs31TpA

    unity_W2AoiuwCs31TpA

    Joined:
    Nov 18, 2017
    Posts:
    3
    Thanks for your reply.
    It works fine by using your suggestion.But the point is what causes the difference(dragging it to the scene directly it doesn't move forward but dragging it to the hazards array it can move forward).In other words what determines the execution order of the same fuction(like Start()) in different scripts of a GameObject?
    Thanks again!