Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Space Shooter Tutorial Q&A

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

  1. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    This is because you didn't set the mover speed to static.

    I'd suggest, however, that you change the mover speed per instance when instantiating.

    To understand how to get an object reference when instantiating, please see the documentation on Object.Instantiate, and note how to take the reference, which in the associated code snippet is called clone.

    With the object reference, you can get the mover component and set the speed.
     
  2. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    OBTW, @OboShape, the rest is keen. Just don't set the static enemy mover speed, but set a private variable like currentHazardSpeed and use that the set the hazards per instance.

    Be aware that the hazards don't currently collide with each other as they are all going the same speed down screen. If the speed is mixed, per screen, then some other mechanic must be used to prevent the hazards from colliding with, and destroying, each other.
     
  3. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    And, lastly, @OboShape, if you're going to work this out for our gentleman (genteel person?) inquisitor, please do post it for everyone to see.
     
  4. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    yep will do once I've got it done correctly, don't want to mislead anyone down a dark coding path :)
     
  5. kmj1996

    kmj1996

    Joined:
    Sep 1, 2015
    Posts:
    8
  6. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Fear the darkside of coding! Wait... fear... leads to... agh... circular... logic... <head asplodes>

     
  7. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    @kmj1996 ok, just been back to the drawing board, this will increase the enemy speed every say 100 points as requested. its a little more thought out than my last rapid response, and not a static in sight, just using content thats been covered already in the first few tutorials :)

    but bear in mind that these are just my ideas from a fellow student..

    any probs, ill edit, here goes .....

    I created a new script called 'EnemyMover.cs' and this replaced the Mover.cs script (which now only handles the bolts) that was attached to the hazards.

    the EnemyMover script is short and has the following:-
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class EnemyMover : MonoBehaviour
    5. {
    6.     // basically this script is all controlled from the GameController script and called after this object is instantiated
    7.     public void MoveEnemy( float speed)
    8.     {
    9.         Rigidbody rb = GetComponent<Rigidbody>();
    10.         rb.velocity = transform.forward * speed;
    11.     }
    12. }
    so with that saved, I removed the Mover script from the hazard prefabs, and added this EnemyMover script.

    The other alterations that I had to do were within the GameController script, thankfully just in three places.

    at the top, I put in some extra public declarations just below the ones that are there already. so these can be adjusted via the inspector and adjust to taste.
    Code (CSharp):
    1.     //------------------ SCRIPT ADDITIONS ------------------------------------------------------
    2.     // whats the score threshold we want to increase on (ie every 100 points as below)
    3.     public int speedIncreasePointsThreshold = 100;
    4.     // our starting enemy speed (changeable in inspector)
    5.     public  float enemySpeed = -2f;    
    6.     // once the threshold is reached, how much do we want to increment enemy speed by. (again, can be altered via inspector)
    7.     public float enemySpeedIncrement = 1f;
    8.     // ---------- END OF ADDITIONS ------------------------------------------------------------
    within the SpawnWaves() function, I changed around the following lines, ive shown the lines above and below where the changes were made, to give a point of reference.
    Code (CSharp):
    1.                 Quaternion spawnRotation = Quaternion.identity;
    2.  
    3.                 // --------------------- changes in script start here -----------------------------------------------
    4.                 GameObject tempObject =  Instantiate (hazard, spawnPosition, spawnRotation) as GameObject;
    5.                 // get a reference to the attached EnemyMover script, if there isnt one, it returns NULL
    6.                 EnemyMover enemyMover = tempObject.GetComponent<EnemyMover>();
    7.                 // make sure that there is an EnemyMover component, before trying to call a function on it.
    8.                 if(enemyMover)
    9.                     enemyMover.MoveEnemy(enemySpeed);
    10.                 // --------------------- end of changes in this function  ---------------------------------------------
    11.  
    12.                 yield return new WaitForSeconds (spawnWait);
    13.             }
    14.             yield return new WaitForSeconds (waveWait);
    15.            
    and within the AddScore function i made the following alterations.
    Code (CSharp):
    1.     public void AddScore (int newScoreValue)
    2.     {
    3.         score += newScoreValue;
    4.         UpdateScore ();
    5.  
    6.         // --------------------- changes in script start here -----------------------------------------------
    7.         // basically here, when there is a score change, check to see if our current score is an exact multiple of our
    8.         // threshold with no remainder (c# flavor of % shows remainder values)
    9.         // and we only really want this to be checked once each time the score is updated.
    10.         Debug.Log (score % speedIncreasePointsThreshold);
    11.         if(score % speedIncreasePointsThreshold == 0)
    12.         {
    13.             enemySpeed -= enemySpeedIncrement;
    14.         }
    15.         // --------------------- end of changes in script  ------------------------------------------------------------
    16.     }
    as a little gotcha, this model will only work if your game scoring system, can give multiples of your points threshold, otherwise your remainder values will never be 0, and therefore speed will never be increased..
     
    Last edited: Sep 17, 2015
  8. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    @OboShape yup that works! Nice.

    If it were me, and this is only flavour, nothing else...

    I would have kept Mover.cs and simply used:
    Code (CSharp):
    1. If (mover)
    2.    mover.speed = myMoveValue;
    I think that'd work without testing... But your solution is perfectly fine!

    Ace!
     
  9. TsI_Badger

    TsI_Badger

    Joined:
    Sep 1, 2015
    Posts:
    4
    They are both set to values that are not 0.
     
  10. Cylibus

    Cylibus

    Joined:
    Mar 29, 2014
    Posts:
    6
    The audio assets don't seem to be working for me, even when I press the play button in the preview nothing happens.
     
  11. dcolzani

    dcolzani

    Joined:
    Sep 22, 2014
    Posts:
    19
    Having the same issue but this did not fix my issue. To be clear, I'm making a 2D (just 2d sprites, the game is still set to 3d) version of the game and using a box collider here. If I uncomment this code //gameController.AddScore(scoreValue); my objects get destroyed just fine but as soon as I add it in no objects get destroyed. I have to compile errors.
     
    Last edited: Sep 19, 2015
  12. IanSmellis

    IanSmellis

    Joined:
    Nov 2, 2014
    Posts:
    26
    Not trying to be rude, but if you don't follow the tutorial you might not get the right help you need.
     
    OboShape likes this.
  13. Jean_Paul

    Jean_Paul

    Joined:
    Sep 9, 2015
    Posts:
    7
    This may not be the best place to ask, but I'll try anyway. I'm building upon this tutorial, and I'm adding different weapons as power-ups and other ships for the player to control. I want to add a force shield effect to the player ship. What would be the best approach to get a nice effect? I tried using a sphere with a transparent texture and a particle effect on hit, it looks ok-ish, but it's not great. Am I right to assume custom shaders would be a better solution? Or any other ideas i could try. I did try a few of the free assets, but to no avail, unless I missed something lol
     
  14. dcolzani

    dcolzani

    Joined:
    Sep 22, 2014
    Posts:
    19
    I'd agree but, someone else had a similar issue. The only difference in my game is my objects aren't 3d models, just 2d sprites I made in photoshop. Everything has worked up to this point. Even if I switch it to a mesh collider, my results are the same.
     
  15. revilofr

    revilofr

    Joined:
    Sep 19, 2015
    Posts:
    1
    or... not ;)

    Actually I experienced the same bug with the lastest version of Unity. I did have assigned the playerexplosion but I had an UnassignedRefenceException.

    I tried to put it to None and then reassign it but it didn't work. I added a nullity test before, same thing.

    The only thing which worked was : quit, re launch unity, load project, load the scene.

    I hope it will be helpfull.

    To all unity team : Guys you do an amazing work. I'm really impressed regarding the quality of your product ! all the best to you all !
     
  16. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    try popping a question in, or have a look in the shader section. probably the best section to get a good response.
    there is one thread there that has a force field esque shader there.
    but heres the main thread
    http://forum.unity3d.com/forums/shaders.16/
     
    Jean_Paul likes this.
  17. Invasive_metrics

    Invasive_metrics

    Joined:
    Sep 20, 2015
    Posts:
    1
    My bolt sinks.... I have use gravity turned off, I've checked to make sure my bolt and the done bolt were identical, and my mover code looks thusly:

    using UnityEngine;
    using System.Collections;

    public class mover : MonoBehaviour {

    private Rigidbody rb;
    public float speed;


    // Use this for initialization
    void Start () {
    rb = GetComponent<Rigidbody>();
    rb.velocity = rb.transform.forward * speed;

    }

    // Update is called once per frame
    void Update () {

    }
    }


    I thought I was bypassing the lack of helpers is that what's wrong?
     
  18. Jean_Paul

    Jean_Paul

    Joined:
    Sep 9, 2015
    Posts:
    7
    Thank you ;)
     
  19. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    Not sure, just a couple of thoughts...
    theres no rotation within the bolt prefab?
    are both the boundary and bolts colliders set to trigger?
    and you have gravity turned off for the bolt like you said.

    when they sink, i take it they last a while before going out of sight. do they look like they fire straight, or does it look like theres some rotation on them?


    if you were to play the game, drag a bolt prefab into the scene, does that move correctly, or vanish in the same way as the instantiated bolts?

    just a couple of ideas..
     
    IanSmellis likes this.
  20. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Ok, we need to strip this down and start from the beginning. At what stage did the project stop working?

    The fastest way to get up and running would be to go back to that lesson, and to go back to a saved version of your project at that point and follow the videos very closely and see what you've missed. (Fwiw, I just completed the entire series from scratch for tonight's live training class, and it worked perfectly when I followed all the steps!)

    If this is not possible then can you give me as compete a summary as you can, including all the questions and answers we've covered?
     
  21. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Can you give us any more details? Also - just to make sure, have you upgraded to the most recent version of the editor, restarted Unity and your machine?
     
  22. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Please make sure you are not mixing physics and physics2d. They are compatible, but not communal. They can both be in the same project, but won't work together. A 2D collider will not collide with a 3D collider,many both have their own methods (eg: OnTriggerEnter and OnTriggerEnter2D, Rigidbody and Rigidbody2D).
     
  23. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    You can try a particle effect that emits from the edges or vertices of a sphere. Two counter rotating / randomly rotating spheres with an animated texture. There are custom shield / force field shaders on the asset store. It all depends on the look you want!
     
  24. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    An unassigned reference exception is not a bug In Unity.

    It is an issue with the project.

    At runtime, a script cannot find a required object. There are many reasons that this can happen. First, you need to isolate the state of your game at the point you are getting the null ref. either you have not linked the appropriate item, or the item is missing, destroyed or perhaps on a different object.
     
  25. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Please learn to use code tags properly:
    http://forum.unity3d.com/threads/using-code-tags-properly.143875/
     
  26. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    What is the orientation of your bolt? The bolt parent object should have no rotation. The bolt VFX should have 90* in the x. There should be only 1 Rigidbody, and 1 collider - both on the parent GameObject. Gravity on the 1 Rigidbody should be false (unticked). When instantiated, they see given the position and rotation of the shotSpawn transform. Is there an accidental rotation of the shotSpawn?
     
  27. TsI_Badger

    TsI_Badger

    Joined:
    Sep 1, 2015
    Posts:
    4
    Ok thanks for all of you help.
     
  28. cubialpha

    cubialpha

    Joined:
    Sep 21, 2015
    Posts:
    1
    I've finished the tutorial (I've even used my own assets for a different look) and it's fine. But my question is, where is the next part of the tutorial (if there is one)? For the enemy ships, etc?
     
  29. yuvalw12

    yuvalw12

    Joined:
    Sep 21, 2015
    Posts:
    4
    HI Guys!
    i have a problem in the part of Creating Shots.

    my code is the same as the tutorial and eveything work fine but when i shot, the bolt dont move smoothly.
    any ideas of how to fix it?
     
  30. Mr.Mille

    Mr.Mille

    Joined:
    Sep 17, 2015
    Posts:
    21
    The Mover script should be attached to your Bolt prefab. It should look like this:
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class Mover : MonoBehaviour
    6. {
    7.     public float speed;
    8.  
    9.     void Start ()
    10.     {
    11.         GetComponent<Rigidbody>().velocity = transform.forward * speed;
    12.     }
    13. }
    You should set the speed variable to 20 in the Inspector.
     
  31. yuvalw12

    yuvalw12

    Joined:
    Sep 21, 2015
    Posts:
    4

    thanx, but my code is the same and the speed is 20 but still the bolt dont move smoothly like in the tutorial.
    to visualize how the bolt move:
    how i expect it to move:-------------------------
    how its actually move:-- -- -- -- -- --
    and its move very slow
     
  32. Mr.Mille

    Mr.Mille

    Joined:
    Sep 17, 2015
    Posts:
    21
    Check ther Fire Rate in the Inspector of the Player Component Script 'PlayerController'. It should be 0.25
     
  33. yuvalw12

    yuvalw12

    Joined:
    Sep 21, 2015
    Posts:
    4
    It is 0.25
     
  34. Mr.Mille

    Mr.Mille

    Joined:
    Sep 17, 2015
    Posts:
    21
    1. Compare your PlayerController Script with Done_PlayerController and make sure you coded your PlayerController properly.
    2. Make sure, that the ShotSpawn doesn't collide with player collider.
     
  35. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    We just did that tonight as a live session. It should be posted in the archive this week.
     
  36. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Check you only have one rigidbody, and that it's on the parent, not the VFX object. Make sure there is only one collider, the capsule, and that it's on the parent...
     
  37. bluejv7

    bluejv7

    Joined:
    Sep 14, 2015
    Posts:
    1
    Wanted to make a note for the audio section and ask a question about AudioSource naming conventions.

    When trying to cache the AudioSource with a variable named "audio", the autocomplete will not recognize your new variable (probably a keyword for unity?). This tripped me up a bit until I renamed the variable "audioSource".

    Code (CSharp):
    1. ...
    2. public AudioSource audioSource;
    3.  
    4. void Start() {
    5.     audioSource = GetComponent<AudioSource>();
    6. }
    7.  
    8. ...
    9. audioSource.play();
    What is the standard for naming an AudioSource file? I remember someone mentioning Rigidbody usually being named "rb".
     
  38. TaoBro

    TaoBro

    Joined:
    Sep 20, 2015
    Posts:
    1
    Hi everybody! Hello Adam.

    I am having difficulties to implement GetComponent<Rigidbody>() as a reference as you suggested for it to work in Unity 5.
    I understand this has to be done:

    private Rigidbody rb;

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


    But can anybody please show how to properly do this in the actual scrip context?
    I mean, where on the scrip, "after what" and "before what".
    I cant seem to place this code correctly.

    BTW: this method is not used in the "Done_PlayerController.cs" script provided for me to compare.

    Thank you in advanced!
     
  39. Abaddon89

    Abaddon89

    Joined:
    Sep 20, 2015
    Posts:
    1
    Hello everybody!
    I'm doing this tutorial and I find it great so far. Nonetheless I'm getting some trouble with part 3.02. I'm trying to implement the score calculation and its update on screen, but I get some weird behaviour. I'm using Unity 5.2.0 and I decided to display the score using a Text component instead of the GUIText (I've tried with both, but when I noticed that the error was the same, I reverted to use Text).

    I get this error:
    But this is weird, I double checked a thousand times the reference in the inspector and it's correctly set. Furthermore the error appears everytime the UpdateScore() method is called, so one time at the start of the game, and everytime an asteroid get hit. But even if the error appears at the start of the game, the score is set to 0 and displayed correctly, but doesn't update at the collision with the asteroids (to be more precise, the int variable score get updated correctly, but not the Text).

    This is my code:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4.  
    5. public class GameController : MonoBehaviour {
    6.  
    7.     public GameObject hazard;
    8.  
    9.     public int hazardsPerWave;
    10.     public float hazardRate;
    11.     public float prepTime;
    12.     public float timeBetweenWaves;
    13.     public Vector3 spawnPosition;
    14.  
    15.     public Text scoreText;
    16.     private int score;
    17.  
    18.     // Use this for initialization
    19.     void Start () {
    20.         score = 0;
    21.         UpdateScore();
    22.         StartCoroutine(SpawnWaves());
    23.     }
    24.  
    25.     IEnumerator SpawnWaves()
    26.     {
    27.         yield return new WaitForSeconds(prepTime);
    28.         while(true)
    29.         {
    30.             for(int i=0; i<hazardsPerWave; i++)
    31.             {
    32.                 Vector3 position = new Vector3(Random.Range(-spawnPosition.x, spawnPosition.x), spawnPosition.y, spawnPosition.z);
    33.                 Quaternion rotation = Quaternion.identity;
    34.                 Instantiate(hazard, position, rotation);
    35.                 yield return new WaitForSeconds(hazardRate);
    36.             }
    37.             yield return new WaitForSeconds(timeBetweenWaves);
    38.         }
    39.     }
    40.  
    41.     public void AddScore(int newScoreValue)
    42.     {
    43.         score += newScoreValue;
    44.         UpdateScore();
    45.     }
    46.  
    47.     void UpdateScore()
    48.     {
    49.         scoreText.text = "Score: " + score;
    50.     }
    51. }
    I partially resolved the problem setting manually the Text variable in the Start method. This is the working code for me:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4.  
    5. public class GameController : MonoBehaviour {
    6.  
    7.     public GameObject hazard;
    8.  
    9.     public int hazardsPerWave;
    10.     public float hazardRate;
    11.     public float prepTime;
    12.     public float timeBetweenWaves;
    13.     public Vector3 spawnPosition;
    14.  
    15.     private Text scoreText;
    16.     private int score;
    17.  
    18.     // Use this for initialization
    19.     void Start () {
    20.         scoreText = GameObject.FindWithTag("ScoreText").GetComponent<Text>();
    21.         score = 0;
    22.         UpdateScore();
    23.         StartCoroutine(SpawnWaves());
    24.     }
    25.  
    26.     IEnumerator SpawnWaves()
    27.     {
    28.         yield return new WaitForSeconds(prepTime);
    29.         while(true)
    30.         {
    31.             for(int i=0; i<hazardsPerWave; i++)
    32.             {
    33.                 Vector3 position = new Vector3(Random.Range(-spawnPosition.x, spawnPosition.x), spawnPosition.y, spawnPosition.z);
    34.                 Quaternion rotation = Quaternion.identity;
    35.                 Instantiate(hazard, position, rotation);
    36.                 yield return new WaitForSeconds(hazardRate);
    37.             }
    38.             yield return new WaitForSeconds(timeBetweenWaves);
    39.         }
    40.     }
    41.  
    42.     public void AddScore(int newScoreValue)
    43.     {
    44.         score += newScoreValue;
    45.         UpdateScore();
    46.     }
    47.  
    48.     void UpdateScore()
    49.     {
    50.         scoreText.text = "Score: " + score;
    51.     }
    52. }
    This way the game runs properly without any error, but still, it's strange and I'd like to know where I made a mistake.
    Thank you!
     
  40. yuvalw12

    yuvalw12

    Joined:
    Sep 21, 2015
    Posts:
    4
    Thank you very much!
    The rigidbody on the VFX object was the problem.
     
  41. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    You can name it anything you want! public AudioSource aardvarkNation; for example, works just fine. The only thing you can't use are reserved keyworks. The old "rigidbody" is a keyword used to trigger a warning that the previous shortcuts are obsolete. I suspect the same is true for the use of "audio".

    In our example and lessons public Rigidbody rb; is the usual name, but it's not absolute. In my scripts I use public AudioSource audioSource;
     
  42. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Can you please learn to use code tag properly?

    http://forum.unity3d.com/threads/using-code-tags-properly.143875/
     
  43. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    You have written this code correctly, yes.

    I'm unclear what your problem is, to be honest.

    If you can't figure out how to use/place this code, you may need to back up one level and look at the basic scripting lessons in the "Learn" section of our website.

    This should work fine as long as you include this code within the class structure of a C# script. This code will create a variable to hold a reference to a Rigidbody, and will then try to populate that reference by finding the component on the same GameObject as the script. If there is not Rigidbody component on the same GameObject as this script, the "GetComponent" call will return null.
     
  44. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Huh... odd. FWIW, I can't see anything overtly wrong with either script... which leads me to think that there must be an error in the the project and hierarchy.
     
  45. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    You're welcome!
     
  46. JaxD

    JaxD

    Joined:
    Sep 18, 2015
    Posts:
    7
    Hello,

    I am having an issue when my shot objects are being destoryed by the boundary collider, it create multiples of clones.
    Code (CSharp):
    1. Shot (clone)
    2. Shot (clone) (clone)
    3. Shot (clone) (clone) (clone)
    When all the Shot object clones are destroyed, I get an error message "MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it."

    This is my shoddy PlayerController script in all its nasty glory, mix and match of people's suggestion on the Youtube video.


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. [System.Serializable]
    5. public class Boundary
    6. {
    7.     public float xMin, xMax, zMin, zMax;
    8. }
    9.  
    10. public class PlayerController : MonoBehaviour
    11. {
    12.     public float speed; //sets a speed value that will multiply the speed value
    13.     public float tilt;
    14.     public Boundary boundary;
    15.     private Rigidbody rb;
    16.  
    17.     public GameObject shot;
    18.     public Transform shotSpawn;
    19.     public float fireRate;
    20.  
    21.     private float nextFire;//limits how fast a player can shoot, fire rate
    22.  
    23.     void Start()
    24.     {
    25.  
    26.         rb = GetComponent<Rigidbody>();     //The new shape to push an information from Rigidbody. I think.
    27.  
    28.     }
    29.  
    30.     void Update()
    31.     {
    32.         if (Input.GetButton("Fire1") && Time.time > nextFire) //when the LMB is pressed and the game time is great than the nextFire float the Instantiate will spawn a shot
    33.         {
    34.             shot = Instantiate(shot) as GameObject;
    35.             nextFire = Time.time + fireRate;
    36.             //GameObject clone =
    37.             shot.transform.position = shotSpawn.transform.position;
    38.         }
    39.  
    40.     }
    41.     void FixedUpdate()
    42.     {
    43.         float moveHorizontal = Input.GetAxis ("Horizontal");
    44.         float moveVertical = Input.GetAxis ("Vertical");
    45.  
    46.         Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
    47.         rb.velocity = movement * speed;
    48.  
    49.         rb.position = new Vector3
    50.          (
    51.           Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax),
    52.           0.0f,
    53.           Mathf.Clamp(rb.position.z, boundary.zMin, boundary.zMax)
    54.           );
    55.  
    56.         rb.rotation = Quaternion.Euler(0.0f, 0.0f, rb.velocity.x * -tilt); //tilts the player ship and adjust according to the player velocity
    57.     }
    58. }
    Edit: I've sorted out my issue, it's the shot instantiate line. I saw a code here that instantiate the game object with its position. It removed the multiple clones.

    Code (CSharp):
    1.             Instantiate(shot, shotSpawn.position, shotSpawn.rotation); //as GameObject;
    2.  
     
    Last edited: Sep 23, 2015
  47. Fran_Ayrolo

    Fran_Ayrolo

    Joined:
    Sep 23, 2015
    Posts:
    1
    Hi, maybe my question doesn't exactly go here, but maybe someone can point me in the right way.
    I came to Unity with some ideas for 2D games mostly, although I'm liking the things you can do with 3D. I picked the Space Shooter tutorial since it was among the basics and the most similar to a 2D game.
    So, as suggested, I decided to start by building a Pong game, the simplest 2D game there is. The problem is I don't know how to extrapolate the moving commands (the Vector3 stuff) from the spaceship into the black rectangle I made to use as an object in my game. I got a bit tangled with the documentation, so I started watching some lessons in the "Scripting" tutorials, but it looks like they are more about describing what each thing is, instead of what to do with them. Overall I'm realely new to coding or scripting.

    Another thing. I made the rectangle using GIMP. When making my game object, that will be represented by that rectangle, should I import it as an asset, create an empty game object and drop it inside? Import it as a sprite?

    I have some guesses for how the ball would behave: give both rectangles and the ball a Rigidbody and a collider (gravity 0, of course) and tick "Is Trigger". Then create a scrip as a component of the ball, saying that OnTriggerEnter, change the direction of the ball. Now, what I don't know is how to tell it to change. The script that makes it move when it spawns would be like "Mover", except that instead of saying:
    rigidbody.velocity = transform.forward * speed;
    I'd have to give it a random direction, and I'm stuck again :/

    Btw, thanks for making the tutorial!
     
  48. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    What was going on in that previous code that you had written, was that by using shot, which is the public variable which you are making a reference to the object your instantiating, every time you create a new shot you were changing the reference to the shop that you just instantiated. That's right you just instantiated would be shot clone so the next one would be shot clone clone. Also that shot is an instance in the scene, so when it's destroyed the system loses the reference and it becomes null. Your previous code would've worked perfectly fine, if you had created a new game object to store the instantiated shot clone into. And then setting the position and rotation as you did would work successfully. However, as you have discovered, there is a better easier way by adding the position and rotation at the same time.

    By the way, how did you end up with that code, which is so radically different from what we showed in the tutorial?
     
  49. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Try posting in the free live online training thread, and I'll try to help you there. Take a look at the live archives as well, as we have some 2D lessons there.
     
  50. JaxD

    JaxD

    Joined:
    Sep 18, 2015
    Posts:
    7
    I got the Instantiate class, that fixed my clone issue, from this exact forum. A post by R42 in page 9 of this thread. He post his Player Controller code, he claimed as clean.

    The rest should be from the video and some of the correction people made in the YouTube comments.