Search Unity

Unity 2D Roguelike: Q&A

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

  1. geodelamano

    geodelamano

    Joined:
    Jun 19, 2019
    Posts:
    2
    Hello, I'm stuck on video 5. I can not reproduce the image of the tutorial:

    When I want to insert my script in the GameObject GameManager I have the two messages below that appears.


    I manage to integrate them since the compenent.
    Code of Board Manager

    using UnityEngine;
    using System;
    using System.Collections.Generic;
    using Random = UnityEngine.Random;


    public class BM : MonoBehaviour
    {
    [Serializable]
    public class Count
    {
    public int minimum;// Valeur minimale pour notre classe Count.
    public int maximum;// Valeur maximale pour notre classe Count.

    public Count(int min, int max)
    {
    minimum = min;
    maximum = max;
    }
    public int columns = 8;
    public int rows = 8;
    public int Count wallCount = new Count(5,9);
    public int foodCount = new Count(1, 5);
    public GameObject exit;

    public GameObject[] floorTiles;
    public GameObject[] wallTiles;
    public GameObject[] foodTiles;
    public GameObject[] enemyTiles;
    public GameObject[] outerWallTiles;

    private Transform boardHolder;
    private List<Vector3> gridPositions = new List<Vector3>();


    void InitialiseList()
    {
    gridPositions.Clear();
    for (int x = 1; x < columns - 1; x++)
    {
    for (int y = 1; y < rows - 1; y++) // Par rangées
    {
    gridPositions.Add(new Vector3(x, y, 0f));
    }
    }
    }
    void BoardSetup()
    {
    boardHolder = new GameObject("Board").transform;
    void Start()
    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);
    }
    }
    }
    Vector3 RandomPosition()
    {
    int randomIndex = Random.Range(0, gridPositions.Count);
    Vector3 randomPosition = gridPositions[randomIndex];
    gridPositions.RemoveAt(randomIndex);
    return randomPosition;
    }
    void LayoutObjectAtRandom(GameObject[] tileArray, int minimum, int maximum)
    {
    int objectCount = Random.Range(minimum, maximum + 1);
    for (int i = 0; i < objectCount; i++)
    {
    Vector3 randomPosition = RandomPosition();
    GameObject tileChoice = tileArray[Random.Range(0, tileArray.Length)];
    Instantiate(tileChoice, randomPosition, Quaternion.identity);
    }
    }
    public void SetupScene(int level)
    {
    BoardSetup();
    InitialiseList();
    LayoutObjectAtRandom(wallTiles, wallCount.minimum, wallCount.maximum);
    LayoutObjectAtRandom(foodTiles, foodCount.minimum, foodCount.maximum);
    int enemyCount = (int)Mathf.Log(level, 2f);
    LayoutObjectAtRandom(enemyTiles, enemyCount, enemyCount);
    Instantiate(exit, new Vector3(columns - 1, rows - 1, 0f), Quaternion.identity);
    }
    }
    }

    Code of Game Manager

    using UnityEngine;
    using System.Collections;

    public class GM : MonoBehaviour
    {
    public BM boardScript;

    private int level = 3;

    void Awake()
    {
    boardScript = GetComponent<BoardManager>();
    InitGame();
    }
    void Initgame()
    {
    boardScript.SetupScene(level);
    }
    }

     
  2. geodelamano

    geodelamano

    Joined:
    Jun 19, 2019
    Posts:
    2
     
  3. SecondDegreePerm

    SecondDegreePerm

    Joined:
    Jul 2, 2017
    Posts:
    35
    Hi all,

    I am currently on video 5. When I build the project, which occurs at 3:00 in the video, unity freezes giving no indication as to what could be wrong. There is no error output, no way to cancel the build apart from ending it on task manager. What I have noticed is that the memory the unity editor uses continually increases after it crashes. Does this suggest some kind of memory leak? Perhaps caused by a faulty loop? Even if this is the case, is there any way to access any kind of error logs for more specific debugging? It feels kind of nebulous that the only feedback I am getting from the editor is that nothing is responding!

    Thanks in advance
     
  4. SecondDegreePerm

    SecondDegreePerm

    Joined:
    Jul 2, 2017
    Posts:
    35
    I ran a diff on the example code and the code I wrote. The only difference was for one of the instantiate calls I used a capital F instead of a lower case f. I have now changed that and I am experiencing the same issue. Everything else is white space difference. I am quite stuck as to why i am experiencing this issue, even more so as I see how to access any logging! It feels like it should be quite important for some kind of logging file to be produced.

    I am using 2019.1.2f1 for this project.
     
  5. EoinTrainor11

    EoinTrainor11

    Joined:
    Apr 7, 2017
    Posts:
    1
    Hi guys.

    Running into an issue here where I can't seem to move my character at all for some reason. Checked a few common issues with this so I know the PlayerTurn variable is set to true, and that input is being detected and a new position is being found. I just think the moving coroutine isn't being called.

    issue.png
    Moving Object:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public abstract class MovingObject : MonoBehaviour
    6. {
    7.  
    8.     public float moveTime = 0.1f;
    9.     public LayerMask blockingLayer;
    10.  
    11.     private BoxCollider2D boxCollider;
    12.     private Rigidbody2D rb2d;
    13.     private float inverseMoveTime;
    14.  
    15.     // Start is called before the first frame update
    16.     protected virtual void Start()
    17.     {
    18.         boxCollider = GetComponent<BoxCollider2D>();
    19.         rb2d = GetComponent<Rigidbody2D>();
    20.         inverseMoveTime = 1f / moveTime;
    21.     }
    22.  
    23.     protected bool Move(int xDir, int yDir, out RaycastHit2D hit2D)
    24.     {
    25.         Vector2 startPos = transform.position;
    26.         Vector2 endPos = startPos + new Vector2(xDir, yDir);
    27.  
    28.         boxCollider.enabled = false;
    29.         hit2D = Physics2D.Linecast(startPos, endPos, blockingLayer);
    30.         boxCollider.enabled = true;
    31.  
    32.         if(hit2D.transform == null)
    33.         {
    34.             //the paramater may be wrong here.....
    35.             StartCoroutine(SmoothMove(endPos));
    36.             Debug.Log("the newPosition is " + endPos);
    37.             return true;
    38.         }
    39.         return false;
    40.     }
    41.  
    42.     protected IEnumerator SmoothMove (Vector3 end)
    43.     {
    44.         float sqrRemainingDist = (transform.position - end).sqrMagnitude;
    45.  
    46.         while (sqrRemainingDist > float.Epsilon)
    47.         {
    48.             Vector3 newPostion = Vector3.MoveTowards(rb2d.position, end, inverseMoveTime * Time.deltaTime);
    49.  
    50.             rb2d.MovePosition(newPostion);
    51.  
    52.             sqrRemainingDist = (transform.position - end).sqrMagnitude;
    53.  
    54.             yield return null;
    55.         }
    56.     }
    57.  
    58.     protected virtual void AttemptMove <T> (int xDir, int yDir)
    59.         where T : Component
    60.     {
    61.         RaycastHit2D hit;
    62.         bool canMove = Move(xDir, yDir, out hit);
    63.  
    64.         if (hit.transform == null)
    65.             return;
    66.  
    67.         T hitComponent = hit.transform.GetComponent<T>();
    68.  
    69.         if (!canMove && hitComponent != null)
    70.             OnCantMove(hitComponent);
    71.  
    72.        
    73.        
    74.     }
    75.  
    76.     protected abstract void OnCantMove<T>(T component)
    77.         where T : Component;
    78.    
    79.  
    80.    
    81. }
    82.  
    Player Script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class PlayerScript : MovingObject
    7. {
    8.     public int wallDamage = 1;
    9.  
    10.     public int foodPoint = 10;
    11.     public int drinkPoint = 20;
    12.  
    13.     public float restartDelay = 1;
    14.  
    15.     private Animator animator;
    16.     private int foodScore;
    17.  
    18.     // Start is called before the first frame update
    19.     protected override void Start()
    20.     {
    21.         animator = GetComponent<Animator>();
    22.         foodScore = GameManager.instance.playerFoodPoints;
    23.         base.Start();
    24.  
    25.        
    26.     }
    27.  
    28.     private void OnDisable()
    29.     {
    30.         GameManager.instance.playerFoodPoints = foodScore;
    31.     }
    32.  
    33.    
    34.     void Update()
    35.     {
    36.         if (!GameManager.instance.playersTurn)
    37.             return;
    38.  
    39.         int horizontal = 0;
    40.         int vertical = 0;
    41.  
    42.         horizontal = (int)Input.GetAxisRaw("Horizontal");
    43.         vertical = (int)Input.GetAxisRaw("Vertical");
    44.  
    45.         if (horizontal != 0)
    46.             vertical = 0;
    47.  
    48.         if (horizontal != 0 || vertical != 0)
    49.             AttemptMove<Wall>(horizontal, vertical);
    50.  
    51.        
    52.         Debug.Log((int)Input.GetAxisRaw("Horizontal"));
    53.        
    54.     }
    55.  
    56.     protected override void AttemptMove<T>(int xDir, int yDir)
    57.     {
    58.         foodScore--;
    59.         base.AttemptMove<T>(xDir, yDir);
    60.  
    61.         RaycastHit2D hit;
    62.         CheckIfGameOver();
    63.         //GameManager.instance.playersTurn = false;
    64.     }
    65.  
    66.     private void OnTriggerEnter2D(Collider2D collision)
    67.     {
    68.         if(collision.tag == "Exit")
    69.         {
    70.             Invoke("Restart", restartDelay);
    71.             enabled = false;
    72.  
    73.         }
    74.  
    75.         else if (collision.tag == "Food")
    76.         {
    77.             foodScore += foodPoint;
    78.             collision.gameObject.SetActive(false);
    79.         }
    80.  
    81.         else if (collision.tag == "Soda")
    82.         {
    83.             foodScore += drinkPoint;
    84.             collision.gameObject.SetActive(false);
    85.         }
    86.     }
    87.  
    88.     protected override void OnCantMove<T>(T component)
    89.     {
    90.         Wall hitWall = component as Wall;
    91.         hitWall.DamageWall(wallDamage);
    92.         animator.SetTrigger("Chopping");
    93.     }
    94.  
    95.     private void Restart()
    96.     {
    97.         SceneManager.LoadScene(0);
    98.     }
    99.  
    100.     public void LoseFood(int lossAmount)
    101.     {
    102.         animator.SetTrigger("Hit");
    103.         foodScore -= lossAmount;
    104.         CheckIfGameOver();
    105.     }
    106.  
    107.     private void CheckIfGameOver()
    108.     {
    109.         if (foodScore <= 0)
    110.             GameManager.instance.GameOver();
    111.  
    112.        
    113.     }
    114.  
    115.    
    116. }
    117.  
    GameManager:
    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 = 0.1f;
    8.  
    9.     public static GameManager instance = null;
    10.  
    11.     public BoardManager boardScript;
    12.  
    13.     [SerializeField]
    14.     private int level = 1;
    15.     //private List<EnemyScript> enemies;
    16.     private bool enemiesMoving;
    17.     public int playerFoodPoints = 100;
    18.     [HideInInspector]
    19.     public bool playersTurn = true;
    20.  
    21.    
    22.    
    23.     void Awake()
    24.     {
    25.         if (instance == null)
    26.         {
    27.             instance = this;
    28.         }
    29.         else if (instance != this)
    30.         {
    31.             Destroy(gameObject);
    32.         }
    33.  
    34.         DontDestroyOnLoad(gameObject);
    35.         //enemies = new List<EnemyScript>();
    36.         boardScript = GetComponent<BoardManager>();
    37.         initGame();
    38.     }
    39.  
    40.     void initGame()
    41.     {
    42.       //  enemies.Clear();
    43.         boardScript.SetUpScene(level);
    44.     }
    45.  
    46.     public void GameOver()
    47.     {
    48.         enabled = false;
    49.     }
    50.     // Update is called once per frame
    51.     void Update()
    52.     {
    53.  
    54.         Debug.Log("The playersTurn variable is" + playersTurn);
    55.        
    56.  
    57.         if (playersTurn || enemiesMoving)
    58.             return;
    59.  
    60.         //StartCoroutine(MoveEnemies());
    61.     }
    62.  
    63.     /*public void AddEnemyToList(EnemyScript enemyScript)
    64.     {
    65.         enemies.Add(enemyScript);
    66.     }*/
    67.  
    68.    /* IEnumerator MoveEnemies()
    69.     {
    70.         enemiesMoving = true;
    71.         yield return new WaitForSeconds(turnDelay);
    72.         if(enemies.Count == 0)
    73.         {
    74.             yield return new WaitForSeconds(turnDelay);
    75.         }
    76.  
    77.         for (int i = 0; i < enemies.Count; i++)
    78.         {
    79.             enemies[i].MoveEnemy();
    80.             yield return new WaitForSeconds(enemies[i].MoveTime);
    81.         }
    82.  
    83.         playersTurn = true;
    84.         enemiesMoving = false;
    85.  
    86.     }*/
    87. }
    88.  
    Thanks for any help guys.
     
  6. TheCopper

    TheCopper

    Joined:
    Mar 4, 2016
    Posts:
    1
    Greetings. You should check if there is any part of your code in your scripts that causes an infinite loop, such as a loop that never returns. At least for me it happened when I accidentally used a for -loop incorrectly, causing Unity to just keep repeating and repeating it with no result, ultimately crashing my Unity.
     
  7. icetear

    icetear

    Joined:
    Dec 29, 2011
    Posts:
    23
    Hello Matthew,

    thank you very much for this nice little Dungeon Crawler Kickstart. I was so inspired by it that I had to take it some steps further - and so "Lootbox RPG" was brought to life! :) Without the Roguelike Tutorial, I would never have made it.

    So thanks again!
    kind regards
    Mario
     
  8. Naiskick

    Naiskick

    Joined:
    Oct 14, 2018
    Posts:
    12
    Hi everyone.
    I have a situation: my player can move to the sprite which the enemy stands on it.
    The Layer of player and enemys have been selleted to "blocking Layer" .And I have uncheck their "Is Trigger" option.
    How can I solve this problem? Any help will be appreciated.




    Here is my code.


    Moving Object script
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public abstract class MovingObject : MonoBehaviour
    6. {
    7.     // Start is called before the first frame update
    8.  
    9.     public float moveTime = 0.1f;
    10.     public LayerMask blockingLayer;
    11.  
    12.     private BoxCollider2D boxCollider;
    13.     private Rigidbody2D rb2D;
    14.     private float inverseMoveTime;
    15.  
    16.  
    17.     protected virtual void Start()
    18.     {
    19.         boxCollider = GetComponent<BoxCollider2D>();
    20.  
    21.         rb2D = GetComponent<Rigidbody2D>();
    22.  
    23.         inverseMoveTime = 1f / moveTime;
    24.     }
    25.  
    26.  
    27.     protected bool Move(int xDir, int yDir, out RaycastHit2D hit)
    28.     {
    29.         Vector2 start = transform.position;
    30.  
    31.         Vector2 end = start + new Vector2(xDir, yDir);
    32.  
    33.         boxCollider.enabled = false;
    34.  
    35.         hit = Physics2D.Linecast(start, end, blockingLayer);
    36.  
    37.         boxCollider.enabled = true;
    38.  
    39.         if (hit.transform == null)
    40.         {
    41.             StartCoroutine(SmoothMovement(end));
    42.  
    43.             return true;
    44.         }
    45.         return false;
    46.     }
    47.     protected IEnumerator SmoothMovement (Vector3 end)
    48.      {
    49.         float sqrRemainingDistance = (transform.position - end).sqrMagnitude;
    50.  
    51.         while(sqrRemainingDistance > float.Epsilon)
    52.             {
    53.                 Vector3 newPostion = Vector3.MoveTowards(rb2D.position, end, inverseMoveTime * Time.deltaTime);
    54.  
    55.                 rb2D.MovePosition(newPostion);
    56.  
    57.                 sqrRemainingDistance = (transform.position - end).sqrMagnitude;
    58.  
    59.                 yield return null;
    60.  
    61.             }
    62.       }
    63.  
    64.     protected virtual void AttemptMove<T>(int xDir,int yDir)
    65.  
    66.         where T :Component
    67.     {
    68.  
    69.         RaycastHit2D hit;
    70.  
    71.         bool canMove = Move(xDir, yDir, out hit);
    72.  
    73.         if (hit.transform == null)
    74.  
    75.             return;
    76.  
    77.         T hitComponent = hit.transform.GetComponent<T>();
    78.  
    79.         if (!canMove && hitComponent != null)
    80.  
    81.             OnCantMove(hitComponent);
    82.     }
    83.  
    84.     protected abstract void OnCantMove<T>(T component)
    85.  
    86.        where T : Component;
    87.   }
    88.  
    89.  
    Thanks again!!
     
    Last edited: Aug 3, 2019
  9. LoneSurvivor82

    LoneSurvivor82

    Joined:
    Aug 17, 2019
    Posts:
    3
    Same here, somehow the values have been change to same 0.0001 in both Prefabs... changed them to 1 and it was fixed. Thank you for pointing on that. If you haven't posted this, I sure would have search for another hour... o_O
     
  10. reptiliancadet54

    reptiliancadet54

    Joined:
    Jan 31, 2018
    Posts:
    3
    Maybe it has something to do with your player? Check your player's boxcollider2d and rigidbody
     
  11. LoneSurvivor82

    LoneSurvivor82

    Joined:
    Aug 17, 2019
    Posts:
    3
    Hi everyone,

    I don't understand why GameManager becomes a prefab in this tutorial. Why can't it exist as an instance in the Hierarchy? Is there a Best Practice when to use GameManager as Prefab and instantiate it programmatically and when it's okay to use it directly in the Hierarchy?

    Thank you very much :)
     
  12. awillshire

    awillshire

    Joined:
    Apr 29, 2014
    Posts:
    17
    Hi All,

    Has anybody tried reworking this using the 2D Tilemaps that unity now has? The tutorial was created before the 2D Tilemaps features were available, so I'm curious if anybody has used them on this and any thoughts/learnings/suggestions that they might have :)
    '
    Cheers!
     
  13. NapoleonicMonkey

    NapoleonicMonkey

    Joined:
    Oct 1, 2019
    Posts:
    2
    Really dumb question: first time with unity and finished Video 11. Should have a mostly complete game, only glitch is I don't have a player on the screen. Skimming the completed boardmanager and gamemanager scripts and he is never created in there. How do I do it? Did I miss a step in a much earlier video?
     
  14. awillshire

    awillshire

    Joined:
    Apr 29, 2014
    Posts:
    17
    Hi NapoleonicMonkey,

    It's been a while since I did the tutorial, but if I remember correctly I think the Player GameObject is one of the few things that remains in the scene after you create the prefab for it. Almost everything else gets deleted & created within scripts, but the player stays there.

    If you check the tutorial videos (have a look at #12) I think you might see the Player sitting there in the scene hierarchy. But apologies if I'm wrong!

    Cheers!
     
  15. NapoleonicMonkey

    NapoleonicMonkey

    Joined:
    Oct 1, 2019
    Posts:
    2
    Thanks, that narrows it down. I've got the player in my scene, he's just not displaying or doing anything so got to see if there's something else missing.

    However I can't fiddle with it now, as Unity is crashing every time I open the project. I don't know if it is because Scavengers is based on an old version of Unity, or there's some other issue. Either way it is frustrating.

    Looks like it is crashing while updating packages for some reason, after shaders?


    Updating Packages/com.unity.learn.iet-framework/Framework/Interactive Tutorials/GUI/New Textures/Task_Todo.png - GUID: 185156b425ccf41ed8c47a4c7c6d397d...
    done. [Time: 21.998332 ms]
    Updating Packages/com.unity.postprocessing/PostProcessing/Shaders/Builtins/DepthOfField.shader - GUID: 0ef78d24e85a44f4da9d5b5eaa00e50b...
    done. [Time: 1297.593278 ms]
    Updating Assets/UTech/MG-Platformer/TextMesh Pro/Resources/Shaders/TMP_Bitmap.shader - GUID: 128e987d567d4e2c824d754223b3f3b0...
    done. [Time: 76.405739 ms]
    Updating Packages/com.unity.uiwidgets/Runtime/Resources/UIWidgets_canvas_tex.shader - GUID: 1702a648d08de40d9aacd9bbab1188b3...
    done. [Time: 3055.449550 ms]
    Updating Packages/com.unity.postprocessing/PostProcessing/Shaders/Debug/Histogram.compute - GUID: 18183ebfeeab97749b43e38b928604a7...
    Launched and connected shader compiler UnityShaderCompiler.exe after 0.03 seconds
    done. [Time: 230.805448 ms]
    Updating Assets/UTech/MG-Platformer/ModAssets/ModResources/Shaders/SpritesHue.shader - GUID: 1af7aa0c4bbc40243accca84055907cc...
    done. [Time: 63.398833 ms]
    Updating Assets/UTech/MG-Platformer/TextMesh Pro/Resources/Shaders/TMP_Bitmap-Mobile.shader - GUID: 1e3b057af24249748ff873be7fafee47...
    done. [Time: 194.424512 ms]
    Updating Packages/com.unity.postprocessing/PostProcessing/Shaders/Builtins/MotionBlur.shader - GUID: 2c459b89a7c8b1a4fbefe0d81341651c...
    done. [Time: 240.896320 ms]
    Updating Packages/com.unity.postprocessing/PostProcessing/Shaders/Debug/Waveform.shader - GUID: 3020ac7ece79a7f4eb789a236f8bd6c5...
    done. [Time: 67.972802 ms]
    Updating Packages/com.unity.postprocessing/PostProcessing/Shaders/Builtins/Texture3DLerp.compute - GUID: 31e9175024adfd44aba2530ff9b77494...
    Launched and connected shader compiler UnityShaderCompiler.exe after 0.02 seconds
    Launched and connected shader compiler UnityShaderCompiler.exe after 0.03 seconds
    done. [Time: 107.725630 ms]
    Updating Packages/com.unity.postprocessing/PostProcessing/Shaders/Builtins/AutoExposure.compute - GUID: 34845e0ca016b7448842e965db5890a5...
    Launched and connected shader compiler UnityShaderCompiler.exe after 0.03 seconds
    done. [Time: 985.483547 ms]
    Updating Packages/com.unity.postprocessing/PostProcessing/Shaders/Builtins/MultiScaleVORender.compute - GUID: 34a460e8a2e66c243a9c12024e5a798d...
    Launched and connected shader compiler UnityShaderCompiler.exe after 0.03 seconds
    Crash!!!
    A crash has been intercepted by the crash handler. For call stack and other details, see the latest crash report generated in:
    * C:/Users/Dylan/AppData/Local/Temp/Unity/Editor/Crashes
    Launched and connected shader compiler UnityShaderCompiler.exe after 0.03 seconds