Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

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

    gwnguy

    Joined:
    Apr 25, 2017
    Posts:
    144
    Check post (#912) by JRWidley.
     
  2. Tempest74

    Tempest74

    Joined:
    May 17, 2017
    Posts:
    133
    Thx, It helped me a lot.
     
  3. Stratorian

    Stratorian

    Joined:
    Jun 27, 2017
    Posts:
    1
    Every time my guy gets to the 'end' the splash screen comes up, but it just repeats "Day 1" and doesn't reload the level.

    This is what I have in my "Restart" function

    private void Restart ()
    {
    //Load the last scene loaded, in this case Main, the only scene in the game.
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);

    }

    I also tried SceneManager.LoadScene(0); but that didn't work either
     
  4. mindfulMike

    mindfulMike

    Joined:
    May 8, 2017
    Posts:
    1
    I am having issues with too many enemies spawning and items spawning on top of each other. Ive checked BoardManager and everything looked right, even used the "Completed" BoardManager, still having spawn issues. Is anyone else having this issue??

    EDIT: *SOLVED* I had an instance of GameManager in my heirarchy lol
     
    Last edited: Jul 3, 2017
  5. AdobeWallHacks

    AdobeWallHacks

    Joined:
    Jul 4, 2017
    Posts:
    2
    Despite me scanning this thread, I couldnt find an answer to my problem, so sorry if this was already answered and I missed it.

    Anyway, my writing of the MovingObject script resulted in many of compile errors in the end of the program, regarding the 'T Component' functions.

    Pastebin of my Code: https://pastebin.com/dThTMALs
    Image of all the sections returning errors: http://imgur.com/o2Cun90

    If you want the specific error a phrase is giving, let me know.

    Help is much appreciated!
     
  6. gwnguy

    gwnguy

    Joined:
    Apr 25, 2017
    Posts:
    144
    I think around line 54, add "void:
    from
    Code (csharp):
    1.  
    2.     protected virtual AttemptMove<T>(int xDir, int yDir)
    3.       where T : Component;
    4.  
    to
    Code (csharp):
    1.  
    2.     protected virtual void AttemptMove<T>(int xDir, int yDir)
    3.         where T : Component
    4.  
    See if any help...
     
  7. Yog555

    Yog555

    Joined:
    Jul 4, 2017
    Posts:
    4
    Hi, I'm working through this tutorial at the moment - slightly modified to use hex tiles instead of squares - but I'm running into strange behaviour using the Count.maximum and Count.minimum member variables. Sorry if this has been asked but searching for these variables brings up every other post as a hit :)

    I initialised my enhancements Count to (2,5) however every time I called LayoutObjectsAtRandom(tilearray, enhancements.minimum, enhancements.maximum) I seemed to be generating exactly 2 enhancements. I logged out when the constructor was called and it reported the correct minimum and maximum after assigning them, however when I logged those values out in SetupScene it was reporting both minimum and maximum as 2. When passed hardcoded values for min and max the LayoutObjectAtRandom function behaves correctly.

    I also broke my project at some point and had to recreate the GameManager object and reattach the scripts and tile arrays, and after that I changed the values passed to the new Count to 1 and 19, and uncommented my previous call to LayoutObject at random, and now it is reporting min/max as 2 & 5! Given that it seemed to load the correct values when the script was reattached to the new manager object, but does not update them if they change subsequently, it feels like this could be a serialization problem? but I don't know enough to properly diagnose it, and since the count class is explicitly serialized i don't know why it would happen?

    Code (CSharp):
    1. using System.Collections;
    2. using System;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using Random = UnityEngine.Random;
    6.  
    7. public class BoardManager : MonoBehaviour {
    8.  
    9.     [Serializable]
    10.     public class Count{
    11.         public int minimum;
    12.         public int maximum;
    13.  
    14.         public Count(int min, int max){
    15.             minimum = min;
    16.             maximum = max;
    17.             Debug.Log("Constructor called with min/max: " + minimum + " " + maximum);
    18.         }
    19.     }
    20.  
    21.     public int columns = 8;
    22.     public int rows = 8;
    23.     public Count enhancements = new Count (2, 5);
    24.     public GameObject[] floorTiles;
    25.     public GameObject[] wallTiles;
    26.     public GameObject[] enhancedTiles;
    27.  
    28.     float xOffset = 1.216f;
    29.     float yOffset = 1.079f;
    30.  
    31.     private Transform boardHolder;
    32.     private List<Vector3> gridPositions = new List<Vector3>();
    33.  
    34.     void InitialiseList(){
    35.         gridPositions.Clear ();
    36.         for (int x = 1; x < columns - 1; x++) {
    37.             for (int y = 1; y < rows - 1; y++) {
    38.                 gridPositions.Add(new Vector3(x,y,0f));
    39.             }
    40.                
    41.         }
    42.     }
    43.  
    44.     private void BoardSetup(){
    45.         boardHolder = new GameObject ("Board").transform;
    46.  
    47.  
    48.         for (int x = 0; x < columns + 1; x++) {
    49.             for (int y = 0; y < rows + 1; y++) {
    50.  
    51.                 float xPos = x * xOffset;
    52.  
    53.                 //are we on an odd row?
    54.                 if (y % 2 == 1) {
    55.                     xPos += xOffset / 2f;
    56.                 }
    57.                 //default to instantiating a random floor tile
    58.                 GameObject toInstantiate = floorTiles [Random.Range (0, floorTiles.Length)];
    59.  
    60.                 //if on the border, choose a wall tile instead
    61.                 if (x == 0 || x == columns || y == 0 || y == rows) {
    62.                     toInstantiate = wallTiles [Random.Range (0, wallTiles.Length)];
    63.  
    64.  
    65.                 }
    66.  
    67.                 GameObject instance = Instantiate (toInstantiate, new Vector3(xPos, y* yOffset, 0f), Quaternion.identity) as GameObject;
    68.                 //GameObject instance = Instantiate (toInstantiate, new Vector3(x,y, 0f), Quaternion.identity) as GameObject;
    69.                 instance.transform.SetParent (boardHolder);
    70.                 instance.name = "Hex_" + x + "_" + y;
    71.             }
    72.         }
    73.     }
    74.  
    75.     Vector3 RandomPosition()
    76.     {
    77.         int randomIndex = Random.Range (0, gridPositions.Count);
    78.         Vector3 RandomPosition = gridPositions [randomIndex];
    79.         gridPositions.RemoveAt (randomIndex);
    80.         return RandomPosition;
    81.     }
    82.  
    83.     void LayoutObjectAtRandom(GameObject[] tileArray, int minimum, int maximum)
    84.     {
    85.         int objectCount = Random.Range (minimum, maximum + 1);
    86.         Debug.Log ("object count between " + minimum + " and " + maximum + ": " + objectCount);
    87.         for (int i = 0; i < objectCount; i++) {
    88.        
    89.             Vector3 randomPosition = RandomPosition ();
    90.             Vector3 gridRef = randomPosition;
    91.             float xPos = randomPosition.x * xOffset;
    92.             //are we on an odd row?
    93.             if (randomPosition.y % 2 == 1) {
    94.                 xPos += xOffset / 2f;
    95.             }
    96.             randomPosition.y = randomPosition.y * yOffset;
    97.             randomPosition.x = xPos;
    98.             //delete the existing floor tile at this location before instantiating enhanced tile
    99.             GameObject tileToReplace = GameObject.Find("Hex_"+gridRef.x+"_"+gridRef.y);
    100.             Destroy (tileToReplace);
    101.             GameObject tileChoice = tileArray[Random.Range (0, tileArray.Length)];
    102.             GameObject instance = Instantiate (tileChoice, randomPosition, Quaternion.identity) as GameObject;
    103.  
    104.             instance.transform.SetParent (boardHolder);
    105.             instance.name = "Hex_" + gridRef.x + "_" + gridRef.y;
    106.  
    107.         }
    108.     }
    109.  
    110.     public void SetupScene(){
    111.         BoardSetup ();
    112.         InitialiseList ();
    113.         Debug.Log ("enhancements min/max " + enhancements.minimum + enhancements.maximum);
    114.         //LayoutObjectAtRandom (enhancedTiles, enhancements.minimum, enhancements.maximum);
    115.         LayoutObjectAtRandom (enhancedTiles, 2, 5); //TODO find out why enhancements.minimum and .maximum aren't working
    116.     }
    117.  
    118.     // Use this for initialization
    119.     void Start () {
    120.        
    121.     }
    122.    
    123.     // Update is called once per frame
    124.     void Update () {
    125.        
    126.     }
    127. }
     
  8. s73v3r

    s73v3r

    Joined:
    Jul 5, 2017
    Posts:
    1
    Is it possible to give the components names, at least ones that are visible in the editor? When I got to the Sound lesson, I ended up setting both the FX source and the Music source to the same AudioSource component. This led to a bug where I would hear the music playing, but once the player took a step, the music was replaced with the footstep sound looped over and over. I feel if one could name these two components, that mixup wouldn't haven't happened.
     
  9. AdobeWallHacks

    AdobeWallHacks

    Joined:
    Jul 4, 2017
    Posts:
    2
    Thank you very much, everything in the function was returning errors, some even suggesting that i needed to update my coding library. Couldnt of thought it was the function declaration. Thank you
     
  10. Vorpike

    Vorpike

    Joined:
    Jun 24, 2017
    Posts:
    10
    Why do you type out the early version of the script in the tutorial, then attach the completed version? It doesn't even work and you already have the version we need typed out...
     
  11. DavDevGames

    DavDevGames

    Joined:
    Jul 11, 2017
    Posts:
    9
    Hello everyone and thanks Matthew-Schell for the amzing Tutorial.

    Guys, I've been following this tutorial and managed to understand and replicate most things I've learned so far. However I'm try to understand how GameManager script/Unity Engine decides a tile position and size on the scene based on its GridPositions. It may be trivia but cant understand how it knows the size of the tile and defines that a given GridPosition have a certain size on the scene and if it needs to instantiate a new adjacent tile it dont overlaps another tile(actually floor GameObject) just basing it on its GridPosition.
     
  12. Yog555

    Yog555

    Joined:
    Jul 4, 2017
    Posts:
    4
    The instantiate function doesn't know as such, it's just taking the arguments of where to place the tile in worldspace - it is using the x and y values from the for loops though, not gridPositions - but this all just works out because the tile prefabs are all of scale 1 in the x and y dimensions. If you instantiate one tile at 0,0,0 then the next at 1,0,0 those prefabs will be exactly one unit apart in the x dimension, since the tile itself is 1 unit wide it lines up perfectly in worldspace and correlates to it's x/y in gridpositions. If you view the prefab in the inspector and change its x or y scale this will no longer be the case and you can see the tiles will overlap or not meet up. If you were using differently sized tiles you would need to calculate an offset before instantiating your tiles
     
    DavDevGames likes this.
  13. DavDevGames

    DavDevGames

    Joined:
    Jul 11, 2017
    Posts:
    9
    Ty! It helped alot =). Thing is I still dont understand well the environment. Thought that when I instantiate a tile in a given coord like 0,0,0 or 1,0,0 was in pixels, cms or something like that but it actually considers that grid on scene editor. Guess what? Need to go back to the basics and study a bit more the environment.

    Thanks again Yog555, you really helped .

    Edit: Im trying to find the distance between point A(0,0,0) and B(1,0,0) in pixels and how I define it. I noticed that in the example we have 32pixels but in my own project it is a way bigger.
     
    Last edited: Jul 12, 2017
  14. DavDevGames

    DavDevGames

    Joined:
    Jul 11, 2017
    Posts:
    9
  15. Shin_Toasty

    Shin_Toasty

    Joined:
    Jun 15, 2017
    Posts:
    48
    Hello world, I've just started using Unity and this is my first post here. :)

    I can't code a restart button that resets the level to 1 and the food to 100, but I've had no trouble coding them on the other tutorial games.

    I have (inadvertently) coded a continue function where you restart the same level, but again, can't get the food back to 100, so I stagger around the level with negative food value dying every step. It's quite funny.
     
  16. MisinformedDNA

    MisinformedDNA

    Joined:
    Jul 23, 2017
    Posts:
    1
    Sorry if this has been asked, (and it's maybe a minor thing but it bugs me), but in video 5, Writing the Game Manager, you set the level to 3. In the previous video you set the enemy count to be equal to `Mathf.Log(level, 2)`. When you run the game, in the video, you have two enemies, but I only have one. As mentioned in video 4, you shouldn't have two enemies until level four, right? What am I missing here?
     
  17. VCBackup

    VCBackup

    Joined:
    Jul 24, 2017
    Posts:
    1
    Hey all, been enjoying the tutorials and following it along pretty well, but I've an error in my code for the Board Manager.

    BoardManager.cs
    ...
    void BoardSetup()
    {
    boardHolder = new GameObject { "Board" }.transform;

    for (int x = -1; x < columns + 1; x++)
    {
    for (int y = -1; y < rows + 1; y++)
    {
    GameObject toInstantiate = floorTiles[Random.Range(0, floorTiles.Length)];
    if (x == -1 || x == columns || y == -1 || y == rows)
    {
    toInstantiate = outerWallTiles[Random.Range(0, outerWallTiles.Length)];

    GameObject instance = Instantiate(toInstantiate, new Vector3(x, y, 0f), Quaternion.identity) as GameObject;

    instance.transform.SetParent(boardHolder);
    }
    }
    }
    }
    ...

    For some reason I keep getting an error from the new GameObject {"Board"} that says:
    class System.String
    Cannot initialize type 'GameObject' with a collection initializer because it does not implement 'System.Collections.IEnumerable'

    Any idea why I'm getting this error? As I follow along I'm pretty sure that it's identical to what is written.
    Cheers!
     
  18. moumni-mohamed

    moumni-mohamed

    Joined:
    Dec 9, 2015
    Posts:
    2
    there is a problem if the number of the maximum and minimum of are greater than the number of the positions in the list . form i use the same concept but i want the levels will be more big by winning in the levels .
     
  19. Dymalle42

    Dymalle42

    Joined:
    Jul 30, 2017
    Posts:
    2
    Hello,
    Thanks for the Tutorial!
    I'm trying to do it with a smaller player but kept the collider attached of the size of a cell.
    But the rigidbody being smaller the player doesn't stay in the middle of the cell, collision being done between the rigidbody and the walls.
    How can I get the physics collision done with the size of the collider, a square cell size, rather than the smaller rigidbody? So that the player is always in the middle of a cell after each move.
     
  20. Yog555

    Yog555

    Joined:
    Jul 4, 2017
    Posts:
    4
    Is this a direct copy/paste? Assuming it's c# and not js which I'm not familiar with, those should be parentheses not braces ie boardHolder = new GameObject ( "Board" ).transform; You're calling the GameObject constructor function and passing it a string, a function call is always Function() - braces denote a collection, like a dictionary, hence the collection-related error message
     
    Last edited: Aug 1, 2017
  21. Tamanoir

    Tamanoir

    Joined:
    Aug 1, 2017
    Posts:
    27
    Hi,
    I have a probleme. After the 8th part of the tutorial I am suppose to see the player on the board doing the idle animation. The issue is that the player isn't appearing on the board i suppos that he is under the board. I'v done some tests and if i suppress the board i can see the player again when i'm running the project. I don't know how to fix this bug. Please help me.

    Thx for your help.

    ps : sorry for my english i'm not native.
     
  22. Yog555

    Yog555

    Joined:
    Jul 4, 2017
    Posts:
    4
    Check the sorting layer on your player prefab's sprite renderer component, you may have left it on default and it's being rendered under the floor tiles
     
  23. Stefan97

    Stefan97

    Joined:
    Aug 2, 2017
    Posts:
    1
    Hi ,
    i am at part 11 of the tut and i have the problem that my player can not be moved , not even once like the problem many others have had.

    EDIT: I am using unity 5.5.2f1

    Every time i press a key to move the player this error message is coming up :
    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. MovingObjekt.move (Int32 xDir, Int32 yDir, UnityEngine.RaycastHit2D& hit) (at Assets/Scripts/MovingObjekt.cs:30)
    3. MovingObjekt.attemptMove[Wall] (Int32 xDir, Int32 yDir) (at Assets/Scripts/MovingObjekt.cs:89)
    4. Player.attemptMove[Wall] (Int32 xDir, Int32 yDir) (at Assets/Scripts/Player.cs:36)
    5. Player.Update () (at Assets/Scripts/Player.cs:75)
    Here are my C# Scripts:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    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.     public int level = 3;
    13.  
    14.     private List<Enemy> enemies;
    15.     private bool enemiesMoving;
    16.  
    17.     private void Awake()
    18.     {
    19.         if (instance == null)
    20.         {
    21.             instance = this;
    22.         }
    23.         else if (instance != this)
    24.         {
    25.             Destroy(gameObject);
    26.         }
    27.          
    28.         DontDestroyOnLoad(gameObject);
    29.  
    30.         enemies = new List<Enemy>();
    31.         boardScript = GetComponent<BoardManager>();
    32.         initGame();
    33.     }
    34.  
    35.  
    36.     void initGame()
    37.     {
    38.         enemies.Clear();
    39.         boardScript.setupScene(level);
    40.     }
    41.  
    42.     // Update is called once per frame
    43.     void Update ()
    44.     {
    45.         if(playersTurn || enemiesMoving)
    46.         {
    47.             return;
    48.         }
    49.  
    50.         StartCoroutine(moveEnemies());
    51.     }
    52.  
    53.  
    54.     public void addEnemyToList(Enemy script)
    55.     {
    56.         enemies.Add(script);
    57.     }
    58.  
    59.     public void gameOver()
    60.     {
    61.         enabled = false;
    62.     }
    63.  
    64.  
    65.     IEnumerator moveEnemies()
    66.     {
    67.         enemiesMoving = true;
    68.         yield return new WaitForSeconds(turnDelay);
    69.         if(enemies.Count == 0)
    70.         {
    71.             yield return new WaitForSeconds(turnDelay);
    72.         }
    73.  
    74.         for(int i = 0; i < enemies.Count; i++)
    75.         {
    76.             enemies[i].moveEnemy();
    77.             yield return new WaitForSeconds(enemies[i].moveTime);
    78.         }
    79.  
    80.         playersTurn = true;
    81.         enemiesMoving = false;
    82.     }
    83. }
    84.  
    Code (CSharp):
    1. using System.Collections;
    2. using System;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using Random = UnityEngine.Random;
    6.  
    7. public class BoardManager : MonoBehaviour {
    8.  
    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 colums = 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.     // setup a list with all the available positions of the board
    36.     void initialiseList()
    37.     {
    38.         gridPositions.Clear();
    39.  
    40.         for(int i = 1; i < colums - 1; i++)
    41.         {
    42.             for(int j = 1; j < rows - 1; j++)
    43.             {
    44.                 gridPositions.Add(new Vector3(i, j, 0f));
    45.             }
    46.         }
    47.     }
    48.  
    49.     //setup the board with random floor and outerwalltiles
    50.     void boardSetup()
    51.     {
    52.         boardHolder = new GameObject("Board").transform;
    53.  
    54.         for (int i = -1; i < colums + 1; i++)
    55.         {
    56.             for (int j = -1; j < rows + 1; j++)
    57.             {
    58.                 GameObject toInstantiate = floorTiles[Random.Range(0, floorTiles.Length)];
    59.                 if(i == -1 || i == colums || j == -1 || j == rows)
    60.                 {
    61.                     toInstantiate = outerWallTiles[Random.Range(0, outerWallTiles.Length)];
    62.                 }
    63.                 GameObject instance = Instantiate(toInstantiate, new Vector3(i, j, 0f), Quaternion.identity) as GameObject;
    64.                 instance.transform.SetParent(boardHolder);
    65.             }
    66.         }
    67.     }
    68.  
    69.     // Declair a random position on inside the outerwalls (for Items, Walls and Enemys)
    70.     Vector3 randomPositions()
    71.     {
    72.         int randomIndex = Random.Range(0, gridPositions.Count);
    73.         Vector3 randomPosition = gridPositions[randomIndex];
    74.         gridPositions.RemoveAt(randomIndex);
    75.  
    76.         return randomPosition;
    77.     }
    78.  
    79.  
    80.     void layoutObjectAtRandom(GameObject[] tileArray, int minimum, int maximum)
    81.     {
    82.         int objectCount = Random.Range(minimum, maximum + 1);
    83.  
    84.         for(int i = 0; i < objectCount; i++)
    85.         {
    86.             Vector3 randomPosition = randomPositions();
    87.             GameObject tileChoice = tileArray[Random.Range(0, tileArray.Length)];
    88.             Instantiate(tileChoice, randomPosition, Quaternion.identity);
    89.         }
    90.     }
    91.  
    92.  
    93.     public void setupScene(int level)
    94.     {
    95.         boardSetup();
    96.         initialiseList();
    97.         layoutObjectAtRandom(wallTiles, wallCount.minimum, wallCount.maximum);
    98.         layoutObjectAtRandom(foodTiles, foodCount.minimum, foodCount.maximum);
    99.  
    100.         int enemyCount = (int)Mathf.Log(level, 2f);
    101.         layoutObjectAtRandom(enemyTiles, enemyCount, enemyCount);
    102.         Instantiate(exit, new Vector3(colums - 1, rows - 1, 0f), Quaternion.identity);
    103.     }
    104. }
    105.  
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public abstract class MovingObjekt : MonoBehaviour {
    6.  
    7.     public float moveTime = 0.1f;
    8.     public LayerMask blockingLayer;
    9.  
    10.     private BoxCollider2D boxCollider;
    11.     private Rigidbody2D rb2D;
    12.     private float inverseMoveTime;
    13.  
    14.  
    15.     // Use this for initialization
    16.     protected virtual void Start ()
    17.     {
    18.         boxCollider = GetComponent<BoxCollider2D>();
    19.         rb2D = GetComponent<Rigidbody2D>();
    20.         inverseMoveTime = 1f / moveTime;
    21.     }
    22.  
    23.  
    24.     protected bool move(int xDir, int yDir, out RaycastHit2D hit)
    25.     {
    26.         Vector2 start = transform.position;
    27.         Vector2 end = start + new Vector2(xDir, yDir);
    28.  
    29.         //deactivate the boxcollider of the moving objetkt so that the linecast will not collide with the objekt it self
    30.         boxCollider.enabled = false;
    31.         Debug.Log(boxCollider.enabled);
    32.  
    33.         //linecast casts an imaginary line between 2 points and checks if there is a collision on the set line
    34.         //hit will store informations about the objekt that collided with the linecast
    35.         hit = Physics2D.Linecast(start, end, blockingLayer);
    36.         boxCollider.enabled = true;
    37.  
    38.         //hit.transform is null if the raycast didnt collide on the blockingLayer
    39.         if(hit.transform == null)
    40.         {
    41.             //start to move the objekt towards its destination
    42.             StartCoroutine(smoothMovement(end));
    43.             return true;
    44.         }
    45.         //if the linecast did detect a collision
    46.         return false;
    47.     }
    48.  
    49.  
    50.     protected IEnumerator smoothMovement(Vector3 end)
    51.     {
    52.         //calculate the remaining distance between the start position and the end position
    53.         float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
    54.  
    55.         //moves the objekt towards its destination(end) . float.Epsilon has a value near 0.
    56.         while(sqrRemainingDistance > float.Epsilon)
    57.         {
    58.             //calculates the new position for the movement towards its destination(end)
    59.             Vector3 newPosition = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.deltaTime);
    60.             //moves the Rigidbody2D to its new Position
    61.             rb2D.MovePosition(newPosition);
    62.             //calculate the new remaining distance between the objekts Rigidbody2D and its destination(end)
    63.             sqrRemainingDistance = (transform.position - end).sqrMagnitude;
    64.             yield return null;
    65.         }
    66.     }
    67.  
    68.  
    69.     protected virtual void attemptMove <T> (int xDir, int yDir)
    70.         where T : Component
    71.     {
    72.         //if the move funktion is detecting a collision , the information about the collision objekt is stored in the hit variable
    73.         RaycastHit2D hit;
    74.         bool canMove = move(xDir, yDir, out hit);
    75.  
    76.         //no collision detected
    77.         if(hit.transform == null)
    78.         {
    79.             return;
    80.         }
    81.  
    82.         T hitComponent = hit.transform.GetComponent<T>();
    83.  
    84.         if (!canMove && hitComponent != null)
    85.         {
    86.             onCantMove(hitComponent);
    87.         }
    88.     }
    89.  
    90.     protected abstract void onCantMove<T>(T component)
    91.         where T : Component;
    92. }
    93.  
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class Player : MovingObjekt {
    7.  
    8.     //damage the player deals to a wall on a single chop
    9.     public int wallDamage = 1;
    10.     //food points the player gains by picking up food
    11.     public int pointsPerFood = 10;
    12.     public int pointsPerSoda = 20;
    13.     public float restartLevelDelay = 1f;
    14.  
    15.     private Animator animator;
    16.     private int food;
    17.  
    18.     // Use this for initialization
    19.     protected override void Start ()
    20.     {
    21.         animator = GetComponent<Animator>();
    22.  
    23.         food = GameManager.instance.playerFoodPoints;
    24.     }
    25.  
    26.     private void OnDisable()
    27.     {
    28.         GameManager.instance.playerFoodPoints = food;
    29.     }
    30.  
    31.  
    32.     protected override void attemptMove<T>(int xDir, int yDir)
    33.     {
    34.         food--;
    35.  
    36.         base.attemptMove<T>(xDir, yDir);
    37.  
    38.         RaycastHit2D hit;
    39.  
    40.         checkIfGameOver();
    41.  
    42.         GameManager.instance.playersTurn = false;
    43.     }
    44.  
    45.  
    46.     private void checkIfGameOver()
    47.     {
    48.         if(food <= 0)
    49.         {
    50.             GameManager.instance.gameOver();
    51.         }
    52.     }
    53.  
    54.     // Update is called once per frame
    55.     void Update ()
    56.     {
    57.         if (!GameManager.instance.playersTurn)
    58.         {
    59.             return;
    60.         }
    61.  
    62.         int horizontal = 0;
    63.         int vertical = 0;
    64.  
    65.         horizontal = (int)Input.GetAxisRaw("Horizontal");
    66.         vertical = (int)Input.GetAxisRaw("Vertical");
    67.  
    68.         //prevent diagonal movement
    69.         if(horizontal != 0)
    70.         {
    71.             vertical = 0;
    72.         }
    73.         if(horizontal != 0 || vertical != 0)
    74.         {
    75.             attemptMove<Wall>(horizontal, vertical);
    76.         }
    77.     }
    78.  
    79.  
    80.     protected override void onCantMove<T>(T component)
    81.     {
    82.         Wall hitWall = component as Wall;
    83.         hitWall.damageWall(wallDamage);
    84.         animator.SetTrigger("playerChop");
    85.  
    86.         //throw new NotImplementedException();
    87.     }
    88.  
    89.  
    90.     private void restart()
    91.     {
    92.         Application.LoadLevel(Application.loadedLevel);
    93.     }
    94.  
    95.  
    96.     public void loseFood(int loss)
    97.     {
    98.         animator.SetTrigger("playerHit");
    99.         food -= loss;
    100.         checkIfGameOver();
    101.     }
    102.  
    103.  
    104.     private void OnTriggerEnter2D(Collider2D other)
    105.     {
    106.         if(other.tag == "Exit")
    107.         {
    108.             Invoke("restart", restartLevelDelay);
    109.             enabled = false;
    110.         }
    111.         else if(other.tag == "Food")
    112.         {
    113.             food += pointsPerFood;
    114.             other.gameObject.SetActive(false);
    115.         }
    116.         else if (other.tag == "Soda")
    117.         {
    118.             food += pointsPerSoda;
    119.             other.gameObject.SetActive(false);
    120.         }
    121.     }
    122. }
    123.  
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class Enemy : MovingObjekt {
    7.  
    8.     public int playerDamage;
    9.  
    10.     private Animator animator;
    11.     private Transform target;
    12.     private bool skipMove;
    13.  
    14.     // Use this for initialization
    15.     protected override void Start ()
    16.     {
    17.         GameManager.instance.addEnemyToList(this);
    18.         animator = GetComponent<Animator>();
    19.         target = GameObject.FindGameObjectWithTag("Player").transform;
    20.         base.Start();
    21.     }
    22.  
    23.  
    24.     protected override void attemptMove<T>(int xDir, int yDir)
    25.     {
    26.         if (skipMove)
    27.         {
    28.             skipMove = false;
    29.             return;
    30.         }
    31.  
    32.         base.attemptMove<T>(xDir, yDir);
    33.  
    34.         skipMove = true;
    35.     }
    36.  
    37.  
    38.     public void moveEnemy()
    39.     {
    40.         int xDir = 0;
    41.         int yDir = 0;
    42.  
    43.         if(Mathf.Abs(target.position.x - transform.position.x) < float.Epsilon)
    44.         {
    45.             //short form of an if{}else{}
    46.             yDir = target.position.y > transform.position.y ? 1 : -1;
    47.         }
    48.         else if(Mathf.Abs(target.position.y - transform.position.y) < float.Epsilon)
    49.         {
    50.             xDir = target.position.x > transform.position.x ? 1 : -1;
    51.         }
    52.  
    53.         //move in the general direktion towards the player
    54.         attemptMove<Player>(xDir, yDir);
    55.     }
    56.  
    57.  
    58.     protected override void onCantMove<T>(T component)
    59.     {
    60.         Player hitPlayer = component as Player;
    61.  
    62.         animator.SetTrigger("EnemyAttack");
    63.  
    64.         hitPlayer.loseFood(playerDamage);
    65.     }
    66. }
    67.  
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Wall : MonoBehaviour {
    6.  
    7.     public Sprite dmgSprite;
    8.     public int hp = 4;
    9.  
    10.     private SpriteRenderer spriteRenderer;
    11.  
    12.     // Use this for initialization
    13.     void Awake ()
    14.     {
    15.         spriteRenderer = GetComponent<SpriteRenderer>();
    16.     }
    17.  
    18.     public void damageWall(int loss)
    19.     {
    20.         spriteRenderer.sprite = dmgSprite;
    21.         hp -= loss;
    22.  
    23.         if(hp <= 0)
    24.         {
    25.             gameObject.SetActive(false);
    26.         }
    27.     }
    28.  
    29. }
    30.  
     
  24. SnowconeMary

    SnowconeMary

    Joined:
    Aug 2, 2017
    Posts:
    1
    I'm having this same issue. Have you found a solution?
     
  25. Zyriab

    Zyriab

    Joined:
    Sep 1, 2017
    Posts:
    2
    Hello and thanks for this tutorial,

    In the tutorial video n°2.02 - Writing the Board Manager, at 3:32 - 3:35 (check the transcript) there's an error, the voice says "[...] we are going to use arrays [...]" but the subtitles/transcript says "[...] we are going to use a raise [...]".

    Thanks for the documentation, videos and all that good stuff, it really makes the difference !
     
  26. Palladann

    Palladann

    Joined:
    Aug 19, 2017
    Posts:
    1
    Hello,

    I wanted to change code in 2D Roguelike project, so that get wrapped/never ending map, so when player move to end of map and wanted to move on outerwall, he got transfered on other side of map, making illusion of wrapped map.

    What I changed is code in player class, on OnTriggerEnter2D() method. Frist, I create and put new tag - "OuterWall" and put that on OuterWall prefabs. Then I switch from BlockingLayer on Default, and put check on Box Collader 2D Is Trigger property also on all OuterWall frebas.

    Here is my code which I add to OnTriggerEnter2D() method.


    Code (CSharp):
    1. private void OnTriggerEnter2D (Collider2D other)
    2.     {
    3.     //Check if the tag of the trigger collided with is Exit.
    4.         if (other.tag == "Exit") {
    5.  
    6.             Instantiate (playerKilled, transform.position, Quaternion.identity);
    7.             SoundManager.instance.RandomizeSfx (portal);
    8.  
    9.             //Invoke the Restart function to start the next level with a delay of restartLevelDelay (default 1 second).
    10.             Invoke ("Restart", restartLevelDelay);
    11.  
    12.             //Disable the player object since level is over.
    13.             enabled = false;
    14.         }
    15.     else if (other.tag == "OuterWall")
    16.         {
    17.             Debug.Log ("OuterWall");
    18.             Debug.Log (other.transform.localPosition.x);
    19.    
    20.             // Checking for left outerwall
    21.             if (other.transform.localPosition.x < 1f)
    22.             {
    23.  
    24.                 transform.localPosition = new Vector3(transform.localPosition.x+7, transform.localPosition.y, 0f);
    25.  
    26.                 Debug.Log("Pomerio se:" + transform.localPosition + " x: " + transform.localPosition.x+7 + " y: " + transform.localPosition.y);
    27.             }
    28.         }
    29.     }
    30.  
    But, as a result I get transfered player who constantly move to left side, and in Debug.Log I get looping message "OuterWall", which means that he constantly trigger collader with object with OuterWall tag.

    How to change code, so that player only once move from left side of map on right side when he wanna go left?
     
  27. dgrosch

    dgrosch

    Joined:
    Sep 2, 2017
    Posts:
    2
    Thanks for this. The double InitGame() was causing me problems as well. After removing the first one, you'll need to move the level increment to before the remaining InitGame(). Otherwise, the first time you init the game, it will have incremented from 1 to 2.

     
    Last edited: Sep 9, 2017
  28. dgrosch

    dgrosch

    Joined:
    Sep 2, 2017
    Posts:
    2
  29. R3turnz

    R3turnz

    Joined:
    Sep 5, 2017
    Posts:
    2
    I finished the tutorial and implemented additonal a replay button and a highscore system. This is the first time I have done something in Unity and I would appreciate feedback or improvements suggestions.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5. using UnityEngine.UI;
    6.  
    7. public class GameManager : MonoBehaviour
    8. {
    9.     public static GameManager instance = null;
    10.     public BoardManager boardManager;
    11.     public int remainedFood = 100;
    12.     [HideInInspector] public bool isPlayersTurn = true;
    13.     public AudioClip gameOverClip;
    14.     public float levelStartDelay = 1f;
    15.     public float turnDelay = .1f;
    16.     public float restartLevelDelay = 1f;
    17.  
    18.     bool doingSetup;
    19.     int level = 1;
    20.     int highscore;
    21.     bool newHighscore;
    22.     List<Enemy> enemies = new List<Enemy>();
    23.     bool areEnemiesMooving;
    24.     Text highscoreText;
    25.     GameObject levelOverlay;
    26.     Text levelText;
    27.     GameObject gameOverOverlay;
    28.     Text gameOverText;
    29.  
    30.     void Awake()
    31.     {
    32.         if (instance == null)
    33.             instance = this;
    34.         else if (instance != this)
    35.             Destroy(gameObject);
    36.         DontDestroyOnLoad(gameObject);
    37.  
    38.         highscore = PlayerPrefs.HasKey("Highscore") ? PlayerPrefs.GetInt("Highscore") : level;
    39.         SetupGame();
    40.     }
    41.  
    42.     void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    43.     {
    44.         level++;
    45.         if (level > highscore)
    46.         {
    47.             highscore = level;
    48.             newHighscore = true;
    49.         }
    50.         SetupGame();
    51.     }
    52.  
    53.     void SetupGame()
    54.     {
    55.         doingSetup = true;
    56.         var ui = GameObject.Find("UI");
    57.         highscoreText = ui.transform.Find("HighscoreText").gameObject.GetComponent<Text>();
    58.         levelOverlay = ui.transform.Find("LevelOverlay").gameObject;
    59.         levelText = levelOverlay.transform.Find("LevelText").gameObject.GetComponent<Text>();
    60.         gameOverOverlay = ui.transform.Find("GameOverOverlay").gameObject;
    61.         gameOverText = gameOverOverlay.transform.Find("GameOverText").gameObject.GetComponent<Text>();
    62.         levelText.text = "Day " + level;
    63.         if (newHighscore)
    64.             highscoreText.text = "New Highscore!";
    65.         else
    66.             highscoreText.text = "Highscore: " + highscore;
    67.         enemies.Clear();
    68.         boardManager.SetupScene(level);
    69.         Invoke("HideLevelDisplay", levelStartDelay);
    70.     }
    71.  
    72.     void HideLevelDisplay()
    73.     {
    74.         levelOverlay.SetActive(false);
    75.         doingSetup = false;
    76.     }
    77.  
    78.     public void NextLevel()
    79.     {
    80.         if (level == 1)
    81.             SceneManager.sceneLoaded += OnSceneLoaded;
    82.         SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex, LoadSceneMode.Single);
    83.     }
    84.  
    85.     public void GameOver()
    86.     {
    87.         enabled = false;
    88.         SoundManager.instance.musicSource.Stop();
    89.         gameOverText.text = "You survived " + level + " days.";
    90.         gameOverOverlay.SetActive(true);
    91.         SoundManager.instance.Play(gameOverClip);
    92.     }
    93.  
    94.     void OnEnable()
    95.     {
    96.         if (level > 1)
    97.             SceneManager.sceneLoaded += OnSceneLoaded;
    98.     }
    99.  
    100.     void OnDisable()
    101.     {
    102.         SceneManager.sceneLoaded -= OnSceneLoaded;  
    103.     }
    104.  
    105.     void OnDestroy()
    106.     {
    107.         PlayerPrefs.SetInt("Highscore", highscore);
    108.     }
    109.  
    110.     public void AddEnemy(Enemy enemy)
    111.     {
    112.         enemies.Add(enemy);
    113.     }
    114.  
    115.     IEnumerator MoveEnemies()
    116.     {
    117.         areEnemiesMooving = true;
    118.         yield return new WaitForSeconds(turnDelay);
    119.  
    120.         foreach (var enemy in enemies)
    121.         {
    122.             enemy.MoveEnemy();
    123.             yield return new WaitForSeconds(enemy.moveTime);
    124.         }
    125.  
    126.         areEnemiesMooving = false;
    127.         isPlayersTurn = true;
    128.     }
    129.  
    130.     public void Update()
    131.     {
    132. #if UNITY_STANDALONE
    133.         if (Input.GetKeyDown(KeyCode.Escape))
    134.             Application.Quit();
    135. #endif
    136.         if (doingSetup || isPlayersTurn || areEnemiesMooving)
    137.             return;
    138.         StartCoroutine(MoveEnemies());
    139.     }
    140. }
    141.  
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.SceneManagement;
    3.  
    4. public class Loader : MonoBehaviour
    5. {
    6.     public GameObject gameManager;
    7.     public GameObject soundManager;
    8.  
    9.     void Awake()
    10.     {
    11.         if (GameManager.instance == null)
    12.             Instantiate(gameManager);
    13.         if (SoundManager.instance == null)
    14.             Instantiate(soundManager);
    15.     }
    16.  
    17.     public void Restart()
    18.     {
    19.         Destroy(GameManager.instance.gameObject);
    20.         Destroy(SoundManager.instance.gameObject);
    21.         GameManager.instance = null;
    22.         SoundManager.instance = null;
    23.         SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex, LoadSceneMode.Single);
    24.     }
    25. }
     
  30. R3turnz

    R3turnz

    Joined:
    Sep 5, 2017
    Posts:
    2
    I just tried to built the game for Android and everything works great except in portrait mode the game is not scaled and only the half is visible. How could this be fixed?
     
  31. martin_binder

    martin_binder

    Joined:
    Sep 12, 2017
    Posts:
    1
    Hello Unity Community!

    First of all I want to say thank you for the great tutorial! I am new to Unity and that the 2D Roguelike Tutorial is my first project in Unity!

    To explain my problem:
    I want to program a game for the Web Browser, so I decided to take this tutorial as my template. I started to become an overview to the project and then i clicked me thoroughly through the project. In the next step, I started the game in the Unity Editor and everything was ok. The character was moving correctly in all directions and everything worked.
    In the second step, I exported the game via WebGL to my Web Browser (Chrome 60 and Opera 47), to see if everything is working correct in the Web Browser. The game was built and at the beginning I thought everything was ok, but it wasn't. When the game started in the Web Browser the graphics loaded correctly, but the character couldn't be moved in any direction.
    Back to the Unity Editor, I wanted to start the game again and it was the same problem as in the Web Browser! I couldn't move the character in any direction. I also started it on my XAMPP Apache Webserver, but there was also the same problem.

    Does anybody have the same problem with the WebGL export or does anybody know how this problem could be fixed?

    Kind regards,
    Martin
     
  32. TharosTheDragon

    TharosTheDragon

    Joined:
    Sep 2, 2017
    Posts:
    21
    When I tested the enemy animator controller and tried clicking the trigger, I noticed that it would stay checked until I clicked it again, rather than reverting back automatically like a trigger should. That is to say, it seemed to be behaving more like a bool than a trigger. The triggers in the player animator controller seemed to be working just fine though. Then I noticed that there was a progress bar under the animations in the animator window that showed which animation was playing, and this progress bar was only present when the triggers were working correctly. However, the next time I tested it and I switched between the enemy animator controller and the player animator controller, the player animator controller began to display the same faulty behavior.

    Does anyone know how to fix this? It seems the problem was present in the tutorial video as well, when the enemy animations were tested.
     
  33. TharosTheDragon

    TharosTheDragon

    Joined:
    Sep 2, 2017
    Posts:
    21
    Is there any way to set the blockingLayer property of MovingObject instances by getting the layer of their game objects so that it doesn't have to be set as a public property of the script component?
     
  34. AstralEQ

    AstralEQ

    Joined:
    Oct 26, 2017
    Posts:
    3
    Trying to get through the tutorial, seems to be working just fine, except I can't proceed past #4 (GameManager) because this happens...



    It can be opened as if it's a script, I fill it out, but after that, it doesn't seem to want to cooperate like a script.


    Also, in the Loader.cs:
    Code (CSharp):
    1.      public GameObject gameManager;
    2.  
    3.     // Use this for initialization
    4.   void Awake ()
    5.     {
    6.         if (gameManager.instance == null) // GameObject does not contain a definition for "instance"
    7.             Instantiate(GameManager); //GameManager is a type, which is not valid in the given context.
    8.     }
     
  35. Deleted User

    Deleted User

    Guest

    In your loader I think you've got your gameManager object and GameManager.instance the wrong way round:
    Code (CSharp):
    1.      public GameObject gameManager;
    2.  
    3.     // Use this for initialization
    4.   void Awake ()
    5.     {
    6.         if (GameManager.instance == null) // Change this to GameManager.instance (as its a static variable)
    7.             Instantiate(gameManager); // Change this to 'gameManager' as it expects an object as opposed to a static variable type
    8.     }
    [/QUOTE]
     
  36. Moeyz1

    Moeyz1

    Joined:
    Nov 4, 2017
    Posts:
    1
    Hey Unity ive gotten this error. Its coming from the completed project (Im working on the different scene which i named MZRougeMain) where it uses this depreciated code>>, static private void OnSceneLoaded(Scene arg0, LoadSceneMode arg1).
    this was just finishing pt 1 of Architecture & polish.

    Bug im getting its automatically making me start from Day 2 and jumps me straight to Day 4 with my foodpoints as -1. Should I just delete the Old project with its scripts. RogueTutorialError.png
     
    FlamingVorpalCow and Martinz like this.
  37. TharosTheDragon

    TharosTheDragon

    Joined:
    Sep 2, 2017
    Posts:
    21
    [/QUOTE]

    You also gotta put your code inside a class.

    Code (CSharp):
    1. using UnityEngine;
    2. public class GameManager : MonoBehaviour
    3.     public GameObject gameManager;
    4.     private static GameManager instance;
    5.     // Use this for initialization
    6.     void Awake ()
    7.     {
    8.         if (instance == null) // Change this to instance
    9.             instance = Instantiate(gameManager); // Change this to 'gameManager' as it expects an object as opposed to a static variable type
    10.     }
    11. }
     
  38. Martinz

    Martinz

    Joined:
    Nov 21, 2012
    Posts:
    1
    Same thing! The 2d Roguelike Update Guide pdf file is wrong, the solution doesn't work.
     
  39. Klausiboy

    Klausiboy

    Joined:
    Aug 29, 2017
    Posts:
    4
    Ok, so I tried out the tutorial, downloaded the assets and started watching the video. I followed instructions, but when I playtest the game, my player sprite is insanely blurry. I don't think I've done anything other from what I've been told. Any ideas why I get that issue and how to fix it?
    Also, this is my first post, so I'm really sorry if I've done it the wrong way, don't go to forums that often
     
  40. Klausiboy

    Klausiboy

    Joined:
    Aug 29, 2017
    Posts:
    4
    Never mind, I had moved around some of the panels in unity to have a better view (I have a pretty small screen), and so my gameview had gotten quite small. That, for some reason blurred the sprites on playback, but when I moved the gamewindow to a better place it got fixed
     
  41. underskyrim

    underskyrim

    Joined:
    Nov 26, 2017
    Posts:
    1
    I am learning the 2D rougelike tutorial for one weeks ,but I have a trouble in the process now . after I finish the 2 unit,i try to run the unity project,however i find only one half prefabs have displayed in the floor map and the other half can not see any prefabs else the enemy prefabs...So,what should I do for this condition?
     
  42. RidiculousName_

    RidiculousName_

    Joined:
    Dec 14, 2017
    Posts:
    1
    Hello Matthew,

    I like your tutorial, but when I try to view the PlayerIdle animation for the first time on video #2: Animations, I can't get the animation to play. The screen just stays blue when I click the play button. Please let me know what I can do, thank you.
     
  43. jamesbarn35

    jamesbarn35

    Joined:
    Dec 19, 2017
    Posts:
    1
    Awesome this worked. Thanks.
     
  44. Tom_Wolland

    Tom_Wolland

    Joined:
    Dec 21, 2017
    Posts:
    1
    Hello people,

    Anyone can help with this error? - Rogue_Like TUTORIAL -

    `Enemy.onCantMove<T>(T)' is marked as an override but no suitable method found to override

    For some reason the game doesn't want to run because of the above suitability of method! Can anyone explain why this is and how do I solve this for the rest of my scripting days please.

    Thank you.

    Tom.

    p.s. total newbie to scripting in MonoDevelop and in the coding world.
    p.s.s. thanks to who ever made these - have been enjoying my time.
     
  45. bernhardoj

    bernhardoj

    Joined:
    Dec 22, 2017
    Posts:
    38
    Hi, I have some problems with this tutorial.
    I'm still newbie in Unity so if you mind please help me :).

    From the image I provided, there are 2 problems i encountered.
    Btw, I am at Step 5 of 14 from the tutorial.

    test.png

    I was editing a GameManager Script when I got this error.
    1. OutOfMemoryException: Out of memory. I had highlighted it on the image.
    2. On Game Scene, it seems that there is a slit on my ground. And the enemy, foods, and walls not appeared.

    Please help me fix this ASAP :).
     
  46. disrupter52

    disrupter52

    Joined:
    Nov 20, 2012
    Posts:
    4
    Good Morning everyone

    I am getting an error in the Move Objects video. Error attached:


    Full code for the script is here.

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

    Attached Files:

  47. gwnguy

    gwnguy

    Joined:
    Apr 25, 2017
    Posts:
    144

    Remove the semi colon from the of line 54
    from this: where T: Component;
    to this: where T: Component

    Check spelling at line line 68
    from this: protected abstract void OnCantMove <T> (T compoonent)
    to this: protected abstract void OnCantMove <T> (T component)
    (ie, remove extra "o" in compoonent)
     
  48. disrupter52

    disrupter52

    Joined:
    Nov 20, 2012
    Posts:
    4
    @gwnguy thank you so much! that solved it. I was going blind looking for errors and things. Sometimes you just need a 2nd pair of eyes looking at it.

    Thanks again.
     
  49. disrupter52

    disrupter52

    Joined:
    Nov 20, 2012
    Posts:
    4
    New Question, related to the old one. I made the changes suggested by @gwnguy and now, on the Enemy script, i get the following error: 'Enemyt.OnCantMove<T>(T)': cannot change access modifiers when overriding 'protected' inherited member 'MovingObject.OnCantMove<T>(T)'

    The function attempting to override in the Enemy script:

    Code (CSharp):
    1. public override void OnCantMove <T> (T component)
    2.     {
    3.         Player hitPlayer = component as Player;
    4.         hitPlayer.LoseFood (playerDamage);
    5.         animator.SetTrigger ("enemyAttack");
    6.     }
     
  50. gwnguy

    gwnguy

    Joined:
    Apr 25, 2017
    Posts:
    144
    Here is my code from Enemy.cs:
    Code (csharp):
    1.  
    2.     protected override void OnCantMove<T>(T component)
    3.     {
    4.         Player hitPlayer = component as Player;
    5.         hitPlayer.LoseFood(playerDamage);
    6.         animator.SetTrigger("EnemyAttack");
    7.     }
    8.  
    Note it is protected override
    You may also wish to verify your
    animator.SetTrigger("EnemyAttack");
    for the spelling and punctuation of "EnemyAttack" (vs "enemyAttack")

    Finally, there seems to be an errant t in your error message: 'Enemyt.OnCantMove<T>(T)':
    (Enemyt.)
     
Thread Status:
Not open for further replies.