Search Unity

Official 2D Roguelike: Q&A

Discussion in 'Community Learning & Teaching' started by Matthew-Schell, Feb 10, 2015.

Thread Status:
Not open for further replies.
  1. WoodyPal

    WoodyPal

    Joined:
    Apr 22, 2015
    Posts:
    2
    Plz help me, I am up to part 9 and am really confused. I have finished the tutorial and have copped all of the code from under the tutorial and have deleted the namespace Completed {} but it is still coming up with a error in the Moving Object script '(4,23) error CS0101: The Namespace 'global::' already contains a definition of 'Moving Object'. This is what I wrote in my code:
    using UnityEngine;
    using System.Collections;

    public abstract class MovingObject : MonoBehaviour
    {
    public float moveTime = 0.1f; //Time it will take object to move, in seconds.
    public LayerMask blockingLayer; //Layer on which collision will be checked.


    private BoxCollider2D boxCollider; //The BoxCollider2D component attached to this object.
    private Rigidbody2D rb2D; //The Rigidbody2D component attached to this object.
    private float inverseMoveTime; //Used to make movement more efficient.

    Line 4 is the line 'public abstract class MovingObject : MonoBehaviour'
    Plz help as I want to continue my tutorial. Thanks
     
  2. Maraku Mure

    Maraku Mure

    Joined:
    May 2, 2015
    Posts:
    28
    Don't worry about it =)
    You are helping me, you don't have to apologize for a "delay" :D

    I'll wait =)
     
  3. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    Maraku,

    struggling to find what the prob might be or how to help with this one :(
    Might have to wait for Matt to get back from his travels to advise you further.

    *backup your project before trying these, just in case*

    theres been a something similar i think to what your experiencing raised in the answers page.
    http://answers.unity3d.com/questions/939656/ui-components-have-missing-scripts.html

    (**but i would back up your project folder before trying this, then when reloading it will reimport all assets, then open up your scene from the scenes folder and test, you might have to reset some arguments in the inspector but it should warn you**)

    or even just try Assets > Reimport All. ( I would still back your project up tho!)

    just out of curiosity to try and see if this is an issue with just this project or not.
    can you create a new project and add a couple of UI elements into a scene, like an image and a text component. check that the scripts are there on the components.
    close and reopen that project and see if the UI elements still have the proper scripts attached.

    so were basically recreating what you are seeing, but with a new clean project. this should tell us if its a Unity or a project issue were facing.

    just as another bit of info for the future, if your getting the The referenced script on this Behaviour is missing! error in future and you cannot find out which component is missing a script have a look at this.
    http://www.theantranch.com/forum/viewtopic.php?f=17&t=11632
     
  4. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    Looking at the error in Red at the bottom, gives you an indication as to what problems you have. if you click on the console tab it will show all your errors and warnings. if you click on the console tab it may elaborate the error. it may say something like ')' expected or suchlike to give a better indication.

    I cant see quite clearly what that error is, but it appears that you have a Parsing error within your BoardManager script at approximately line 100.

    I would start by looking around that point, and see, just in case you are missing/have an extra bracket or such like.

    its always better if you need people to have a look at your code, if you could paste it into a post, but please do remember to use the 'Code Tags' in the post formatting bar , as it makes it a whole lot easier to check line numberings etc.. :)
     
  5. palermo500

    palermo500

    Joined:
    May 10, 2015
    Posts:
    2
    Hey, so I'm in part 2 of the tutorial and I got this message

    Assets/Scripts/PlayerHealth.cs(4,14): error CS0101: The namespace `global::' already contains a definition for `PlayerHealth'

    I haven't named anything PlayerHealth, so I'm not sure what happened. Could anyone tell me how to fix this?
     
  6. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    @palermo500 @WoodyPal

    Evening, I think that you both might be getting roughly the same prob.

    when you get this error The namespace `global::' already contains a definition for XXXXXX

    it tends to mean that you have declared something twice.

    in your case woodypal you, somewhere have declared 'Moving Object' class twice, ie have two MovingObject scripts within your project somewhere.
    and Palermo500, the same, you have two scripts/classes called PlayerHealth.

    if you downloaded the source from the asset store, you will have a 'completed' folder, and just off the root of the project you may have another folder for your scripts. have a quick look to see if you have two scripts in separate folders somewhere.

    if you want to keep the 'completed' folder for future reference, I would suggest creating a new folder under Assets in your project and name this folder 'WebPlayerTemplates' (with that spelling and case) then drag your completed folder into that.

    as this WebPlayerTemplates folder and its contents are generally ignored by the compiler in the editor. so fingers crossed your error should go away :)
     
  7. BusyRobot

    BusyRobot

    Joined:
    Feb 22, 2013
    Posts:
    148
    Can someone give me some advice as to what's the best way to add a main menu to this project? I need to add one to my game (which is based upon this tutorial) and some other tutorials say you should create a separate scene and then load the new game scene in when needed (so that would load the tutorial scene?) other tutorials say do everything within one scene, I'm new to Unity so I'm not sure which is the best way to go. Should I keep everything in the main tutorial scene, and just put a main menu game object to appear created from the loader? which then instantiates the GameManager? or should that actually go in the GameManager?
     
  8. wopolusa

    wopolusa

    Joined:
    Feb 21, 2015
    Posts:
    2
    Done and dusted, as I'm about to attempt a rather large 2D project (at least large for a wee single developer like me who only started using unity this year) this was super helpful for learning some of the more advanced practices and techniques while only taking a few hours to get the hang of on this somewhat functionally simple game.

    All the unity tutorials have been fantastic, helpful and you guys always assisting others in the forums and comments are legends. I really get the sense from the guys at unity that every day isn't just another day at work, it's something you are passionate about and enjoy. It shows.

    Cheers
     
    Matthew-Schell and OboShape like this.
  9. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
  10. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    The problem with this is that if you want to use the same code to check for an item before moving it will need to block collision initially. What you could do maybe is for the first turn the item spawns set it's collider to not be a trigger, and then set isTrigger to true in the next turn. That way you could check for it using the same collision code and then pick it up using our pickup code.
     
    Last edited: May 11, 2015
  11. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238

    That warning shouldn't be an issue, are you testing a build or using Unity Remote?
     
  12. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238

    @Maraku Mure Can you do me a favor and update to the latest version of Unity? That looks to me like a bug in the UI system or something else going wrong. I've never seen those exact errors and the problem appears to be in the scripts for the UI elements, not the tutorial content. Latest patch releases are here: https://unity3d.com/unity/qa/patch-releases
     
  13. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    @RetroGamer28 That error message is telling you you have a typo on line 100 of BoardManager. It looks as if you are missing two closing braces that look like this: } at the end of your script. In the future please post code using the code formatting tools for the forum (trying to read from images is hard).
     
  14. Maraku Mure

    Maraku Mure

    Joined:
    May 2, 2015
    Posts:
    28
    Sure thing man, I'm downloading the patch.
    Cooool I can help Unity Technologies *_* and one day I'll be part of it..... :D

    After the patch I will check it :D
     
  15. pvqr

    pvqr

    Joined:
    Apr 27, 2015
    Posts:
    38
    Ok thanks for the answer, I'll try that.
     
  16. Hedeag

    Hedeag

    Joined:
    Feb 10, 2015
    Posts:
    29
    1. How to make data saves such as the number of food and the number of days and their load?

    2. How to make the change generation levels(other prefabs or sprites), so that there are 5 levels with one generation and the other 5 with another?
     
  17. Maraku Mure

    Maraku Mure

    Joined:
    May 2, 2015
    Posts:
    28
    Dude may God bless you :D

    It works!!!! :DDDDD
    You can't imagine how much I'm happy!!!
    Finally I can finish this tutorial :D
     
    OboShape likes this.
  18. Hedeag

    Hedeag

    Joined:
    Feb 10, 2015
    Posts:
    29
    I've got one more question. I have done the Menu in a separate scene, but when i select a NewGame the game starts with Day2. As far as I understand this happens because there is <Awake> in <Loader.cs>
    And thus the game takes switching the MenuScene for changing the day. I've tried to change <Awake> to <Start> in <Loader.cs>, in this case the game starts from Day1 but the hero doesn't move, as far as I understand this happens because <GameManager.cs> also begins with <Start>. Thus the sequence of scripts is lost. Awake>Start

    How can I solve this problem?
     
  19. pvqr

    pvqr

    Joined:
    Apr 27, 2015
    Posts:
    38
    I'm having the same problem.. the way DontDestroyOnLoad() works is not clear to me, but it seems that it runs before Awake() function. Also, it probably going to day 2 because of this.

    private void OnLevelWasLoaded(int index){
    level++;
    InitGame();
    }
     
  20. ManOfSteele

    ManOfSteele

    Joined:
    May 13, 2015
    Posts:
    2
    Hello, all I just finished part 11 of the 2D Roguelike tutorial. I am enjoying the tutorial a lot. I seem to be having an issue at this point. When I step on the exit sign in play mode something strange is happening, I get a black background with only the player in it. If I take a step I get a MissingReferenceException in regards to a transform.

    I was wondering if it has something to do with my scripts? I followed along with the tutorials but I am only human so it is possible I made some kind of mistake.

    Here is my Player Script:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Player : MovingObject
    5. {
    6.     public int wallDamage = 1;
    7.     public int pointsPerFood = 10;
    8.     public int pointsPerSoda = 20;
    9.     public float restartLevelDelay = 1f;
    10.  
    11.     private Animator animator;
    12.     private int food;
    13.  
    14.     protected override void Start()
    15.     {
    16.         animator = GetComponent<Animator>();
    17.         food = GameManager.instance.playerFoodPoints;
    18.         base.Start();
    19.     }
    20.  
    21.     private void OnDisable()
    22.     {
    23.         GameManager.instance.playerFoodPoints = food;
    24.     }
    25.  
    26.     void Update()
    27.     {
    28.         if (!GameManager.instance.playersTurn)
    29.             return;
    30.  
    31.         int horizontal = 0;
    32.         int vertical = 0;
    33.  
    34.         horizontal = (int)Input.GetAxisRaw("Horizontal");
    35.         vertical = (int)Input.GetAxisRaw("Vertical");
    36.  
    37.         if (horizontal != 0)
    38.             vertical = 0;
    39.  
    40.         if (horizontal != 0 || vertical != 0)
    41.             AttemptMove<Wall>(horizontal, vertical);
    42.     }
    43.  
    44.     protected override void AttemptMove<T>(int xDir, int yDir)
    45.     {
    46.         food--;
    47.         base.AttemptMove<T>(xDir, yDir);
    48.         RaycastHit2D hit;
    49.         CheckIfGameOver();
    50.         GameManager.instance.playersTurn = false;
    51.     }
    52.  
    53.     private void OnTriggerEnter2D(Collider2D other)
    54.     {
    55.         if (other.tag == "Exit")
    56.         {
    57.             Invoke("Restart", restartLevelDelay);
    58.             enabled = false;
    59.         }
    60.         else if (other.tag == "Food")
    61.         {
    62.             food += pointsPerFood;
    63.             other.gameObject.SetActive(false);
    64.         }
    65.         else if (other.tag == "Soda")
    66.         {
    67.             food += pointsPerSoda;
    68.             other.gameObject.SetActive(false);
    69.         }
    70.     }
    71.  
    72.     protected override void OnCantMove<T>(T component)
    73.     {
    74.         Wall hitWall = component as Wall;
    75.         hitWall.DamageWall(wallDamage);
    76.         animator.SetTrigger("PlayerChop");
    77.     }
    78.  
    79.     private void Restart()
    80.     {
    81.         Application.LoadLevel(Application.loadedLevel);
    82.     }
    83.  
    84.     public void LoseFood(int loss)
    85.     {
    86.         animator.SetTrigger("PlayerHit");
    87.         food -= loss;
    88.         CheckIfGameOver();
    89.     }
    90.  
    91.     private void CheckIfGameOver()
    92.     {
    93.         if (food <= 0)
    94.         {
    95.             GameManager.instance.GameOver();
    96.         }
    97.     }
    98. }
    Sorry for the long post, just wanted to provide info that may be required to help me figure this out. Thanks
     
  21. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    hey @Hedeag for saving data take a look at PlayerPrefs here: http://docs.unity3d.com/ScriptReference/PlayerPrefs.html

    To change the sprites you could do it a few ways but I'd probably make a separate set of prefabs by copying and modifying the existing ones. Then I'd add some logic in the BoardManager to check what level or set of levels you're in and instantiate those prefabs instead of the originals.

    as @Pirizao writes, every time a new scene is loaded the OnLevelWasLoaded function of GameManager is called which adds 1 to the level number. There are a few ways you could address this but you could do something checking the index parameter of that function to see if you're in the menu and then skipping over that line where you add to the level number.

    DontDestroyOnLoad causes the game object that the script is attached to not be deleted when a new scene is loaded. In this case it means that the GameManager isn't destroyed when the scene is reloaded. Another way to address the problem you're having generally is to not instantiate the GameManager until you get into your first game scene. Make sure your menu scene does not have the loader on the main camera or anything that depends on the GM, then it will be instantiated when you load the main scene for the first time.
     
  22. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    Can you give some more specifics on the error you're getting? It sounds like something is happening that is causing the board to fail to be generated after the level is reloaded. When you enter the exit square it reloads the scene which deletes everything, then generates a new level. If you're getting a black scene with the player it sounds as if the scene is reloading as it should but then something is wrong or missing which is causing it to fail to generate the new level.
     
  23. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    Hooray! Glad you're back on track :)
     
  24. Hedeag

    Hedeag

    Joined:
    Feb 10, 2015
    Posts:
    29
    Thanks for the advice, but I still can't make a start with day1.Could you write a full and detailed solution to this problem point by point?
     
  25. daithi43

    daithi43

    Joined:
    Apr 2, 2015
    Posts:
    3
    I had a similar issue to you, so I created a new bool at the top of my GameManager script called "restarting" and initialising it as true. I then checked for this flag in both the Awake and OnLevelWasLoaded functions. Not sure if this is a hacky solution but it works and doesn't require any major changes to the code.
    Code (CSharp):
    1. private bool restarting = true;
    2.    
    3.     void Awake ()
    4.     {
    5.         if (instance == null)
    6.             instance = this;
    7.         else if (instance != this)
    8.             Destroy (gameObject);
    9.  
    10.         DontDestroyOnLoad (gameObject);
    11.         enemies = new List<Enemy>();
    12.         boardScript = GetComponent<BoardManager> ();
    13.         //Check if restarting the game
    14.         if (restarting == false) {
    15.         InitGame ();
    16.         }
    17.     }
    18.  
    19.     void OnLevelWasLoaded(int index)
    20.     {
    21.         if (restarting == false) {
    22.             //If we are simply moving onto the next level within the game
    23.             level++;
    24.         } else
    25.             //If we are restarting the game, we dont want to increment level
    26.             restarting = false;
    27.  
    28.         InitGame ();
    29.     }
    30.  
     
    Aldrik2 likes this.
  26. ManOfSteele

    ManOfSteele

    Joined:
    May 13, 2015
    Posts:
    2
    I am no longer having this problem. I think at that point (the end of part 11) it is supposed to happen. I noticed that towards the end of the video he did not test the level transition. That made me consider the possibility that it was behaving as it should. So I then looked at the next part of the tutorial: Adding UI & Level Transitions. In that section he modified the scripts in a way that fixed my perceived problem, which wasn't actually a problem at all. I am now about to start part 13 and everything is working properly. I apologize for not using my common sense sooner, lol. I do appreciate the timely response though. I won't forget that.
     
  27. pvqr

    pvqr

    Joined:
    Apr 27, 2015
    Posts:
    38
    I just managed to do it.
    First you look at Daithi43's code, make a variable to keep track if you are restarting or not.
    I made it a public static variable, so I can acess that boolean from another's scene object (which will be your menu scene).
    When you are at the menu, when you press the play button you need to do 3 things:
    -set the restarting variable to true
    -destroy the game manager
    -load the game scene.

    On the game manager code you need to reset some variables when restarting is true, so reset the level to zero or one, reset the player score, reset his inventory, etc.

    That's about it, if you really don't understand this I can try to explain a little bit better. I'm kinda in a hurry right now so.
    Good luck
     
  28. Hedeag

    Hedeag

    Joined:
    Feb 10, 2015
    Posts:
    29
    daithi43 thanx a lot, it works for me
    Pirizao thanx a lot, too.

    And now who could help with these: :)
    1. How to make data saves such as the number of food and the number of days and their load?

    2. How to make the change generation levels(other prefabs or sprites), so that there are 5 levels with one generation and the other 5 with another?

     
  29. awillshire

    awillshire

    Joined:
    Apr 29, 2014
    Posts:
    20
    Silly question - player start position

    Hi All,
    I'm trying to move the player start position, but for the life of me I can't find where to change it! I've finished the tutorial, and been skimming over the videos but I've not located how to do it.

    Thanks!
    Andrew.
     
  30. daithi43

    daithi43

    Joined:
    Apr 2, 2015
    Posts:
    3
    In the inspector in the editor the players transform sets the position i.e. change it from (0, 0, 0) to (1, 1, 0) to start the player 1 tile right and 1 tile up from the bottom left corner
     
  31. pvqr

    pvqr

    Joined:
    Apr 27, 2015
    Posts:
    38
    I won't give you code, I'll just try to point a way of doing it yourself.

    1. Do you mean serializable content? Like save/load after the program is closed? If so, I'm sorry but I can't help much on this matter, but there are a lot of tutorials on the subject that you can watch and learn.

    2. First of all, import all your asset and make them prefabs. Now all you got to do is mess with the BoardManager class.
    I don't know if this is the most efficient way of doing it, but it's a way.
    Do you remember the lists of gameobjects used to set the board? Make another list containing the new assets you imported.
    Now search for the part where the level gets generated, where you are interacting through lists and picking a random index, before that, you gonna to need to check whenever you want them to change:
    if (level >= 5) changeToNewLists();
    if (level < 5) keepTheOldOnes();

    I think it's that simple.
     
  32. awillshire

    awillshire

    Joined:
    Apr 29, 2014
    Posts:
    20
    Thanks so much Daithi! I think I had a total brain freeze!
    All the best,
    Andrew.
     
  33. Drumclem

    Drumclem

    Joined:
    May 7, 2015
    Posts:
    4
    Hello there,

    Really sorry to be bothering you with an issue that has already been mentioned, but for the life of me I CAN'T FIND THE SOLUTION (caps over, I promise).

    I can only move my player once, in any direction, and once I do that, my box collider 2D is deactivated. Also, enemies don't move.

    I suspect it has to do with Update() not running properly, but I've run through my script lots of times, and can't find out what's wrong. I have no compiling errors whatsoever.

    Any help appreciated, thanks in advance everyone.

    Here's my player script:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Player : MovingObject {
    5.  
    6.     public int wallDamage = 1;
    7.     public int pointsPerFood = 10;
    8.     public int pointsPerSoda = 20;
    9.     public float restartLevelDelay = 1f;
    10.  
    11.     private Animator animator;
    12.     private int food;
    13.  
    14.  
    15.     // Use this for initialization
    16.     protected override void Start () {
    17.         animator = GetComponent<Animator> ();
    18.         food = GameManager.instance.playerFoodPoints;
    19.         base.Start ();
    20.     }
    21.  
    22.     private void OnDisable()
    23.     {
    24.         GameManager.instance.playerFoodPoints = food;
    25.     }
    26.  
    27.     // Update is called once per frame
    28.     void Update () {
    29.         if (!GameManager.instance.playersTurn) return;
    30.  
    31.         int horizontal = 0;
    32.         int vertical = 0;
    33.  
    34.         horizontal = (int)Input.GetAxisRaw ("Horizontal");
    35.         vertical = (int)Input.GetAxisRaw ("Vertical");
    36.         if (horizontal != 0) {
    37.  
    38.             vertical = 0;
    39.         }
    40.  
    41.         if (horizontal != 0 || vertical != 0) {
    42.             AttemptMove<Wall> (horizontal, vertical);
    43.         }
    44.     }
    45.  
    46.     protected override void AttemptMove <T> (int xDir, int yDir)
    47.     {
    48.         food--;
    49.         base.AttemptMove <T> (xDir, yDir);
    50.         RaycastHit2D hit;
    51.         CheckIfGameOver ();
    52.         GameManager.instance.playersTurn = false;
    53.     }
    54.  
    55.     private void OnTriggerEnter2D (Collider2D other)
    56.     {
    57.         if (other.tag == "Exit") {
    58.             Invoke ("Restart", restartLevelDelay);
    59.             enabled = false;
    60.         } else if (other.tag == "Food") {
    61.             food += pointsPerFood;
    62.             other.gameObject.SetActive (false);
    63.         } else if (other.tag == "Soda") {
    64.             food += pointsPerSoda;
    65.             other.gameObject.SetActive (false);
    66.  
    67.         }
    68.     }
    69.  
    70.     protected override void OnCantMove <T> (T component)
    71.     {
    72.         Wall hitWall = component as Wall;
    73.         hitWall.DamageWall (wallDamage);
    74.         animator.SetTrigger ("playerChop");
    75.     }
    76.  
    77.     private void Restart ()
    78.     {
    79.         Application.LoadLevel (Application.loadedLevel);
    80.     }
    81.  
    82.     public void LoseFood (int loss)
    83.     {
    84.         animator.SetTrigger ("playerHit");
    85.         food -= loss;
    86.         CheckIfGameOver ();
    87.     }
    88.  
    89.  
    90.  
    91.     private void CheckIfGameOver()
    92.     {
    93.         if (food <= 0)
    94.             GameManager.instance.GameOver ();
    95.     }
    96. }
    And my GameManager script :
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. public class GameManager : MonoBehaviour {
    6.  
    7.     public float turnDelay = .1f;
    8.     public static GameManager instance = null;
    9.     public BoardManager boardScript;
    10.     public int playerFoodPoints = 100;
    11.     [HideInInspector] public bool playersTurn = true;
    12.  
    13.     private int level = 3;
    14.     private List<Enemy> enemies;
    15.     private bool enemiesMoving;
    16.  
    17.     void Awake () {
    18.         if (instance == null)
    19.             instance = this;
    20.         else if (instance != this)
    21.             Destroy(gameObject);
    22.  
    23.         DontDestroyOnLoad(gameObject);
    24.         enemies = new List<Enemy> ();
    25.         boardScript = GetComponent<BoardManager>();
    26.         InitGame ();
    27.     }
    28.  
    29.     void InitGame()
    30.     {
    31.         enemies.Clear ();
    32.         boardScript.SetupScene (level);
    33.     }
    34.  
    35.     public void GameOver()
    36.     {
    37.         enabled = false;
    38.     }
    39.    
    40.     // Update is called once per frame
    41.     void Update () {
    42.     if (playersTurn || enemiesMoving)
    43.             return;
    44.  
    45.         StartCoroutine(MoveEnemies ());
    46.     }
    47.  
    48.     public void AddEnemiesToList(Enemy script)
    49.     {
    50.         enemies.Add (script);
    51.     }
    52.  
    53.     IEnumerator MoveEnemies()
    54.     {
    55.         enemiesMoving = true;
    56.         yield return new WaitForSeconds (turnDelay);
    57.         if (enemies.Count == 0) {
    58.             yield return new WaitForSeconds (turnDelay);
    59.         }
    60.  
    61.         for (int i = 0; i < enemies.Count; i++) {
    62.             enemies [i].moveEnemy ();
    63.             yield return new WaitForSeconds (enemies [i].moveTime);
    64.         }
    65.  
    66.         playersTurn = true;
    67.         enemiesMoving = false;
    68.  
    69.     }
    70. }
    71.  
     
  34. awillshire

    awillshire

    Joined:
    Apr 29, 2014
    Posts:
    20
    Hi Clem

    A quick check you might want to try is to just compare your source code to the completed example source code. An online checker can be easy - just paste each file into the site. One example is http://www.diffnow.com.

    Good luck!
    Andrew
     
  35. Hedeag

    Hedeag

    Joined:
    Feb 10, 2015
    Posts:
    29
    Drumclem Try update ur MonoDev
    press in MonoDev Tools>Options>Syntax Highlights>Monokai
     
  36. halbard100

    halbard100

    Joined:
    Feb 17, 2015
    Posts:
    3
    I had a similar issue as well; however, I'm simply following the tutorial and not making my own changes. I'm getting a "NullReferenceException: Object reference not set to an instance of an object" error for the GameManager. I changed the GameManager from the one I was writing during pt5, to the script in the Completed folder and was met with a similar error, except it was on line 75 with "levelText = GameObject.Find("LevelText").GetComponent<Text>();" I switched back to my code and didn't change anything, but after pressing play some number of times, it suddenly started to generate the board. Not sure why, but it works now.
     
  37. Drumclem

    Drumclem

    Joined:
    May 7, 2015
    Posts:
    4
    Thanks for the tool awillshire! I tried it and apart from what will be written in later tutorials, my script is rigorously identical to the completed one. I really don't understand.

    Hedeag, I did try this, but it only changes the skin of MonoDevelop. Did I miss something?
     
  38. pvqr

    pvqr

    Joined:
    Apr 27, 2015
    Posts:
    38
    Can you post your moving object script here? Maybe we find something there.
     
  39. Caidran

    Caidran

    Joined:
    May 20, 2015
    Posts:
    2
    Hello,

    First of all - great tutorial! I'm new to C# (some experience in bash, python, so not completely lacking in programming experience) but even I was able to follow (almost) all of it without a great deal of trouble. I have a few questions though that I was hoping someone may know the answer to - or could point me in the right direction;

    1) I'd like to explore the possibility of removing the left/right columns/outer walls and generating terrain as the player moves in those directions as the player moves. I'm attempting to create new content in a procedural manner to allow the game to continue (possibly endlessly) however I'm not having much luck and I'm not entirely sure it'll be possible to do so using the tutorial as sort of a template - any ideas? (Not asking for anyone to write a full fledged procedural generation script for me, just interested as to wether or not it is possible via this tutorial as a template and how it could be achieved! )

    I did have more than one question, but the second one was how can I get the camera to follow my player which I have managed to figure out, so just the one question from me right now! :)

    Thanks
     
  40. Drumclem

    Drumclem

    Joined:
    May 7, 2015
    Posts:
    4
    Here it is. There was a difference: I had forgotten to put boxCollider back on after linecast. Still, can't move my character more than once. Thanks for the help!

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public abstract class MovingObject : MonoBehaviour {
    5.  
    6.     public float moveTime = 0.1f;
    7.     public LayerMask blockingLayer;
    8.  
    9.     private BoxCollider2D boxCollider;
    10.     private Rigidbody2D rb2D;
    11.     private float inverseMoveTime;
    12.  
    13.  
    14.     // Use this for initialization
    15.     protected virtual void Start () {
    16.         boxCollider = GetComponent<BoxCollider2D> ();
    17.         rb2D = GetComponent<Rigidbody2D> ();
    18.         inverseMoveTime = 1f / moveTime;
    19.     }
    20.  
    21.     protected bool Move (int xDir, int yDir, out RaycastHit2D hit) //out => arguments passed out by reference
    22.     {
    23.         Vector2 start = transform.position; //implicit conversion, discarding z axis
    24.         Vector2 end = start + new Vector2 (xDir, yDir);
    25.  
    26.         boxCollider.enabled = false;
    27.  
    28.         hit = Physics2D.Linecast (start, end, blockingLayer);
    29.  
    30.         boxCollider.enabled = true;
    31.  
    32.         if (hit.transform == null)
    33.         {
    34.             StartCoroutine(SmoothMovement (end));
    35.             return true;
    36.         }
    37.  
    38.         return false;
    39.     }
    40.  
    41.     protected IEnumerator SmoothMovement (Vector3 end)
    42.     {
    43.         float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
    44.  
    45.         while (sqrRemainingDistance > float.Epsilon)
    46.         {
    47.             Vector3 newPosition = Vector3.MoveTowards (rb2D.position, end, inverseMoveTime * Time.deltaTime);
    48.             rb2D.MovePosition (newPosition);
    49.             sqrRemainingDistance = (transform.position - end).sqrMagnitude;
    50.             yield return null; //Wait one frame before checking again
    51.         }
    52.     }
    53.  
    54.     protected virtual void AttemptMove <T> (int xDir, int yDir)
    55.         where T : Component
    56.     {
    57.         RaycastHit2D hit;
    58.         bool canMove = Move (xDir, yDir, out hit);
    59.  
    60.         if (hit.transform == null)
    61.             return;
    62.  
    63.         T hitComponent = hit.transform.GetComponent<T>();
    64.  
    65.         if (!canMove && hitComponent != null)
    66.             OnCantMove(hitComponent);
    67.  
    68.     }
    69.  
    70.     protected abstract void OnCantMove <T> (T component) //abstract function => no opening or closing brackets
    71.         where T: Component;
    72.  
    73. }
    74.  
     
  41. Drumclem

    Drumclem

    Joined:
    May 7, 2015
    Posts:
    4
    Ok strike that, sorry everyone, my code was just fine. I had just forgotten to... set my Player's tag to "Player"... hence many things didn't work. There a couple of things not working still, but I'll work it out by myself. Thank you !
     
  42. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    hey @Hedeag if you don't want to use the PlayerPrefs direction I suggested earlier you could also take a look at this: https://unity3d.com/learn/tutorials...ining-archive/persistence-data-saving-loading

    The solution that @daithi43 posted looks fine to me, have your setup and generation code check if you're changing levels or restarting the whole game and act accordingly. But part of the point of these projects is to give you somewhere to start and then you go and figure out your own solutions if you want to extend it. If you're having a problem with replicating something I've done in the tutorial I'm happy to help but it's not up to me to help you come up with your own game, that's your job (and part of the fun!) That said I think @Pirizao is pointing you in the right direction with his suggestions.

    @ManOfSteele yes that is something I got a few notes on, people testing at moments where we're going from one video to another and it seems like stuff should be working but doesn't. Basically if I don't say 'And now test it' in the video don't assume it's going to work at that point. There's a bunch of interdependent stuff going on that can cause things to not work until other things are finished.

    @Caidran this isn't really set up to do marching, infinite levels, it's pretty much setup to have discrete play / setup phases. However, with some tweaking I could imagine that you could set things up to check if the player is about to bring a new, empty area of the level into view and try to generate more of it while the enemies are moving. The thing I'd worry about is stutters or lag as it runs the instantiation to generate the new tiles. A quick google revealed this, which includes some JS code, not verified whether it's good but maybe take a look:
     
  43. Chessbow

    Chessbow

    Joined:
    May 22, 2015
    Posts:
    1
    I think there's something wrong between my GameManager and my Player class (inherits MovingObject Class) , because when i play the scene nothing moves.. also, while running it says:
    and when i tried to move the player it says: NullReferenceException: Object reference not set to an instance of an object, and points to the MovingObject and Player Scripts, at the GameManager.instance.variable;

    i tried to input manually the variables wich print out a "NullReferenceException". by making this I only can make one move, the enemies also move and in then it says :

    But in this case with the manual input, it allows the player to keep moving while editing the player turn from the gameManager of the scene, but enemies cant move. i hope you can help me.
     
    Last edited: May 22, 2015
  44. Optimussackers

    Optimussackers

    Joined:
    May 22, 2015
    Posts:
    1
    Hey Im pretty new to coding and thought id try this out to learn and have a bit of fun, Ive followed all of the videos and written the scripts exactly as they were shown in the videos (I think) but keep getting this error message;


    NullReferenceException: object reference not set to an instance of an object Player.Update() (at Assets/scripts/player .cs :51)

    I can't see what the error is for, here is this section of the code;


    Screenshot 2015-05-22 00.59.44.png Screenshot 2015-05-22 01.06.48.png



    Id appreciate any help, even if its my own stupidity getting the best of me.
     
  45. j03d4d

    j03d4d

    Joined:
    Oct 4, 2013
    Posts:
    21
    Matt,

    Thanks for the tutorial. Very informative. Can you please help me? I am on part 109: Writting the player controller.

    This is the error I'm getting in the player.cs script: "Assets/Scripts/Player.cs(7,31): error CS0246: The type or namespace name `MovingObject' could not be found. Are you missing a using directive or an assembly reference?"

    This is my script:

    using UnityEngine;
    using System.Collections;

    public class Player : MovingObjects
    {

    public int wallDamage = 1; //How much damage you do
    public int pointsPerFood = 10; //How much food heals you
    public int pointsPerSoda = 20; //How much soda heals you
    public float restartLevelDelay = 1f;


    private Animator animator;
    private int food; //How much food he has(health)


    // Use this for initialization
    protected override void Start ()
    {
    animator = GetComponent<Animator>();

    food = GameManager.instance.playerFoodPoints; //Set the variable food we created equal to playerFoodPoints in the game manager

    base.Start ();
    }

    private void OnDisable()
    {
    GameManager.instance.playerFoodPoints = food; //Stores players food for when you change levels
    }

    // Update is called once per frame
    void Update ()
    {
    if (!GameManager.instance.playersTurn) return; //If it's not the players turn then the next line of code will NOT be executed


    int horizontal = 0;
    int veritical = 0;

    horizontal = (int) Input.GetAxisRaw("Horizontal");
    vertical = (int) Input.GetAxisRaw("Vertical");

    if (horizontal !=0) //Check if moving horizontal
    veritcal = 0; //If so then don't move vertical


    if (horizontal !=0 || veritical !=0) //if moving in either direction
    AttemptMove<Wall> (horizontal, veritical); //<Wall> is to check if there is a wall relates to <T> in the wall script

    }
    // <T> = Type of component we are expecting to encounter
    protected override void AttemptMove <T> (int xDir, int yDir)
    {
    food--;

    base.AttemptMove <T> (xDir, yDir);

    RaycastHit2D hit;

    CheckIfGameOver(); //Because player has lost food we check if food is <= 0

    GameManager.instance.playersTurn = false; //End players turn
    }

    private void OnTriggerEnter2D (Collider2D other) //We set exit, food, soda to is trigger (check tag of object collided with)
    {
    if (other.tag == "Exit")
    {
    Invoke ("Restart", restartLevelDelay);
    enabled = false;
    }
    else if (other.tag == "Food")
    {
    food += pointsPerFood; //Heal
    other.gameObject.SetActive(false); //Deletes food object
    }
    else if (other.tag == "Soda")
    {
    food += pointsPerSoda; //heal
    other.gameObject.SetActive(false); //deletes soda object
    }
    }

    protected override void OnCantMove <T> (T component) //<T> checks if your hitting something (T component) checks what your hitting (wall or enemy)
    {
    Wall hitWall = component as Wall; //Create variable called hitWall of the type Wall and set it to equal the component passed in as a parameter while casting it to a wall
    hitWall.DamageWall(wallDamage); //Call the damage wall function of the wall that we hit (Pass in wallDamage) which is how much damage the player will do
    animator.SetTrigger("playerChop"); //play player chop animation
    }

    private void Restart ()
    {
    Application.LoadLevel(Application.loadedLevel); //Load last scene which is Main (the only scene in the game)
    }

    public void LoseFood (int loss) //player loses food when hit
    {
    animator.SetTrigger("playerHit"); //play player hit animation
    food -= loss; //how much damage taken
    CheckIfGameOver(); //CHeck if food <=0
    }

    private void CheckIfGameOver()
    {
    if (food <=0)
    GameManager.instance.GameOver(); //Calls game over function on the GameManager script
    }
    }

    Can you see what I'm doing wrong?
     
  46. pvqr

    pvqr

    Joined:
    Apr 27, 2015
    Posts:
    38
    For @Chessbow and @Optimussackers
    Regarding this error: NullReferenceException: Object reference not set to an instance of an object
    Do a double check on your scripts and see if every GameObject variable you created has the proper object attached to it, you just probably forgot to drag the prefab to it or to initialize it on the Start()/Awake() method.

    About the ArgumentOutOfRangeException: Argument is out of range, it's probably caused by your list of enemies, are you intiating and clearing the list everytime you load a level? If so, in your GameManager script, look for the method that handles the enemie's turn and see if there's something wrong there.

    @j03d4d

    "Assets/Scripts/Player.cs(7,31): error CS0246: The type or namespace name `MovingObject' could not be found.
    public class Player : MovingObjects

    Maybe it's just a typo, check for the 's' on both scripts.
     
  47. Hedeag

    Hedeag

    Joined:
    Feb 10, 2015
    Posts:
    29
    Why I don't want? I want to use PP very much but I haven't understood how yet.

    Well let's look at Save / Load at least.
    Firstly, I saw a bunch of lessons and they weren't very helpful.
    I tried using PlayerPrefs.

    I am able to save data, Food, Days.
    But when loading my character and the enemies do not move.

    I write in GameManager.cs in the function void OnLevelWasLoaded
    PlayerPrefs.SetInt("Days", level);


    And when dying in the function public void GameOver()
    level=PlayerPrefs.GetInt("Days");


    But when loading I get +1 level, I mean I get saved at the 8th level, the 8th level is recorded in the data, but it loads the 9th level and the character doesn't move.
     
  48. MrToad

    MrToad

    Joined:
    May 22, 2015
    Posts:
    2
    I'd like FoodTiles not to appear if there is 3 or more adjacent WallTiles.
    How can I do this ?
     
  49. j03d4d

    j03d4d

    Joined:
    Oct 4, 2013
    Posts:
    21
    @Pirizao
    ***EDIT: Nevermind I think I figured it out. I deleted the 's' and the end of MovingObjects in both scripts and the error went away.

    I'm confused

    The code in my Player.cs script is :
    public class Player : MovingObjects
    {

    and my code in my MovingObjects script is:
    public abstract class MovingObjects : MonoBehaviour
    {

    They both have an 's' at the end of MovingObject if that's what your talking about . . .

    I'm new to Unity - Can someone please help me figure this out? I'm sick of getting stuck on every tutorial over one stupid error I can't figure out -.-
     
    Last edited: May 23, 2015
  50. j03d4d

    j03d4d

    Joined:
    Oct 4, 2013
    Posts:
    21
    Matthew Schell

    Again great tutorial I learned a lot but can I give you some advice for your net tutorial?

    Next time can you copy and paste the EXACT script you had us write from the video in the scripts section other than pasting the one from the 'completed' folder? This made it REALLY confusing and hard to bug test coming from a very new Unity user. As a beginner if Unity gives me an error on line 88 I need to be able to look at line 88 of your code and it needs to be the exact same as my line 88 if I followed your instructions exact. That way I can spot typos ect.

    Thanks again!
     
Thread Status:
Not open for further replies.