Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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

    DarthStevenus

    Joined:
    Jul 19, 2015
    Posts:
    2
    Okay I've looked at my project over and over again and I still don't know what's up. I don't think it's my scripts and I'm not getting any error messages aside from a warning about a script in the completed folder that I'm not even using, so I'm just going to post my project here and hope that someone more experienced in Unity than me will take a look at it and be able to figure it out.

    http://www.filedropper.com/2droguelike
     
  2. grappler

    grappler

    Joined:
    Jun 26, 2015
    Posts:
    13
    Thanks for the reply. I understand--just not used to overriding code in an editor like that. This tutorial is a simple example, but I can imagine that getting things out of sync could lead to some confusion in a more sophisticated game.
     
  3. MurDoK722

    MurDoK722

    Joined:
    Jun 9, 2015
    Posts:
    15
    This game will not work with me.... I have tried everything and it is still giving me a rough time. I think I am going to have to delete and start over for the 2nd time!
     
  4. Adam.Kubik

    Adam.Kubik

    Joined:
    Jul 19, 2015
    Posts:
    1
    Hi folks, I'm new to the Unity and I've been doing some tutorials, including this one. I'm having some very strange issues in part 12 (adding UI and level transitions). These include (but are not limited to):

    • not being able to move - the player character makes 1 step and that's it, no matter how many times I press the key. I've used the Debug.Log(Input.GetKeyDown) to determine if Unity 'reads' the key. Turns out it does, but the player doesn't move
    • black background - after adding the black screen sometimes it covers the whole map. The only visible elements are the player and the Food count. I've double checked the order of game objects in Hierarchy, used copied GameManager script (the one with namespace Completed), even the one from included Completed directory, but nothing works


    I just want to say that I did not have any issues so far. This applies to this particular tutorial, as well as others (I'm done with Roll-A-Ball, Space Shooter, Survival Shooter, even Cave Generation). Any help would be appreciated.
     
  5. MurDoK722

    MurDoK722

    Joined:
    Jun 9, 2015
    Posts:
    15
    Okay, I am getting a compile error CS1525 unexpected symbol ' private'
    it is in the Player Script. I have looked over the completed code below the vid and have found no errors.
    Can anyone please help, this is my 3rd try at this game.
     

    Attached Files:

  6. MurDoK722

    MurDoK722

    Joined:
    Jun 9, 2015
    Posts:
    15
    Okay Now I am getting several CS0116 errors coming from my Player Script. It says: A namespace can only contain types and namespace declarations.
     
  7. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    hey @MurDoK722 I hate to say it but I really think this tutorial might not be the right one for you right now. The two errors you describe are scripting errors most likely due to typos. You'll need to review the scripts to make sure you haven't omitted a brace or semi-colon somewhere above the point you're getting an error. What both of those mean are that something is wrong with the syntax and the compiler is encountering something where it doesn't think it should be, for example if you left off a closing brace on a function. Sorry I can't be more specific but I wasn't able to identify the error from the picture of your source above. In the future if you want people to look at script with an error please post the error and the entire script, using the code formatting tools in the forum. Please review this thread on how to post code: http://forum.unity3d.com/threads/using-code-tags-properly.143875/
     
  8. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    I'm sorry but I'm not going to be able to look at your project to debug it. However, debugging these kind of issues is a useful exercise for learning, so don't look at it as a waste of time yourself. Once you go through the pain of solving it it will be indelibly burned into your brain and you (hopefully) won't make that mistake again. As much as we wouldn't like it to be this is a big and important part of making games: fixing annoying, hard to find, frustrating bugs. It sucks to do, but feels great when you solve it, and your players will love you for it (or hate you if you don't do it).

    What I can say is that it sounds like you are encountering an infinite loop. Examine the points where for and while loops are being used in the source. One of these is probably entering into a loop but for some reason not being able to exit (by meeting it's conditions for finishing) and therefore causing Unity to become unresponsive.
     
  9. MurDoK722

    MurDoK722

    Joined:
    Jun 9, 2015
    Posts:
    15
    I actually solved my issue, fixed the scripts and everything is running smoothly.
    The only problem I am experiencing is a minor one.
    My player will walk through the walls instead of breaking them? they are set on blocking layer and the sorting layer is items.
     
    Matthew-Schell likes this.
  10. MurDoK722

    MurDoK722

    Joined:
    Jun 9, 2015
    Posts:
    15
    Never mind I found it thanks.
     
    Matthew-Schell likes this.
  11. REC26

    REC26

    Joined:
    Jul 22, 2015
    Posts:
    1
    I have a weird issue, I'm at the part where you are supposed to split the sprites in the Sprite Editor and after that select (with Command) sprites and drag them to the Hierarchy list in order to create an animation. In the tutorial, after dropping the sprites in the Hierarchy list it appears a window where you can save the animation. I get no window asking for this.

    Is this something that's been updated in the latest version (which I'm running) or am I missing something?
     
  12. djchallis

    djchallis

    Joined:
    May 20, 2015
    Posts:
    3
    Did anybody respond to this? The same thing is happening to me. I'm half way through video 5 when we test the BoardManager for the first time. Every time I run the game it's creating 1 enemy, but in the video it's creating 2 enemies.
    The Mathf.Log line at the bottom of BoardManager is returning 1.584962, which is being cast to an int so it's rounding down to 1 enemy.

    In video four he says that at level 4 you should get two enemies, which is consistent with my tests. My best guess is that he's somehow loading level 4, even though he has level 3 in the script.

    I know this is a very minor issue, but it's confusing. Am I missing something about how Mathf.Log works, or how casting to an int rounds numbers? Or is it just that he's loading a different level and didn't make it clear in the video?

    EDIT: By the end of the video (after setting up the Loader script) he only has one enemy when he tests it, but I'm not sure what would have changed this.
     
    Last edited: Jul 23, 2015
  13. Fragmental

    Fragmental

    Joined:
    Jun 30, 2013
    Posts:
    61
    Hello. I'm trying to find the best way to modify the code from this 2d roguelike so that each item in the level can be loaded sequentially after a button click, instead of being loaded all at once. The level should be kept after closing the program so that a level that is not complete can continue where it left off.

    Any help would be appreciated. Great tutorial btw.
     
  14. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    In all likelihood I messed this up during editing, you're understanding correctly and there should only be one enemy.
     
  15. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    This has changed with a recent update. When you create the sprite it will automatically save the animation and animation controller in the sprites folder. You can rename them there by clicking each twice slowly. I'll add an annotation to the video.
     
  16. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    The area of code you'll want to modify is the BoardSetup() function of BoardManager. You could insert whatever code you want there to wait for input before continuing with the loop. As far as saving and loading levels there are a number of ways to do it, take a look at this live session as a starting point: https://unity3d.com/learn/tutorials...ining-archive/persistence-data-saving-loading
     
  17. Aoernis

    Aoernis

    Joined:
    Jul 24, 2015
    Posts:
    2
    Hello

    I'm at the end of "Unit Mechanics" and I've got a problem.

    When I launch the game, everything should work but i got this error :
    NullReferenceException: Object reference not set to an instance of an object​
    It's because of this line in Player.cs (Start) :
    food = GameManager.instance.playerFoodPoints;​

    I think Player.cs is executed before GameManager.cs and so GameManager is Null in Player.cs. Is that possible ?

    And if i disable the Player script on my Hierarchy, then i launch the game and then i enable the Player script on my Hierarchy. Everything is OK and i can play. (Except I've to enable the player script at the beginning of each level)
     
    Last edited: Jul 25, 2015
  18. djchallis

    djchallis

    Joined:
    May 20, 2015
    Posts:
    3
    Thanks, that's good to know!
     
    Matthew-Schell likes this.
  19. keatonhuff

    keatonhuff

    Joined:
    Jul 25, 2015
    Posts:
    1
    I am on Part 3, video 6. I just finished the first part of the Enemy Animator Controller around 2:10. When I press the play button all that appears is the player bouncing unlike in the video where the entire game shows up, and I get a procession of errors stating:

    NullReferenceException: Object reference not set to an instance of an object
    Player.Update () (at Assets/Scripts/Player.cs:44)

    I also get:

    UnassignedReferenceException: The variable gameManager of Loader has not been assigned.
    You probably need to assign the gameManager variable of the Loader script in the inspector.
    UnityEngine.Object.Instantiate[GameObject] (UnityEngine.GameObject original) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.cs:95)
    Loader.Awake () (at Assets/Scripts/Loader.cs:12)

    All of the code I am using for the Player Script at this point comes from the code lines provided under the video.
     
  20. Aoernis

    Aoernis

    Joined:
    Jul 24, 2015
    Posts:
    2
    Hello again,

    I've solved my problem by using "Edit > Project Setting > Script Execution Order"
    Then add Loader and Player so Loader is now executed before Player and it works.
    But i think there was maybe an other and better solution.
     
    link_108 likes this.
  21. Sssquish

    Sssquish

    Joined:
    Jul 26, 2015
    Posts:
    2
    I'm having a problem in part 5 of the tutorial. The first time he tests the GameManager game object and the board is rendered, nothing comes up for me. I have BoardManager and GameManager attached to the GameManager game object, and I have the camera transform and GameManger transform set to the same values as in the video. I've tried replacing the BoardManager code with the completed script and I got the same issues. No error report, no freeze, the board just doesn't generate. Any help would be greatly appreciated, please find my scripts below.

    Code (CSharp):
    1. using UnityEngine;
    2. using System;
    3. using System.Collections.Generic;
    4. using Random = UnityEngine.Random;
    5.  
    6. public class BoardManager : MonoBehaviour
    7. {
    8.     [Serializable]
    9.     public class Count  
    10.     {
    11.         public int minimum;
    12.         public int maximum;
    13.        
    14.         public Count (int min, int max)
    15.         {
    16.             minimum = min;
    17.             maximum = max;
    18.         }
    19.     }
    20.    
    21.     public int columns = 8;
    22.     public int rows = 8;
    23.     public Count wallCount = new Count (5,9);
    24.     public Count foodCount = new Count (1,5);
    25.     public GameObject exit;
    26.     public GameObject[] floorTiles;
    27.     public GameObject[] wallTiles;
    28.     public GameObject[] foodTiles;
    29.     public GameObject[] enemyTiles;
    30.     public GameObject[] outerWallTiles;
    31.    
    32.     private Transform boardHolder;
    33.     private List <Vector3> gridPositions = new List<Vector3>();
    34.    
    35.     void InitialiseList ()
    36.     {
    37.         gridPositions.Clear ();
    38.        
    39.         for (int x = 1; x < columns - 1; x++)
    40.         {
    41.             for (int y = 1; y < rows - 1; y++)
    42.             {
    43.                 gridPositions.Add(new Vector3(x,y,0f));
    44.             }
    45.         }
    46.     }
    47.    
    48.     void BoardSetup ()
    49.     {
    50.         boardHolder = new GameObject ("Board").transform;
    51.        
    52.         for (int x = -1; x < columns + 1; x++)
    53.         {
    54.             for (int y = -1; y < rows + 1; y++)
    55.             {
    56.                 GameObject toInstantiate = floorTiles[Random.Range (0, floorTiles.Length)];
    57.                 if ( x == -1 || x == columns || y == -1 || y == rows)
    58.                     toInstantiate = outerWallTiles[Random.Range (0,outerWallTiles.Length)];
    59.                
    60.                 GameObject instance = Instantiate(toInstantiate, new Vector3 (x,y,0f), Quaternion.identity) as GameObject;
    61.  
    62.                 instance.transform.SetParent(boardHolder);
    63.             }
    64.         }
    65.     }
    66.    
    67.     Vector3 RandomPosition()
    68.     {
    69.         int randomIndex = Random.Range(0, gridPositions.Count);
    70.         Vector3 randomPosition = gridPositions[randomIndex];
    71.         gridPositions.RemoveAt(randomIndex);
    72.         return randomPosition;
    73.     }
    74.    
    75.     void LayoutObjectAtRandom(GameObject[] tileArray, int minimum, int maximum)
    76.     {
    77.         int objectCount = Random.Range (minimum, maximum + 1);
    78.        
    79.         for (int i = 0; i < objectCount; i++)
    80.         {
    81.             Vector3 randomPosition = RandomPosition();
    82.             GameObject tileChoice = tileArray[Random.Range (0, tileArray.Length)];
    83.             Instantiate (tileChoice, randomPosition, Quaternion.identity);
    84.         }
    85.     }
    86.    
    87.     public void SetupScene(int level)
    88.     {
    89.         BoardSetup ();
    90.         InitialiseList ();
    91.         LayoutObjectAtRandom (wallTiles, wallCount.minimum, wallCount.maximum);
    92.         LayoutObjectAtRandom (foodTiles, foodCount.minimum, foodCount.maximum);
    93.         int enemyCount = (int)Mathf.Log (level, 2f);
    94.         LayoutObjectAtRandom (enemyTiles, enemyCount, enemyCount);
    95.         Instantiate (exit, new Vector3(columns - 1, rows - 1, 0F), Quaternion.identity);
    96.     }
    97. }
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class GameManager : MonoBehaviour
    5. {
    6.     public BoardManager boardScript;
    7.  
    8.     private int level = 3;
    9.    
    10.     void awake()
    11.     {
    12.         boardScript = GetComponent<BoardManager>();
    13.         InitGame ();
    14.     }
    15.  
    16.     void InitGame()
    17.     {
    18.         boardScript.SetupScene (level);
    19.     }
    20. }
    21.  
     
  22. Dchand4

    Dchand4

    Joined:
    Jul 11, 2015
    Posts:
    3
    Would like it a lot if somebody please responded to my earlier question on page 7. Thanks in advance!
     
  23. Fragmental

    Fragmental

    Joined:
    Jun 30, 2013
    Posts:
    61
    "boxCollider.enabled = true" is missing a semicolon. The ide(monodevelop) should have produced an error.
     
  24. Fragmental

    Fragmental

    Joined:
    Jun 30, 2013
    Posts:
    61
    Thank you for this swift reply! :D.

    So interrupting the loop is the best option?

    What is the best method(figurative and literal...is this a terrible joke in c# circles)? I have tried this using various methods. I've tried using a function with a while loop, and that froze unity. I tried using coroutines with a while loop and that either never loaded the level, did nothing, or froze unity.

    Edit:
    I used
    Code (CSharp):
    1. while (!clicked)
    2.                 {
    3.                     yield return new WaitForSeconds(0.01f);
    4.                 }
    5.                 clicked = false;
    and it seems to work ok as a test.
     
    Last edited: Jul 27, 2015
  25. 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/
     
  26. 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/
     
  27. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    @keatonhuff the error is telling you what you need to know "You probably need to assign the gameManager variable of the Loader script in the inspector." Did you drag the GameManager prefab into the Game Manager variable slot of Loader, attached to the Main Camera of your scene? When in doubt, open the completed scene Main in the Completed folder under Scenes and compare.
     
  28. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    That's a bit strange. In Loader the GameManager is checked for and instantiated in Awake if missing, which is called before Start so you shouldn't need to edit the script execution order. Can you make sure your Loader script is attached to the Main Camera and has the Game Manager prefab assigned correctly as in Completed > Scenes > Main? Sounds like your fix will work but shouldn't be needed.
     
  29. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238

    You are calling "awake" in your GameManager script instead of "Awake", note the capitalization. Case sensitivity matters in C#.
     
  30. Sssquish

    Sssquish

    Joined:
    Jul 26, 2015
    Posts:
    2
    Wow.. I feel ridiculous. I was about to open a VM on another machine to see if my old computer was the problem. Thank you very much Matthew.
     
    Matthew-Schell likes this.
  31. Dchand4

    Dchand4

    Joined:
    Jul 11, 2015
    Posts:
    3
    Thanks Fragmental! It fixed everything!
     
    Fragmental likes this.
  32. Fragmental

    Fragmental

    Joined:
    Jun 30, 2013
    Posts:
    61
    You're welcome. I found this issue, by copying your code into my ide and then looking at the error it produced. It told me exactly what the problem was and which line it was on. Doing the same should help you to solve this problem in the future.

    Also, as mentioned by Adam Buckner, using the code tags will make your code more readable, in answers or forums, which will make it much easier to others to diagnose the issue.
     
    Last edited: Aug 22, 2015
  33. Hedeag

    Hedeag

    Joined:
    Feb 10, 2015
    Posts:
    29
    Could you help me, I faced this problem: when there are10-15 enemies on the map, they make moves very slowly, is it possible tospeed them up, so thatthey moved in a second and you didn't have to wait for 2-3 seconds until each of them moves?
     
  34. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    This is a known limitation of this design. It's to prevent the enemies or player moving into the same square and getting stuck. You'll have to make some changes to the movement code to eliminate that. I was trying to figure out how to get rid of it before shipping but ran out of time and just had to ship. If you figure something out post it here.
     
  35. bradido

    bradido

    Joined:
    Nov 19, 2009
    Posts:
    6
    I am having an issue at the end of step 11 when you try to move around and pick up food, soda, and use the exit. None of the collisions are firing.

    I have:
    • Verified I have the latest version of Unity
    • Verified my sorting layers
    • Made sure the isTrigger box is checked on Food and Soda
    • Tried tracing anything in OnTriggerEnter2D (nothing happens)
    • I replaced my Player script with the code on the tutorial page
    • I replaced my Player script with the completed one (commented out the SoundManager and foodText)
    • I replaced my Food prefab with the completed prefab
    • Replaced my Player prefab with the completed one
    • I have done numerous screenshots of the Inspector of the completed objects (Food, Player, Soda) and compared them to my objects and they are Identical.

    The completed project seems to work fine though. Is there an order of operations issue that perhaps get resolved in the final code structure?

    Thanks.
     
  36. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    Please verify that the Player is on the Layer BlockingLayer. Sorting Layers are for sprites, Layers are for physics (among other things).
     
  37. joewode

    joewode

    Joined:
    Dec 3, 2014
    Posts:
    35
    I'm having the same exact problem as Adam.Kubik:

    I had no problems up until this lesson and I can't figure out why adding UI elements would break the whole game. I've gone over my code multiple times now and it seems to be correct. Help?
     
  38. bradido

    bradido

    Joined:
    Nov 19, 2009
    Posts:
    6
    I found my issue :)

    Since I eliminated the Player or Food prefabs/scripts as the culprits, it had to be somewhere in MovingObject. Turns out I missed the line of code re-enableing the boxCollider after the Raycast in the Move() function.

    Thanks Matthew!
     
    Matthew-Schell likes this.
  39. Fragmental

    Fragmental

    Joined:
    Jun 30, 2013
    Posts:
    61
    I have the level being loaded sequentially, one tile at a time on each click now, and I'm trying to make the game wait until the level is fully loaded before the game really begins.

    I tried deactivating the player and sound objects and then activating them after the level has loaded, but it turns out finding a non-active game object is tricky.

    Then I tried leaving the Player Object active and then leaving the player script and layer spriterender deactivated at launch and activating them via script. This worked, but there is an error when the next leave loads that says:
    I can't help but feel like there is a better way to do this.
     
  40. oripatti

    oripatti

    Joined:
    Aug 3, 2015
    Posts:
    1
    Hi!

    Sorry if this has been asked before but I have strange problem with the movement. Somehow the player sometimes moves a bit too far (e.g. not a whole tile but a little bit more). This causes all kinds of problems when enemies and player are almost half way in the same tile. Sometime the player stops a bit short from exit (but it triggers still) or collects food when not entirely on a tile.

    My MovingObjects scritp is here:
    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.     // Use this for initialization
    14.     protected virtual void Start ()
    15.     {
    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)
    22.     {
    23.         Vector2 start = transform.position;
    24.         Vector2 end = start + new Vector2 (xDir, yDir);
    25.  
    26.         boxCollider.enabled = false;                            // disable box collider so we don't bump into our own hitbox
    27.         hit = Physics2D.Linecast (start, end, blockingLayer);    // check if something is on the blocking layer on the line we're moving on
    28.         boxCollider.enabled = true;                                // enable box collider again for the moving object
    29.  
    30.         if (hit.transform == null) {                            // check if there's nothing on the way of the movement
    31.             StartCoroutine(SmoothMovement (end));                // do move
    32.             return true;                                        // return true if we can move
    33.         }
    34.  
    35.         return false;                                            // if we can't move, return false
    36.  
    37.     }
    38.  
    39.     protected IEnumerator SmoothMovement (Vector3 end)
    40.     {
    41.         float sqrRemaininDistance = (transform.position - end).sqrMagnitude;
    42.  
    43.         while (sqrRemaininDistance > float.Epsilon)
    44.         {
    45.             Vector3 newPosition = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.deltaTime);
    46.             rb2D.MovePosition(newPosition);
    47.             sqrRemaininDistance = (transform.position - end).sqrMagnitude;
    48.             yield return null;
    49.         }
    50.     }
    51.  
    52.     protected virtual void AttemptMove <T> (int xDir, int yDir)
    53.         where T : Component
    54.     {
    55.         RaycastHit2D hit;
    56.         bool canMove = Move (xDir, yDir, out hit);                // Move function returns a boolean and a hit component
    57.  
    58.         if (hit.transform == null)                                // check the hit component returned
    59.             return;                                                // if there's nothing in the way (i.e. hit is null)
    60.  
    61.         T hitComponent = hit.transform.GetComponent<T> ();        // if there was something in the way, we get the component that's blocking us
    62.  
    63.         if (!canMove && hitComponent != null)                    // if we can't move and hit component is not null (meaning we can interact), we check what happens when we interact with the component
    64.             OnCantMove (hitComponent);                            // we pass the component blocking us to the OnCantMove function. The component will have it's own class for interaction
    65.     }
    66.  
    67.     protected abstract void OnCantMove <T> (T component)        // this is "empty" class for dealing with interaction. Every component has its own class (player interacts with floors, food, enemies and enemies interact with player etc).
    68.         where T : Component;
    69.  
    70. }
    71.  
    and my player code is here:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using UnityEngine.UI;
    4.  
    5. public class Player : MovingObject {
    6.  
    7.     public int wallDamage            = 1;                            // how much damage player inflicts to walls
    8.     public int pointsPerFood        = 10;
    9.     public int pointsPerSoda        = 20;
    10.     public int pointsPerPissjug        = 50;
    11.     public float restartLevelDelay    = 1f;
    12.     public Text foodText;                                            // display food
    13.  
    14.     private Animator animator;
    15.     private int food;
    16.  
    17.  
    18.     // Use this for initialization
    19.     protected override void Start () {
    20.         animator = GetComponent<Animator> ();                        // get reference to the animator component
    21.  
    22.         food = GameManager.instance.playerFoodPoints;                // get the food points that are stored in the GameManager in order to save them on level change
    23.  
    24.         foodText.text = "Food " + food;
    25.  
    26.         base.Start ();                                                // call the Start function of our base MovingObject class
    27.     }
    28.  
    29.     private void OnDisable() {
    30.         GameManager.instance.playerFoodPoints = food;                // when player is not active (e.g. changing level), we store the food points to the game manager for later use.
    31.     }
    32.  
    33.     // Update is called once per frame
    34.     void Update () {
    35.         if (!GameManager.instance.playersTurn)
    36.             return;
    37.  
    38.         int horizontal    = 0;                                        // reset the x axis position we're moving to (1,-1)
    39.         int vertical     = 0;                                        // reset the y axis position we're moving to (1,-1)
    40.  
    41.         horizontal = (int)(Input.GetAxisRaw ("Horizontal"));        // read the key presses and turn them into integers
    42.         vertical = (int)(Input.GetAxisRaw ("Vertical"));            // read the key presses and turn them into integers
    43.  
    44.         if(horizontal != 0)                                            // if horizontal not 0, we change vertical to 0
    45.             vertical = 0;                                            // so that player cannot move diagonally (1,1, -1,-1 etc)
    46.  
    47.         if (horizontal != 0 || vertical != 0)                        // if neitheris not 0 (e.g. we are not moving diagonally) we attempt to move
    48.             AttemptMove<Wall> (horizontal, vertical);                // we call AttemptMove function and pass it a Wall-component (so it expects something to interact with)
    49.  
    50.     }
    51.  
    52.     protected override void AttemptMove <T> (int xDir, int yDir) {    // we override the function from MovingObject and give it the coordinates and what kind of component it should expect (T)
    53.            
    54.         food--;                                                        // everytime we try to move, we lose on food point                                              
    55.         foodText.text = "Food " + food;
    56.         base.AttemptMove <T> (xDir, yDir);                            // apply the parent classes AttemptMove function and pass on "us" (T) and the coordinates
    57.         RaycastHit2D hit;                                            // we create a hit variable to reference in Move
    58.         CheckIfGameOver ();                                            // finally we check if player's out of food or game has ended otherwise
    59.         GameManager.instance.playersTurn = false;                    // change player's turn to false so the game knows we're through with this turn
    60.     }
    61.  
    62.     private void OnTriggerEnter2D (Collider2D other) {                // Check the other tiles we can interact with with UNITY's OnTriggerEnter2D API
    63.                                                                     // it checks the tile when entering and does something corresponding what it encounters
    64.         if (other.tag == "Exit") {
    65.             Invoke ("Restart", restartLevelDelay);
    66.             enabled = false;
    67.         } else if (other.tag == "Food") {
    68.             food += pointsPerFood;
    69.             foodText.text = "Food " + food;                            // increase food count
    70.             other.gameObject.SetActive (false);
    71.         } else if (other.tag == "Soda") {
    72.             food += pointsPerSoda;
    73.             foodText.text = "Food: " + food;
    74.             other.gameObject.SetActive (false);
    75.         }
    76.     }
    77.  
    78.     protected override void OnCantMove <T> (T component) {
    79.  
    80.         Wall hitWall = component as Wall;                            // we create a variable hitWall of Wall type and cast the passed component as Wall to it
    81.         hitWall.DamageWall (wallDamage);                            // then we call DamageWall function to the hitWall varibale
    82.         animator.SetTrigger ("PlayerAttack");                        // we call playerAttack animation
    83.  
    84.     }
    85.  
    86.     private void Restart() {
    87.         Application.LoadLevel (Application.loadedLevel);
    88.     }
    89.  
    90.     public void LoseFood (int loss) {
    91.         animator.SetTrigger ("PlayerHit");
    92.         food -= loss;
    93.         foodText.text = "Food " + food;
    94.         CheckIfGameOver ();
    95.     }
    96.  
    97.     private void CheckIfGameOver() {
    98.         if (food <= 0)
    99.             GameManager.instance.GameOver ();
    100.     }
    101.  
    102.  
    103. }
    104.  
    Maybe I'm just blind and can't see a typo or something....


    Other thing I've been trying to find is a inventory system. It would be good to be able to eat the food etc when you want.
     
  41. Shunaev

    Shunaev

    Joined:
    Mar 4, 2015
    Posts:
    9
    Matthew-Schell and Fragmental like this.
  42. Bduarte

    Bduarte

    Joined:
    Jul 17, 2015
    Posts:
    2
    I am running through this tutorial and I am on part 11, but I'm having a issue that when I press play to test my game I am able to move my player but only once, two other things I noticed is that my game always spawns 2 enemies and also my enemies are not moving. If anybody can help me solve this problem I will be dearly grateful. Thank you and goodnight.
     
  43. theswedishafro

    theswedishafro

    Joined:
    Jul 1, 2015
    Posts:
    1
    Posting this in case any derpy people like myself run into a similar problem and want a quick fix.

    If you run the scene after Part 11 of the tutorial and your player can only move to the tile 1 space above or 1 space to the right of the starting position, make sure your code on line 2 of the MovingObjects' Move function is the following:

    Code (CSharp):
    1. Vector2 end = start + new Vector2(xDir, yDir);
    and not just

    Code (CSharp):
    1. Vector2 end = new Vector2(xDir, yDir);
    Simple mistake that can be hard to pin down because it produces no errors/warnings.

    P.S. Thanks for the great tutorial. I am really enjoying it thus far.
     
    Matthew-Schell likes this.
  44. Fragmental

    Fragmental

    Joined:
    Jun 30, 2013
    Posts:
    61
    I'm loading the level sequentially.

    I'm trying to disable the player,and then wait until the level is loaded to reenable.
    If I disable the player object, the enemy script can't find the player object.
    If I disable the player script,
    Code (csharp):
    1. GameManager.instance.playerFoodPoints = food;
    isn't passed.

    I'm disabling at the beginning SetupScene of Boardmanager, and reenabling in a coroutine that runs at the end of of SetupScene.

    Is there a simple solution to this, or would I need a more extensive rewrite?
     
  45. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    You could add a variable to store a reference to the player object to another script like the GameManager and then call SetActive(true) on it. That's probably what I would do.
     
  46. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    Please double check that your player's rigidbody2d is set to isKinematic = true in the inspector. When in doubt check your prefab against the Player prefab in the completed folder.
     
  47. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    Please use the code tags to format your source. Looking at the image I'm guessing that you didn't add the player prefab to your scene. Also check the sorting layers on your sprites to make sure they're not being rendered behind the floor tiles.
     
  48. Fragmental

    Fragmental

    Joined:
    Jun 30, 2013
    Posts:
    61
    Thank you for the reply!

    I'm not entirely sure I follow. I may be misunderstanding, (and I apologize if I am) but if I'm reading this correctly, I considered doing this, but unless the player object is active when the game begins, finding it requires some code that is far more complex and resource intensive than I would like to use. I found it easier to simply leave the objects active in the inspector, find them on start, and then disable them.

    The current project starts with both soundmanager obj and the player obj enabled. Then code finds the player and soundmanager at the beginning of the SetupScene of Boardmanager and disables them both. The player and soundmanager objects are both reeneabled at the end of setupscene. The problem with this is that the enemy script cannot find the player object, and I have to load the enemy before I can load the player.

    If I disable and reenable the player sprite and script instead of the player object,
    Code (csharp):
    1. GameManager.instance.playerFoodPoints = food;
    isn't passed.

    If I disable the sprite, but leave the script enabled, the player is able to move before the final tile is loaded, which is a problem.
     
  49. David_Munoz

    David_Munoz

    Joined:
    Jul 30, 2015
    Posts:
    2
    Hello, i got to the end of "Enemy Animator Controller" video, but i cant move the player. I cant find the problem, everything is as in the tutorial but the name of the prefab "Player" element, the build settings are in "stand alone" and when using Debug to console i learned that the Update function of the Player script is called in a loop but nothing seems to move. Please help me to figure this out.
     
  50. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238

    If you add a 'player' variable of the type GameObject to GameManager for example, and then drag a reference to it in the inspector, you will be able to access it whether it is enabled or not. You won't need to find it at all, you can use the reference you stored. Disable it in the scene before hitting play, and enable it when you need it via script using player.SetActive(true). Give it a try.
     
Thread Status:
Not open for further replies.