Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    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. geodelamano

    geodelamano

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

    SecondDegreePerm

    Joined:
    Jul 2, 2017
    Posts:
    42
    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
     
  3. SecondDegreePerm

    SecondDegreePerm

    Joined:
    Jul 2, 2017
    Posts:
    42
    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.
     
  4. 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.
     
  5. TheCopper

    TheCopper

    Joined:
    Mar 4, 2016
    Posts:
    5
    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.
     
  6. icetear

    icetear

    Joined:
    Dec 29, 2011
    Posts:
    24
    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
     
  7. 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
  8. LoneSurvivor82

    LoneSurvivor82

    Joined:
    Aug 17, 2019
    Posts:
    42
    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
     
  9. Khan_Yasin

    Khan_Yasin

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

    LoneSurvivor82

    Joined:
    Aug 17, 2019
    Posts:
    42
    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 :)
     
  11. awillshire

    awillshire

    Joined:
    Apr 29, 2014
    Posts:
    20
    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!
     
    Goriburne7 likes this.
  12. 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?
     
  13. awillshire

    awillshire

    Joined:
    Apr 29, 2014
    Posts:
    20
    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!
     
  14. 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
     
  15. BrewNCode

    BrewNCode

    Joined:
    Feb 17, 2017
    Posts:
    372
    Loader won't recognize my GameManager static variable. got an error in the Loader script.

    GameManager:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. namespace Completed
    6. {
    7.     public class GameManager : MonoBehaviour
    8.     {
    9.         #region Variables
    10.         public static GameManager instance = null;      // Static instance of GameManager which allows it to bne accessed
    11.  
    12.         private BoardManager boardScript;               // Store a reference to our BoardManager which will set up the level.
    13.  
    14.         private int level = 3;      // Current level numbner, experessed in game as "Day 1"
    15.  
    16.  
    17.         #endregion Variables
    18.  
    19.  
    20.         private void Awake()
    21.         {
    22.             // Check if instance alrfeady exists
    23.             if(instance == null)
    24.             {
    25.                 // if not, set instance to this
    26.                 instance = this;
    27.             }
    28.             else if(instance != this)
    29.             {
    30.                 // Then destroy this. This enforeces our singleton pattern, meaning there can only ever be one instance of a GameManager.
    31.                 Destroy(gameObject);
    32.             }
    33.  
    34.             // Sets this to not be destroyed when reloading scene
    35.             DontDestroyOnLoad(gameObject);
    36.  
    37.             // Get a component reference to the attached BoardManager script.
    38.             boardScript = GetComponent<BoardManager>();
    39.  
    40.             // Call the InitGame function to initialize the first level
    41.             InitGame();
    42.         }
    43.  
    44.         void InitGame()
    45.         {
    46.             // Call the SetupScene function of the BoardManager scripot, pass it current level number.
    47.             boardScript.SetupScene(level);
    48.         }
    49.  
    50.  
    51.  
    52.  
    53.  
    54.     } // main class
    55. }
    56.  
    Loader:
    (Error on line if(GameManager.instance == null))
    Code (CSharp):
    1. using System.Collections.Generic;
    2. using UnityEngine;
    3.  
    4. public class Loader : MonoBehaviour
    5. {
    6.     #region Vartiables
    7.     public GameObject gameManager;      // Gamemanager prefab to instantiate.
    8.     public GameObject soundManager;     // SoundManager prefab to instantiate.
    9.  
    10.  
    11.     #endregion
    12.     private void Awake()
    13.     {
    14.         // Check if a GameManager has already been assigned to static variable GameManager instance or
    15.         // if it is null.
    16.         if (GameManager.instance == null)
    17.             Instantiate(gameManager);
    18.  
    19.         // Check if a soundmanager has already been assignert to static variable GameManager.instance or
    20.         // if it is still null
    21.         if (soundManager.instance == null)
    22.             Instantiate(soundManager);
    23.     }
    24.  
    25.  
    26.  
    27.  
    28.  
    29. } // main class
    30.  
     
  16. nerf_herder42

    nerf_herder42

    Joined:
    May 16, 2019
    Posts:
    1
    I'm just after writing the enemy script, but my enemy will not move and my player will only move once. I'm not getting any console errors and I've been trying to follow this tutorial exactly, I really can't figure out what's wrong. I'm relatively new to Unity so if anyone could help me figure out what's wrong or has any advice I'd really appreciat it!

    Also, I'm happy to post screenshots and code, but as of now I don't actually know where the problem is to upload an image of it.
     
  17. deibbun

    deibbun

    Joined:
    Feb 7, 2018
    Posts:
    2
     
  18. deibbun

    deibbun

    Joined:
    Feb 7, 2018
    Posts:
    2
    Alpha37,
    I know it's been a few years and you probably don't even care about this post but I am answering so that someone like me will have a better answer. This was the first and only post I found about this complete problem. Everyone will know by now that the OnLevelWasLoaded() function will need to be replaced with OnEnable(), OnDisable(), & OnLevelFinishedLoading() functions. These won't completely fix it. A boolean has to be created to check if this instance is the first run or not and if so, just return. All other runs will increment the level variable. My Unity somehow kept trying to load the Completed package GameManager which was still incorrect instead of my updated GameManager.
     
  19. StikeleatherDillon

    StikeleatherDillon

    Joined:
    Mar 2, 2020
    Posts:
    2
    Hey everybody. Very new to Unity, less new to C#. I am getting the Error "
    NullReferenceException: Object reference not set to an instance of an object
    GameManager.InitGame () (at Assets/Scripts/GameManager.cs:28)
    GameManager.Awake () (at Assets/Scripts/GameManager.cs:23)
    UnityEngine.Object:Instantiate(GameObject)

    Loader:Awake() (at Assets/Scripts/Loader.cs:12" On the tutorial, I am at the step where I should be able to run the game and see a level be created. This is my Code so far, thank you.
    BoardManager.cs
    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Runtime.Serialization;
    4. using System;
    5. using System.Collections.Generic;
    6. using UnityEngine;
    7. using Random = UnityEngine.Random;
    8.  
    9.  
    10. public class BoardManager : MonoBehaviour
    11.     {
    12.     [Serializable]
    13.     public class Count
    14.         {
    15.             public int minimum;
    16.             public int maximum;
    17.  
    18.             public Count(int min, int max)
    19.             {
    20.                 minimum = min;
    21.                 maximum = max;
    22.             }
    23.  
    24.         }
    25.  
    26.         public int columns = 8;
    27.         public int rows = 8;
    28.         public Count wallCount = new Count(8, 9);
    29.         public Count foodCount = new Count(1, 5);
    30.         public GameObject exit;
    31.         public GameObject[] floorTiles;
    32.         public GameObject[] wallTiles;
    33.         public GameObject[] foodTiles;
    34.         public GameObject[] enemyTiles;
    35.         public GameObject[] outerwallTiles;
    36.  
    37.         private Transform boardHolder;
    38.         private List<Vector3> gridPositions = new List<Vector3>();
    39.  
    40.         void InitialiseList()
    41.         {
    42.             gridPositions.Clear();
    43.  
    44.             for (int x = 1; x < columns - 1; x++)
    45.             {
    46.                 for (int y = 1; y < rows; y++)
    47.                 {
    48.                     gridPositions.Add(new Vector3(x, y, 0f));
    49.                 }
    50.             }
    51.         }
    52.  
    53.         void BoardSetup ()
    54.         {
    55.             boardHolder = new GameObject ("Board").transform;
    56.  
    57.             for (int x = -1; x < columns + 1; x++)
    58.             {
    59.                 for (int y = -1; y < rows + 1; y++)
    60.                 {
    61.                     GameObject toInstantiate = floorTiles[Random.Range(0, floorTiles.Length)];
    62.                     if (x == -1 || x == columns || y == -1 || y == rows)
    63.                         toInstantiate = outerwallTiles[Random.Range(0, outerwallTiles.Length)];
    64.  
    65.                     GameObject instance = Instantiate (toInstantiate, new Vector3(x, y, 0f), Quaternion.identity) as GameObject;
    66.  
    67.                     instance.transform.SetParent (boardHolder);
    68.                 }
    69.             }
    70.         }
    71.  
    72.         Vector3 RandomPosition()
    73.         {
    74.             int randomIndex = Random.Range(0, gridPositions.Count);
    75.             Vector3 randomPosition = gridPositions[randomIndex];
    76.             gridPositions.RemoveAt(randomIndex);
    77.             return randomPosition;
    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 = RandomPosition();
    87.                 GameObject tileChoice = tileArray[Random.Range(0, tileArray.Length)];
    88.                 Instantiate(tileChoice, randomPosition, Quaternion.identity);
    89.             }
    90.         }
    91.  
    92.         public void SetupScene(int level)
    93.         {
    94.             BoardSetup();
    95.             InitialiseList();
    96.             LayoutObjectAtRandom(wallTiles, wallCount.minimum, wallCount.maximum);
    97.             LayoutObjectAtRandom(foodTiles, wallCount.minimum, wallCount.maximum);
    98.             int enemyCount = (int)Mathf.Log(level, 2f);
    99.             LayoutObjectAtRandom(enemyTiles, enemyCount, enemyCount);
    100.             Instantiate(exit, new Vector3(columns - 1, rows - 1, 0F), Quaternion.identity);
    101.         }
    102.     }
    GameManager.cs
    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3. using System.Collections.Generic;
    4.  
    5. public class GameManager : MonoBehaviour
    6. {
    7.     public static GameManager instance = null;
    8.     private BoardManager boardScript;
    9.  
    10.     private int level = 3;
    11.  
    12.  
    13.     void Awake()
    14.     {
    15.         if (instance == null)
    16.             instance = this;
    17.        
    18.         else if(instance != this)
    19.             Destroy(gameObject);
    20.  
    21.         DontDestroyOnLoad(gameObject);
    22.         boardScript = GetComponent<BoardManager>();
    23.         InitGame();
    24.     }
    25.  
    26.     void InitGame()
    27.     {
    28.         boardScript.SetupScene(level);
    29.     }
    30.  
    31.    // Update is called once per frame
    32.     void Update() {
    33.        
    34.     }
    35. }
    Loader.cs
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Loader : MonoBehaviour
    6. {
    7.     public GameObject gameManager;
    8.  
    9.     void Awake ()
    10.     {
    11.         if (GameManager.instance == null)
    12.             Instantiate(gameManager);
    13.     }
    14. }
    15.  
     
  20. StikeleatherDillon

    StikeleatherDillon

    Joined:
    Mar 2, 2020
    Posts:
    2
    I had my for loop fixed, and still had the same error.
    1. for (int x = 1; x < columns - 1; x++)
    2. {
    3. for (int y = 1; y < rows; y++)
    4. {
    5. gridPositions.Add(new Vector3(x, y, 0f));
    6. }
    7. }
    8. }
    9. I added the minus 1 to the y < rows.
     
  21. SeanDev

    SeanDev

    Joined:
    Jan 25, 2014
    Posts:
    27
    I will be reading the tutorial and my question later tonight but for now my main question is, how can I save the project so that each time I load it from the Hub it doesn't have to unpack everything. A bit confused about the file system regarding these Kits
     
  22. ttorcaso2022

    ttorcaso2022

    Joined:
    Mar 3, 2020
    Posts:
    2
    Hey

    So I'm having trouble on the tutorial for the 2D RougeLike game, and my error is very interesting.

    I'm on video 5 and when they go into the game video, seeing the game. My game is invisible. Its really hard to describe, but when I press play I only get the background color. Anything wrong?
     
  23. ttorcaso2022

    ttorcaso2022

    Joined:
    Mar 3, 2020
    Posts:
    2

    Also, I'm a bit new to Unity so maybe I missed something up? I don't know
     
    sabrinasd2004 likes this.
  24. sabrinasd2004

    sabrinasd2004

    Joined:
    Mar 21, 2020
    Posts:
    7
    I'm at the start of the lessons and when I play the game, my player appears at the scene but not in the game. What could be wrong?

    upload_2020-3-23_14-5-19.png
    upload_2020-3-23_14-5-46.png
     
  25. sabrinasd2004

    sabrinasd2004

    Joined:
    Mar 21, 2020
    Posts:
    7
    So, I'm having problems with my scripts apparently and the game isn't working when I click "Play" in Unity. I am following the tutorial and then when I'm about to test it, unity doesn't work. What could be the problem?
     
  26. JoscoDev

    JoscoDev

    Joined:
    Oct 17, 2019
    Posts:
    1
    Is there any solution to the weird line across the middle of the map ? I have tried mostly everything online ( AA, Quality, Aspect ratio, switching from Bilinear etc) Only thing that works is keeping camera on int coords (not useful) or changing the camera rotation slightly ( X= 0.1). This issue exists even in the Completed Game.

    This is very annoying
     

    Attached Files:

  27. unity_BD4o21tJVocYSw

    unity_BD4o21tJVocYSw

    Joined:
    Apr 19, 2020
    Posts:
    1
    Hey guys, does anyone have the updated files for the tutorial including the "Dungeon Generation"?
     
    Goriburne7 likes this.
  28. unity_OFvkDMzEugDX-g

    unity_OFvkDMzEugDX-g

    Joined:
    Apr 18, 2020
    Posts:
    1
    so I don't know whether this has been resolved or no, but in the tutorial they miss out on an important line in movingobject.cs, where after casting a ray you have to enable the collider again, otherwise it won't work
     
  29. s4shrish

    s4shrish

    Joined:
    Jul 6, 2017
    Posts:
    8
    Guys, read the upgrade guide provided with the game project. I was having an issue where my character was moving fine when I played it in the editor, when I clicked "Maximize On Play" the character would move all wonky and stop at weird fractional float values. So I read the guide after much googling and no solution coming up, and there was this line in the upgrade guide that said to add a check for if the character "isMoving" or not with a bool variable. So created the variable in the abstract class, made it true in the beginning part of coroutine and false at its end. Voila, problem doesn't appear. Somehow it is still weird how this problem only appeared in editor fullscreen and build but not smaller screen editor tests.
    Well, a problem solved is a problem solved. And this is the second time I am doing this tutorial, I tried this some 2 years ago for the first time, and due to some weird error could not fix it. Now my debugging skills are a little better. Pretty noice.
    Good luck guys, and stay safe during this quarantine.

    Edit: Also, the "yield return null;" in the moving object class was causing issues, as when I changed it to "yield return new WaitForFixedUpdate();" the slower movement in Maximize on Play fullscreen dissappeared completely.
     
    Last edited: May 2, 2020
    JNKC and SpecDrum like this.
  30. Goriburne7

    Goriburne7

    Joined:
    Apr 12, 2019
    Posts:
    2
    Hi all I just finished the 2d dungeon tutorial and I can't find it anywhere else so I decided to post the code I copied from the youtube video (
    )
    here's the code from the vid if you're interested
    Code (CSharp):
    1. using System;
    2.  
    3. //Serializable so it will show up in the inspector.
    4. [Serializable]
    5.  
    6.  
    7. public class IntRange
    8. {
    9.     public int m_Min;
    10.     public int m_Max;
    11.  
    12.  
    13.     // Start is called before the first frame update
    14.     public IntRange(int min, int max)
    15.     {
    16.         m_Min = min;
    17.         m_Max = max;
    18.     }
    19.  
    20.     // Update is called once per frame
    21.     public int Random
    22.     {
    23.         get { return UnityEngine.Random.Range(m_Min, m_Max); }  
    24.     }
    25. }
    26.  
    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3.  
    4. public class BoardCreator : MonoBehaviour
    5. {  
    6.     //The type of tile That will be laid in a specific position
    7.     public enum TileType
    8.     {
    9.         Wall, Floor,
    10.     }
    11.  
    12.     public int columns = 100;                               //The number of columns on the board (how wide it will be).
    13.     public int rows = 100;                                  //The number of rows on the board (how tall it will be).
    14.     public IntRange numRooms = new IntRange(15, 20);        //The range of the number of rooms there can be.
    15.     public IntRange roomWidth = new IntRange(3, 10);        //The range of widths rooms can have.
    16.     public IntRange roomHeight = new IntRange(3, 10);       //The range of heights rooms can have.
    17.     public IntRange corridorLength = new IntRange(6, 10);   //The range of length corridors between rooms can have.
    18.     public GameObject[] floorTiles;                         //An array of floor tile prefabs
    19.     public GameObject[] wallTiles;                          //An array of wall tile prefabs
    20.     public GameObject[] outerWallTiles;                     //An array of outer wall tile prefabs
    21.     public GameObject player;
    22.  
    23.     private TileType[][] tiles;                            //A jagged array of tile types representing the board like a grid
    24.     private Room[] rooms;                                   //All the rooms that are created for this board
    25.     private Corridor[] corridors;                           //All the corridors that connect the rooms
    26.     private GameObject boardHolder;                         //Game object that acts as a container for all other tiles
    27.  
    28.     // Start is called before the first frame update
    29.     private void Start()
    30.     {
    31.         //create the board holder
    32.         boardHolder = new GameObject("BoardHolder");
    33.  
    34.         SetupTilesArray();
    35.  
    36.         CreateRoomsAndCorridors();
    37.  
    38.         SetTilesValuesForRooms();
    39.         SetTilesValuesForCorridors();
    40.  
    41.         InstantiateTiles();
    42.         InstantiateOuterWalls();
    43.  
    44.     }
    45.  
    46.     void SetupTilesArray()
    47.     {
    48.         //Set the tiles jagged array to the correct width.
    49.         tiles = new TileType[columns][];
    50.  
    51.         //Go through all the tile arrays...
    52.         for(int i = 0; i< tiles.Length; i++)
    53.         {
    54.             //... and set each tile array is the correct height
    55.             tiles[i] = new TileType[rows];
    56.         }
    57.     }
    58.     void CreateRoomsAndCorridors()
    59.     {
    60.         // Create the rooms array with a random size
    61.         rooms = new Room[numRooms.Random];
    62.  
    63.         //There should be one less corridor than there is rooms
    64.         corridors = new Corridor[rooms.Length - 1];
    65.  
    66.         //Create the first room and corridor
    67.         rooms[0] = new Room();
    68.         corridors[0] = new Corridor();
    69.  
    70.         //Setup the first room, there is no previoius corridor so we do not use one.
    71.         rooms[0].SetupRoom(roomWidth, roomHeight, columns, rows);
    72.  
    73.         //Set up the first corridor using the first room
    74.         corridors[0].SetupCorridor(rooms[0], corridorLength,  roomWidth, roomHeight, columns, rows, true);
    75.         for (int i = 1; i < rooms.Length; i++)
    76.         {
    77.             //create a room
    78.             rooms[i] = new Room();
    79.  
    80.             //Set up room based on the previous corridor
    81.             rooms[i].SetupRoom(roomWidth, roomHeight, columns, rows, corridors[i - 1]);
    82.  
    83.             //If we haven't reached the end of the corridors array
    84.             if (i<corridors.Length)
    85.             {
    86.                 //... create a corridor
    87.                 corridors[i] = new Corridor();
    88.  
    89.                 //Setup the corridor based on the room that was just created
    90.                 corridors[i].SetupCorridor(rooms[i], corridorLength, roomWidth, roomHeight, columns, rows, false);
    91.  
    92.  
    93.             }
    94.  
    95.             //Spawn the player in the middle dungeon room
    96.             if (i == Mathf.Floor(rooms.Length*.5f))
    97.             {
    98.                 Vector3 playerPos = new Vector3(rooms[i].xPos, rooms[i].yPos, 0);
    99.                 Instantiate(player, playerPos, Quaternion.identity);
    100.             }
    101.         }
    102.     }
    103.  
    104.     void SetTilesValuesForRooms()
    105.     {
    106.         //Go through all the rooms...
    107.         for (int i=0; i < rooms.Length; i++)
    108.         {
    109.             Room currentRoom = rooms[i];
    110.  
    111.             //... and for each room go  through it's width
    112.             for (int j = 0; j < currentRoom.roomWidth; j++)
    113.             {
    114.                 int xCoord = currentRoom.xPos + j;
    115.  
    116.                 //For each horizontal Tile go up Vertically through the room's height.
    117.                 for (int k =0; k < currentRoom.roomHeight; k++)
    118.                 {
    119.                     int yCoord = currentRoom.yPos + k;
    120.  
    121.                     //The  coordiunates in the jagged array are based on the room's position and it's width and height.
    122.                     tiles[xCoord][yCoord] = TileType.Floor;
    123.                 }
    124.             }
    125.         }
    126.     }
    127.  
    128.     void SetTilesValuesForCorridors()
    129.     {
    130.         //Go through every corridors...
    131.         for (int i = 0; i < corridors.Length; i++)
    132.         {
    133.             Corridor currentCorridor = corridors[i];
    134.  
    135.             //and go through it's length
    136.             for(int j = 0; j < currentCorridor.corridorLength; j++)
    137.             {
    138.                 //Start the coordinates at the start of the corridor
    139.                 int xCoord = currentCorridor.startXPos;
    140.                 int yCoord = currentCorridor.startYPos;
    141.  
    142.                 //Depending on the direction, add or subtract from the appropriate
    143.                 //coordinate based on how far through the length the loop is.
    144.                 switch (currentCorridor.direction)
    145.                 {
    146.                     case Direction.North:
    147.                         yCoord += j;
    148.                         break;
    149.                     case Direction.East:
    150.                         xCoord += j;
    151.                         break;
    152.                     case Direction.South:
    153.                         yCoord -= j;
    154.                         break;
    155.                     case Direction.West:
    156.                         xCoord -= j;
    157.                         break;
    158.                 }
    159.  
    160.                 //Set the tile at these coordinates to floor
    161.                 tiles[xCoord][yCoord] = TileType.Floor;
    162.             }
    163.         }
    164.     }
    165.  
    166.     void InstantiateTiles ()
    167.     {
    168.         //Go though all the tiles in the jagged array...
    169.         for  (int i=0;i<tiles.Length; i++)
    170.         {
    171.             for (int j = 0; j < tiles[i].Length; j++)
    172.             {
    173.                 //...and instantiate a floor tile for it.
    174.                 InstantiateFromArray(floorTiles, i, j);
    175.  
    176.                 //if the tile type is Wall...
    177.                 if (tiles[i][j] == TileType.Wall)
    178.                 {
    179.                     //... instatiate a wall over the top
    180.                     InstantiateFromArray(wallTiles, i, j);
    181.                 }
    182.             }
    183.         }
    184.     }
    185.  
    186.     void InstantiateOuterWalls()
    187.     {
    188.         //The outer walls are one unite left, right, up and down from the board
    189.         float leftEdgeX = -1f;
    190.         float rightEdgeX = columns + 0f;
    191.         float bottomEdgeY = -1f;
    192.         float topEdgeY = rows+ 0f;
    193.  
    194.         //Instantiate both vertical walls  (one on each side).
    195.         InstatiateVerticalOuterWall(leftEdgeX, bottomEdgeY, topEdgeY);
    196.         InstatiateVerticalOuterWall(rightEdgeX, bottomEdgeY, topEdgeY);
    197.  
    198.         //Instantiate both horizontal walls  (one on each side).
    199.         InstatiateHorizontalOuterWall(leftEdgeX+1f, rightEdgeX-1f, bottomEdgeY);
    200.         InstatiateHorizontalOuterWall(leftEdgeX+1f, rightEdgeX-1f, topEdgeY);
    201.  
    202.     }
    203.  
    204.     void InstatiateVerticalOuterWall (float xCoord, float  startingY, float endingY)
    205.     {
    206.         //Start the loop at the starting value for Y
    207.         float currentY = startingY;
    208.  
    209.         //While the value for Y is less than the end value...
    210.         while (currentY <= endingY)
    211.         {
    212.             //... instantiate an outer wall tile at the x coordinate and the current y coordinate.
    213.             InstantiateFromArray(outerWallTiles, xCoord, currentY);
    214.  
    215.             currentY++;
    216.         }
    217.     }
    218.  
    219.     void InstatiateHorizontalOuterWall(float startingX, float endingX, float Ycoord)
    220.     {
    221.         //Start the loop at the starting value for X
    222.         float currentX = startingX;
    223.  
    224.         //While the value for X is less than the end value...
    225.         while (currentX <= endingX)
    226.         {
    227.             //... instantiate an outer wall tile at the y coordinate and the current x coordinate.
    228.             InstantiateFromArray(outerWallTiles, currentX, Ycoord);
    229.  
    230.             currentX++;
    231.         }
    232.     }
    233.  
    234.     void InstantiateFromArray (GameObject[] prefabs,float xCoord, float yCoord)
    235.     {
    236.         //Create a random index for the array.
    237.         int randomIndex = Random.Range(0, prefabs.Length);
    238.  
    239.         //The position to be instantiated at is based on coordinates.
    240.         Vector3 position = new Vector3(xCoord, yCoord, 0f);
    241.  
    242.         //Create an instance of the prefab from the random index of the array.
    243.         GameObject tileInstance = Instantiate(prefabs[randomIndex], position, Quaternion.identity) as GameObject;
    244.  
    245.         //Set the tile's parent to the board holder
    246.         tileInstance.transform.parent = boardHolder.transform;
    247.     }
    248. }
    249.  
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. // Enum to specify the direction is heading
    4. public enum Direction
    5. {
    6.     North, East, South, West,
    7. }
    8.  
    9. public class Corridor
    10. {
    11.     public int startXPos;           //The x coordiante for the start of the corridor.
    12.     public int startYPos;           //The x coordiante for the start of the corridor.
    13.     public int corridorLength;      //How many units long the corridor is.
    14.     public Direction direction;     //Which direction the corridor is heading from its room.
    15.  
    16.     //Get the end position of the corridor based on it start position and which direction it's heading.
    17.     public int EndPositionX
    18.     {
    19.         get
    20.         {
    21.             if (direction == Direction.North || direction == Direction.South)
    22.                 return startXPos;
    23.             if (direction == Direction.East)
    24.                 return startXPos + corridorLength - 1;
    25.             return startXPos - corridorLength + 1;
    26.         }
    27.     }
    28.     public int EndPositionY
    29.     {
    30.         get
    31.         {
    32.             if (direction == Direction.East || direction == Direction.West)
    33.                 return startYPos;
    34.             if (direction == Direction.North)
    35.                 return startYPos + corridorLength - 1;
    36.             return startYPos - corridorLength + 1;
    37.         }
    38.     }
    39.     public void SetupCorridor (Room room, IntRange length, IntRange roomWidth, IntRange roomHeight, int columns, int rows, bool firstCorridor)
    40.     {
    41.         //Set a random direction ( a random Index from 0 to 3 cast to direction).
    42.         direction = (Direction)Random.Range(0, 4);
    43.  
    44.         //Find the direction opposite to the one entering the room this corridor is leaving from
    45.         //Cast the previous corridor's direction to an int between 0 and 3 and add 2 (a number between 2 and 5)
    46.         //Find the remainder when dividing by 4 (if 2 then 2,  if 3 then 3, if 4 then 0, if 5 then 1).
    47.         //Overall effect is if the direction was South then that is 2, becomes 4, the remainder is 0. If 5 then 1;
    48.         Direction oppositeDirection = (Direction)(((int)room.enteringCorridor + 2) % 4);
    49.  
    50.         //If this is not the first corridor and the randomly selected direction is opposite to the previous corridor's direction...
    51.         if (!firstCorridor && direction == oppositeDirection)
    52.         {
    53.             // Rotate the direction 90 degrees clockwise (North becomes East, East becomes South, etc).
    54.             //This is a more broken down version of the opposite direction operation above but instead of adding 2 we're adding 1.
    55.             //This means instead of rotating 180 (the opposite direction) we're rotating 90.
    56.             int directionInt = (int)direction;
    57.             directionInt++;
    58.             directionInt = directionInt % 4;
    59.             direction = (Direction)directionInt;
    60.  
    61.         }
    62.  
    63.         //Set a random length
    64.         corridorLength = length.Random;
    65.  
    66.         //create a cap for how long the length can be (this will be changed based  on the direction and positions);
    67.         int maxLength = length.m_Max;
    68.  
    69.         switch (direction)
    70.         {
    71.             //If the chosen direction is North (up)...
    72.             case Direction.North:
    73.                 //... the starting position in the x axis can be random but within the width of the room
    74.                 startXPos = Random.Range(room.xPos, room.xPos + room.roomWidth - 1);
    75.  
    76.                 //The starting position in the y-axis must be the top of the room.
    77.                 startYPos = room.yPos + room.roomHeight;
    78.  
    79.                 //The maximum length the corridor can be in is the height of the board (rows) but from the top of the room (yPos + height)
    80.                 maxLength = rows - startYPos - roomHeight.m_Min;
    81.                 break;
    82.             case Direction.East:
    83.                 startXPos = room.xPos + room.roomWidth;
    84.                 startYPos = Random.Range(room.yPos, room.yPos + room.roomHeight - 1);
    85.                 maxLength = columns - startXPos - roomWidth.m_Min;
    86.                 break;
    87.             case Direction.South:
    88.                 startXPos = Random.Range(room.xPos, room.xPos + room.roomWidth);
    89.                 startYPos = room.yPos;
    90.                 maxLength = startYPos - roomHeight.m_Min;
    91.                 break;
    92.             case Direction.West:
    93.                 startYPos = Random.Range(room.yPos, room.yPos + room.roomHeight);
    94.                 startXPos = room.xPos;
    95.                 maxLength = startXPos - roomWidth.m_Min;
    96.                 break;
    97.         }
    98.  
    99.         //We clamp the length of the corridor to make sure it doesn't go off the board.
    100.         corridorLength = Mathf.Clamp(corridorLength, 1, maxLength);
    101.     }
    102. }
    103.  
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Room
    4. {
    5.     public int xPos;                        //The x coordinate of the lower left tile of the room.
    6.     public int yPos;                        //The y coordinate of the lower left tile of the room.
    7.     public int roomWidth;                   //How many tiles wide the room is
    8.     public int roomHeight;                  //How many tiles high the room is
    9.     public Direction enteringCorridor;      //The direction of the corridor that is entering this room
    10.  
    11.  
    12.     // This is used for the first room. It does not have a  corridor parameter since there are no corridors yet.
    13.     public void SetupRoom(IntRange widthRange, IntRange heightRange, int columns, int rows)
    14.     {
    15.         //Set a random width and height
    16.         roomWidth = widthRange.Random;
    17.         roomHeight = heightRange.Random;
    18.  
    19.         //Set the x and y coordinates so the room pos roughly in the middle of the board.
    20.         xPos = Mathf.RoundToInt(columns / 2f - roomWidth / 2f);
    21.         yPos = Mathf.RoundToInt(rows / 2f - roomHeight / 2f);
    22.     }
    23.  
    24.  
    25.     // This is an overload of the SetupRoom function and has a corridor parameter that represents the corridor entering the room.
    26.     public void SetupRoom (IntRange widthRange, IntRange heightRange, int columns, int rows, Corridor corridor)
    27.     {
    28.         // Set the entering corridor direction
    29.         enteringCorridor = corridor.direction;
    30.  
    31.         //Set random values for width and height
    32.         roomWidth = widthRange.Random;
    33.         roomHeight = heightRange.Random;
    34.  
    35.         switch (corridor.direction)
    36.         {
    37.             //if the corridor entering this room is going north...
    38.             case Direction.North:
    39.                 //... the height of the room mustn't go beyond the board so that it must be clamped based
    40.                 //on the height of the board (rows) and the end of the corridor that leads to the room.
    41.                 roomHeight = Mathf.Clamp(roomHeight, 1, rows - corridor.EndPositionY);
    42.  
    43.                 //The y coordinate of the room must be at the end of the corridor (since the corridor leads to the bottom of the room).
    44.                 yPos = corridor.EndPositionY;
    45.                
    46.                 //The x coordinate can be random but the left-most possibility is no further than the width
    47.                 //and the right-most possibility is that the end of the corridor is at the position of the room.
    48.                 xPos = Random.Range(corridor.EndPositionX - roomWidth + 1, corridor.EndPositionX);
    49.  
    50.                 //This must be clamped to ensure that the room doesn't go off the board
    51.                 xPos = Mathf.Clamp(xPos, 0, columns - roomWidth);
    52.                 break;
    53.             case Direction.East:
    54.                 roomWidth = Mathf.Clamp(roomWidth, 1, columns - corridor.EndPositionX);
    55.                 xPos = corridor.EndPositionX;
    56.  
    57.                 yPos = Random.Range(corridor.EndPositionY - roomHeight + 1, corridor.EndPositionY);
    58.                 yPos = Mathf.Clamp(yPos, 0, rows - roomHeight);
    59.                 break;
    60.             case Direction.South:
    61.                 roomHeight = Mathf.Clamp(roomHeight, 1, corridor.EndPositionY);
    62.                 yPos = corridor.EndPositionY - roomHeight + 1;
    63.  
    64.                 xPos = Random.Range(corridor.EndPositionX - roomWidth + 1, corridor.EndPositionX);
    65.                 xPos = Mathf.Clamp(xPos, 0, columns - roomWidth);
    66.                 break;
    67.             case Direction.West:
    68.                 roomWidth = Mathf.Clamp(roomWidth, 1, corridor.EndPositionX);
    69.                 xPos = corridor.EndPositionX - roomWidth + 1;
    70.  
    71.                 yPos = Random.Range(corridor.EndPositionY - roomHeight + 1, corridor.EndPositionY);
    72.                 yPos = Mathf.Clamp(yPos, 0, rows - roomHeight);
    73.                 break;
    74.  
    75.         }
    76.     }
    77. }
    78.  
    Hope someone finds this useful
     
  31. Goriburne7

    Goriburne7

    Joined:
    Apr 12, 2019
    Posts:
    2
    Update: I changed the BoardCreator code to spawn enemies, food and an exit in the last room
    In the video, he removed the loader object but you need to keep it for the next levels to load correctly.
    Don't forget to add the prefabs onto the new Board creator in the game manager Prefab. And remember to add my copy of his code above this post.

    Keep it 100

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4.  
    5. public class BoardCreator : MonoBehaviour
    6. {  
    7.     //The type of tile That will be laid in a specific position
    8.     public enum TileType
    9.     {
    10.         Wall, Floor,
    11.     }
    12.  
    13.     public int columns = 100;                               //The number of columns on the board (how wide it will be).
    14.     public int rows = 100;                                  //The number of rows on the board (how tall it will be).
    15.     public IntRange numRooms = new IntRange(15, 20);        //The range of the number of rooms there can be.
    16.     public IntRange roomWidth = new IntRange(3, 10);        //The range of widths rooms can have.
    17.     public IntRange roomHeight = new IntRange(3, 10);       //The range of heights rooms can have.
    18.     public IntRange corridorLength = new IntRange(6, 10);   //The range of length corridors between rooms can have.
    19.     public GameObject[] floorTiles;                         //An array of floor tile prefabs
    20.     public GameObject[] wallTiles;                          //An array of wall tile prefabs
    21.     public GameObject[] outerWallTiles;                     //An array of outer wall tile prefabs
    22.     public GameObject[] foodTiles;                          //Array of food prefabs.
    23.     public GameObject[] enemyTiles;                         //Array of enemy prefabs.
    24.  
    25.  
    26.     public GameObject player;
    27.     public GameObject exit;
    28.  
    29.     private TileType[][] tiles;                            //A jagged array of tile types representing the board like a grid
    30.     private Room[] rooms;                                   //All the rooms that are created for this board
    31.     private Corridor[] corridors;                           //All the corridors that connect the rooms
    32.     private GameObject boardHolder;                         //Game object that acts as a container for all other tiles
    33.  
    34.     private List<Vector3> roomPositions = new List<Vector3>();    //A list of possible locations to place tiles.
    35.  
    36.  
    37.     //SetupScene initializes our level and calls the following functions to lay out the game board
    38.     public void SetupScene(int level)
    39.     {
    40.         //Increase complexity based on a logarithmic progression
    41.         int scale = (int)Mathf.Log(level, 2f);
    42.         int miniScale = (int)Mathf.Sqrt(scale);
    43.         //more rooms each level
    44.         int roomMin = 3 + level + scale;
    45.         numRooms = new IntRange(roomMin, roomMin + scale);
    46.  
    47.         //create the board holder
    48.         boardHolder = new GameObject("BoardHolder");
    49.  
    50.         SetupTilesArray();
    51.  
    52.         CreateRoomsAndCorridors();
    53.  
    54.         SetTilesValuesForRooms();
    55.         SetTilesValuesForCorridors();
    56.  
    57.         InstantiateTiles();
    58.         InstantiateOuterWalls();
    59.  
    60.         //Determine amount of food based on current level number, based on a logarithmic progression
    61.         int foodCount = 4+scale;
    62.  
    63.         //Determine number of enemies based on current level number, based on a logarithmic progression
    64.         int enemyCount = 1+scale;
    65.  
    66.         //Instantiate a random number of food tiles based on minimum and maximum, at randomized positions.
    67.         LayoutObjectAtRandom(foodTiles, foodCount, foodCount+ miniScale);
    68.  
    69.         //Instantiate a random number of enemies based on minimum and maximum, at randomized positions.
    70.         LayoutObjectAtRandom(enemyTiles, enemyCount, enemyCount+ miniScale);
    71.  
    72.     }
    73.  
    74.     void SetupTilesArray()
    75.     {
    76.         //Set the tiles jagged array to the correct width.
    77.         tiles = new TileType[columns][];
    78.  
    79.         //Go through all the tile arrays...
    80.         for(int i = 0; i< tiles.Length; i++)
    81.         {
    82.             //... and set each tile array is the correct height
    83.             tiles[i] = new TileType[rows];
    84.         }
    85.     }
    86.     void CreateRoomsAndCorridors()
    87.     {
    88.         // Create the rooms array with a random size
    89.         rooms = new Room[numRooms.Random];
    90.  
    91.         //There should be one less corridor than there is rooms
    92.         corridors = new Corridor[rooms.Length - 1];
    93.  
    94.         //Create the first room and corridor
    95.         rooms[0] = new Room();
    96.         corridors[0] = new Corridor();
    97.  
    98.         //Setup the first room, there is no previous corridor so we do not use one.
    99.         rooms[0].SetupRoom(roomWidth, roomHeight, columns, rows);
    100.  
    101.         //Spawn the player in the first dungeon room
    102.         Vector3 playerPos = new Vector3(rooms[0].xPos, rooms[0].yPos, 0);
    103.         Instantiate(player, playerPos, Quaternion.identity);
    104.  
    105.         //Set up the first corridor using the first room
    106.         corridors[0].SetupCorridor(rooms[0], corridorLength,  roomWidth, roomHeight, columns, rows, true);
    107.         for (int i = 1; i < rooms.Length; i++)
    108.         {
    109.             //create a room
    110.             rooms[i] = new Room();
    111.  
    112.             //Set up room based on the previous corridor
    113.             rooms[i].SetupRoom(roomWidth, roomHeight, columns, rows, corridors[i - 1]);
    114.  
    115.             //If we haven't reached the end of the corridors array
    116.             if (i<corridors.Length)
    117.             {
    118.                 //... create a corridor
    119.                 corridors[i] = new Corridor();
    120.  
    121.                 //Setup the corridor based on the room that was just created
    122.                 corridors[i].SetupCorridor(rooms[i], corridorLength, roomWidth, roomHeight, columns, rows, false);
    123.  
    124.  
    125.             }
    126.         }
    127.         //Spawn the exit in the first dungeon room
    128.         Vector3 exitPos = new Vector3(rooms[rooms.Length- 1].xPos, rooms[rooms.Length - 1].yPos, 0);
    129.         Instantiate(exit, exitPos, Quaternion.identity);
    130.     }
    131.  
    132.     void SetTilesValuesForRooms()
    133.     {
    134.         //Clear our list gridPositions.
    135.         roomPositions.Clear();
    136.         //Go through all the rooms...
    137.         for (int i=0; i < rooms.Length; i++)
    138.         {
    139.             Room currentRoom = rooms[i];
    140.  
    141.             //... and for each room go  through it's width
    142.             for (int j = 0; j < currentRoom.roomWidth; j++)
    143.             {
    144.                 int xCoord = currentRoom.xPos + j;
    145.  
    146.                 //For each horizontal Tile go up Vertically through the room's height.
    147.                 for (int k =0; k < currentRoom.roomHeight; k++)
    148.                 {
    149.                     int yCoord = currentRoom.yPos + k;
    150.  
    151.                     //The  coordiunates in the jagged array are based on the room's position and it's width and height.
    152.                     tiles[xCoord][yCoord] = TileType.Floor;
    153.  
    154.                     //At each index add a new Vector3 to our list with the xCoord and yCoord coordinates of that position.(adds room coordinates to a list)
    155.                     roomPositions.Add(new Vector3(xCoord, yCoord, 0f));
    156.                 }
    157.             }
    158.         }
    159.     }
    160.  
    161.     void SetTilesValuesForCorridors()
    162.     {
    163.         //Go through every corridors...
    164.         for (int i = 0; i < corridors.Length; i++)
    165.         {
    166.             Corridor currentCorridor = corridors[i];
    167.  
    168.             //and go through it's length
    169.             for(int j = 0; j < currentCorridor.corridorLength; j++)
    170.             {
    171.                 //Start the coordinates at the start of the corridor
    172.                 int xCoord = currentCorridor.startXPos;
    173.                 int yCoord = currentCorridor.startYPos;
    174.  
    175.                 //Depending on the direction, add or subtract from the appropriate
    176.                 //coordinate based  on how far through the length the loop is.
    177.                 switch (currentCorridor.direction)
    178.                 {
    179.                     case Direction.North:
    180.                         yCoord += j;
    181.                         break;
    182.                     case Direction.East:
    183.                         xCoord += j;
    184.                         break;
    185.                     case Direction.South:
    186.                         yCoord -= j;
    187.                         break;
    188.                     case Direction.West:
    189.                         xCoord -= j;
    190.                         break;
    191.                 }
    192.  
    193.                 //Set the tile at these coordinates to floor
    194.                 tiles[xCoord][yCoord] = TileType.Floor;
    195.             }
    196.         }
    197.     }
    198.  
    199.     void InstantiateTiles ()
    200.     {
    201.         //Go though all the tiles in the jagged array...
    202.         for  (int i=0;i<tiles.Length; i++)
    203.         {
    204.             for (int j = 0; j < tiles[i].Length; j++)
    205.             {
    206.                 //...and instantiate a floor tile for it.
    207.                 InstantiateFromArray(floorTiles, i, j);
    208.  
    209.                 //if the tile type is Wall...
    210.                 if (tiles[i][j] == TileType.Wall)
    211.                 {
    212.                     //... instatiate a wall over the top
    213.                     InstantiateFromArray(wallTiles, i, j);
    214.                 }
    215.             }
    216.         }
    217.     }
    218.  
    219.     void InstantiateOuterWalls()
    220.     {
    221.         //The outer walls are one unite left, right, up and down from the board
    222.         float leftEdgeX = -1f;
    223.         float rightEdgeX = columns + 0f;
    224.         float bottomEdgeY = -1f;
    225.         float topEdgeY = rows+ 0f;
    226.  
    227.         //Instantiate both vertical walls  (one on each side).
    228.         InstatiateVerticalOuterWall(leftEdgeX, bottomEdgeY, topEdgeY);
    229.         InstatiateVerticalOuterWall(rightEdgeX, bottomEdgeY, topEdgeY);
    230.  
    231.         //Instantiate both horizontal walls  (one on each side).
    232.         InstatiateHorizontalOuterWall(leftEdgeX+1f, rightEdgeX-1f, bottomEdgeY);
    233.         InstatiateHorizontalOuterWall(leftEdgeX+1f, rightEdgeX-1f, topEdgeY);
    234.  
    235.     }
    236.  
    237.     void InstatiateVerticalOuterWall (float xCoord, float  startingY, float endingY)
    238.     {
    239.         //Start the loop at the starting value for Y
    240.         float currentY = startingY;
    241.  
    242.         //While the value for Y is less than the end value...
    243.         while (currentY <= endingY)
    244.         {
    245.             //... instantiate an outer wall tile at the x coordinate and the current y coordinate.
    246.             InstantiateFromArray(outerWallTiles, xCoord, currentY);
    247.  
    248.             currentY++;
    249.         }
    250.     }
    251.  
    252.     void InstatiateHorizontalOuterWall(float startingX, float endingX, float Ycoord)
    253.     {
    254.         //Start the loop at the starting value for X
    255.         float currentX = startingX;
    256.  
    257.         //While the value for X is less than the end value...
    258.         while (currentX <= endingX)
    259.         {
    260.             //... instantiate an outer wall tile at the y coordinate and the current x coordinate.
    261.             InstantiateFromArray(outerWallTiles, currentX, Ycoord);
    262.  
    263.             currentX++;
    264.         }
    265.     }
    266.  
    267.     void InstantiateFromArray (GameObject[] prefabs,float xCoord, float yCoord)
    268.     {
    269.         //Create a random index for the array.
    270.         int randomIndex = Random.Range(0, prefabs.Length);
    271.  
    272.         //The position to be instatiated at is based on coordinates.
    273.         Vector3 position = new Vector3(xCoord, yCoord, 0f);
    274.  
    275.         //Create an instance of the prefab from the random index of the array.
    276.         GameObject tileInstance = Instantiate(prefabs[randomIndex], position, Quaternion.identity) as GameObject;
    277.  
    278.         //Set the tile's parent to the board holder
    279.         tileInstance.transform.parent = boardHolder.transform;
    280.     }
    281.  
    282.     //RandomPosition returns a random position from our list roomPositions.
    283.     Vector3 RandomPosition()
    284.     {
    285.         //Declare an integer randomIndex, set it's value to a random number between 0 and the count of items in our List roomPositions.
    286.         int randomIndex = Random.Range(0, roomPositions.Count);
    287.  
    288.         //Declare a variable of type Vector3 called randomPosition, set it's value to the entry at randomIndex from our List roomPositions.
    289.         Vector3 randomPosition = roomPositions[randomIndex];
    290.  
    291.         //Remove the entry at randomIndex from the list so that it can't be re-used.
    292.         roomPositions.RemoveAt(randomIndex);
    293.  
    294.         //Return the randomly selected Vector3 position.
    295.         return randomPosition;
    296.     }
    297.  
    298.     //LayoutObjectAtRandom accepts an array of game objects to choose from along with a minimum and maximum range for the number of objects to create.
    299.     void LayoutObjectAtRandom(GameObject[] tileArray, int minimum, int maximum)
    300.     {
    301.         //Choose a random number of objects to instantiate within the minimum and maximum limits
    302.         int objectCount = Random.Range(minimum, maximum + 1);
    303.  
    304.         //Instantiate objects until the randomly chosen limit objectCount is reached
    305.         for (int i = 0; i < objectCount; i++)
    306.         {
    307.             //Choose a position for randomPosition by getting a random position from our list of available Vector3s stored in roomPosition
    308.             Vector3 randomPosition = RandomPosition();
    309.  
    310.             //Choose a random tile from tileArray and assign it to tileChoice
    311.             GameObject tileChoice = tileArray[Random.Range(0, tileArray.Length)];
    312.  
    313.             //Instantiate tileChoice at the position returned by RandomPosition with no change in rotation
    314.             Instantiate(tileChoice, randomPosition, Quaternion.identity);
    315.         }
    316.     }
    317. }
    318.  
     
  32. Lucifer656

    Lucifer656

    Joined:
    Jul 15, 2020
    Posts:
    7
    Is there a video or step missing from the tutorials? I have been following the videos and everything was working until the part 9 player script video, which starts referencing things in the GameManager script like
    GameManager.instance.playerFoodPoints that dont seem to have been added to the GameManager script yet in the tutorials. I looked ahead in the tutorials to see if I could figure out what was going on, and the code referenced seems to have magically appeared in the GameManager script in the part 11 enemy animator controller video so I assume it was supposed to have been covered earlier in the series.
     
  33. Valjuin

    Valjuin

    Joined:
    May 22, 2019
    Posts:
    481
    Added right at very beginning of part 9 player script video.
     
  34. mrochek

    mrochek

    Joined:
    Aug 10, 2020
    Posts:
    1
    I homeschool my son who is interested in game design. I am trying to tailor the coursework as much as possible so that it appeals to his interests. He is interested in 2D top-down games. I did not see any beginner tutorials/projects for this type of game. Rogue is the only one that I have found but it is intermediate. Can you tell me what makes this project intermediate or what pre-requisites should be learned to be able to get the most out of this project?
    Thanks!
     
    plaidmoss likes this.
  35. jepthanatos

    jepthanatos

    Joined:
    Sep 26, 2020
    Posts:
    1
    This code works in the last version of Unity but in the pdf you can find in the project's assets, it tells you to use 3 functions (OnLevelFinishedLoading, OnEnable, OnDisable) and add a delegate (they don't explain where or how) and refers to another tutorial.
    I think even the script or the pdf should be updated to find the correct way to solve the problem.

    And btw I couldn't make the 3 functions work properly.
     
    Last edited: Oct 1, 2020
  36. BlueSteelAU

    BlueSteelAU

    Joined:
    Jan 16, 2018
    Posts:
    1
    when using making other floor sprites as stated in tutorial. "drag them down to prefabs" 2019 or 2020 its coming up with a requesator window about saving it as a new original prefab or a variant.. which should i choose .. and why is it coming up
     
  37. Veliko

    Veliko

    Joined:
    Dec 5, 2020
    Posts:
    1
    I'm on video 2, deciding to attempt this tutorial after the initial Unity intro pathways. I can't even press Play to test the animations as the video suggests due to "All Compiler errors have to be fixed before you enter Playmode!" There appear to be a number of errors about "Collab" not containing assorted definitions:

    Example:
    Library\PackageCache\com.unity.collab-proxy@1.3.8\Editor\Models\Providers\Collab.cs(593,22): error CS1061: 'Collab' does not contain a definition for 'RevertFiles' and no accessible extension method 'RevertFiles' accepting a first argument of type 'Collab' could be found (are you missing a using directive or an assembly reference?)
    All of the errors are related to this "collab-proxy" as at the start of that example.

    Anyone have any insight for me?

    edit: Resolved it myself. Unity Collaborate in the Package Manager was version 1.3.8, and downgrading to the last verified distribution, 1.2.16, cleared up the problem.
     
    Last edited: Dec 14, 2020
  38. orinichevdima

    orinichevdima

    Joined:
    Jan 2, 2021
    Posts:
    1
    I have the same issue and after small research I've found that problem is caused by race between players turn and enemies moving. I found that when players turn is marked as finished actual player is still in movement and when enemy starts moving collision detection shows that space is empty.
    To fix this race I've had to change a lot of code, I've added two abstract methods "OnStartMoving" and "OnStopMoving" to the class MovingObject which indicate that object is moving. Also I've changed signature of the OnCantMove.
    This changes lead to refactoring in Player and Enemy files.
    All changed files are attached to my comment, please review
     

    Attached Files:

    Rrawrr likes this.
  39. cthulu2024

    cthulu2024

    Joined:
    Jul 12, 2020
    Posts:
    1
    Pretty sure the "New original prefab" option will duplicate the behavior in the tutorial. It seems like its a new feature to make creating variants easier, which he doesn't do in that tutorial.
     
    GregoryLane likes this.
  40. samuelmiller

    samuelmiller

    Joined:
    Aug 15, 2020
    Posts:
    8
    In my experience, the "variants" were a problem for following the tutorial, so I would recommend using "New Original Prefab." I'm sure there's a good way to use the variants, but that might be a better exercise after completing the tutorial.
     
  41. Neoparadoxon

    Neoparadoxon

    Joined:
    May 1, 2021
    Posts:
    1
    Thanks for this great tutorial on how to design games, especially showing the concept of a gamemanager and random board generation has felt like increasing my game design skills to the next level. I went through the project step-by-step and while fixing all the little issues (my fault almost all of the time) I clarified most of the questions I had myself. Thanks also a lot for the detailled finished code with all these comments on almost every line of code, which makes it easy to comprehend some lines I didn't grasp on my first view. Also the communitythreads are very helpful (e.g. hint on resetting the size of the enemy prefab box collider 2D).

    I finally struggle with 2 things in the update pdf.

    If I implement the scenemanager and functions as written, it appears to load twice, as it starts with level 2 and progress on exit to level 4 in which the player starves with his first step despite having tons of food. As said, I assume the scene to load twice. I tried a few things but couldn't fix it for now, but there are some things I still haven't checked (maybe exit is triggered twice). Has anyone experienced a similar issue?

    2nd issue: after I added the isMoving variable to the MovingObject script (I assumed it has to be the MovingObject script as there is no Move function in the Player script) I could not hear the footstep/move-sounds of my player, which works with the original script. I think this happens because the Move function returns false to the player script after adding "isMoving" and its functionality as the pdf says, which is preventing the movement coroutine to start again while being executed, so I don't want to remove it entirely again.
    Instead to fix this I changed the MovingObject script from

    Code (CSharp):
    1.         if (hit.transform == null && !isMoving)
    2.         {
    3.             StartCoroutine(SmoothMovement (end));
    4.             return true;
    5.         }

    to

    Code (CSharp):
    1.         if (hit.transform == null)
    2.         {
    3.             if (!isMoving) StartCoroutine(SmoothMovement (end));
    4.             return true;
    5.         }
    Is there a better solution to this?


    Nevertheless thanks again for this great tutorial :)
     
    Last edited: May 3, 2021
  42. UnityMaru

    UnityMaru

    Community Engagement Manager PSM

    Joined:
    Mar 16, 2016
    Posts:
    1,227

    A learner from the tutorial comments helped to answer this.

    "If you find that many objects are loading twice after following the .pdf to update to tutorial, check and make sure that InitGame() isn't running twice in the GameManager script. When you add the revisions, it will be present in awake and OnLevelFinishedLoading() and will create chaos."
     
    a20davruiagu likes this.
  43. Null-N-Void

    Null-N-Void

    Joined:
    Aug 9, 2021
    Posts:
    2
    Hello all.
    I'm having a small issue with following the tutorial. I am currently at the end of part 11 where we are attempting to add the updated enemy script to the enemy1 and enemy2 prefabs. When I go to add the script as a component to the prefabs, I do not have the options for Move Time, Blocking Layer, or Player Damage. Not entirely sure why this is as I have followed the tutorial exactly. If anyone has any insight, I am happy to learn why those options are not appearing.

    Attached is a screen shot of the inspector showing how my script's component differs from the completed scripts component.
     

    Attached Files:

  44. Valjuin

    Valjuin

    Joined:
    May 22, 2019
    Posts:
    481
    Make sure you have declared the public variables in your MovingObject and Enemy scripts. These are what appear in the Inspector.

    Also, make sure your Enemy script inherits from MovingObject, which should be a public abstract class.

    See screenshot.
    upload_2021-8-10_0-14-58.png
     
    Last edited: Aug 10, 2021
  45. Null-N-Void

    Null-N-Void

    Joined:
    Aug 9, 2021
    Posts:
    2
    I found my solution to be much simpler. I renamed the file thinking there would be no consequence. So I renamed it to it's original name and the problem was fixed. Thank you for your help.
     
    Valjuin likes this.
  46. Valjuin

    Valjuin

    Joined:
    May 22, 2019
    Posts:
    481
    Ah, I hadn’t noticed that in your screenshot. Glad you managed to fix your problem :).
     
  47. DucaDiMonteSberna

    DucaDiMonteSberna

    Joined:
    Jan 18, 2018
    Posts:
    79
    you can olso rename the class to match the new name, that should also fix it
     
  48. Ignasis

    Ignasis

    Joined:
    Feb 6, 2021
    Posts:
    2
    I'm having an issue while following along with the tutorial I'm on part 4 and I can't get my floors to spawn, I've went through my code checked the spacing, checked the GameObjects and I can't find anything out of the ordinary. I've looked through this thread but haven't found anything that would help solve my problem. I'll post my code below.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using System;
    4. using Random = UnityEngine.Random;
    5. using UnityEngine;
    6.  
    7. public class BoardManager : MonoBehaviour
    8. {
    9.     [Serializable]
    10.     public class Count
    11.     {
    12.         public int minimum;
    13.         public int maximum;
    14.  
    15.         public Count (int min, int max)
    16.         {
    17.             minimum = min;
    18.             maximum = max;
    19.         }
    20.     }
    21.  
    22.     public int columns = 8;
    23.     public int rows = 8;
    24.     public Count wallCount = new Count(5, 9);
    25.     public Count foodCount = new Count(1, 5);
    26.     public GameObject exit;
    27.     public GameObject[] floorTiles;
    28.     public GameObject[] wallTiles;
    29.     public GameObject[] foodTiles;
    30.     public GameObject[] enemyTiles;  
    31.     public GameObject[] outerWallTiles;
    32.  
    33.     private Transform boardHolder;
    34.     private List <Vector3> gridPositions = new List <Vector3> ();
    35.    
    36.  
    37.     void InitialiseList ()
    38.     {
    39.         gridPositions.Clear ();
    40.  
    41.         for (int x = 1; x < columns -1; x++)
    42.         {
    43.             for (int y = 1; y < rows -1; y++)
    44.             {
    45.                 gridPositions.Add (new Vector3(x, y, 0f));
    46.             }
    47.         }
    48.     }
    49.  
    50.     void BoardSetup ()
    51.     {
    52.         boardHolder = new GameObject ("Board").transform;
    53.  
    54.         for (int x = -1; x < columns + 1; x++)
    55.         {
    56.             for (int y = -1; y < rows + 1; y++)
    57.             {
    58.                 GameObject toInstantiate = floorTiles [Random.Range (0, floorTiles.Length)];
    59.                
    60.  
    61.                 if (x == -1 || x == columns || y == -1 || y == rows)
    62.                 {
    63.                     toInstantiate = outerWallTiles [Random.Range (0, outerWallTiles.Length)] as GameObject;
    64.  
    65.                     GameObject instance = Instantiate (toInstantiate, new Vector3 (x, y, 0f), Quaternion.identity);
    66.  
    67.                     instance.transform.SetParent (boardHolder);
    68.                 }
    69.             }
    70.         }
    71.     }
    72.  
    73.     Vector3 RandomPosition ()
    74.     {
    75.         int randomIndex = Random.Range (0, gridPositions.Count);
    76.         Vector3 randomPosition = gridPositions [randomIndex];
    77.         gridPositions.RemoveAt (randomIndex);
    78.         return randomPosition;
    79.     }
    80.  
    81.     void LayoutObjectAtRandom (GameObject[] tileArray, int minimum, int maximum)
    82.     {
    83.         int objectCount = Random.Range (minimum, maximum + 1);
    84.         for (int i = 0; i < objectCount; i++)
    85.         {
    86.             Vector3 randomPosition = RandomPosition ();
    87.             GameObject tileChoice = tileArray [Random.Range(0, tileArray.Length)];
    88.             Instantiate (tileChoice, randomPosition, Quaternion.identity);
    89.         }
    90.     }
    91.  
    92.     public void SetupScene (int level)
    93.     {
    94.         BoardSetup ();
    95.         InitialiseList ();
    96.         LayoutObjectAtRandom (wallTiles, wallCount.minimum, wallCount.maximum);
    97.         LayoutObjectAtRandom (foodTiles, foodCount.minimum, foodCount.maximum);
    98.         int enemyCount = (int) Mathf.Log (level, 2f);
    99.         LayoutObjectAtRandom (enemyTiles, enemyCount, enemyCount);
    100.         Instantiate (exit, new Vector3(columns - 1, rows - 1, 0f), Quaternion.identity);
    101.     }
    102. }
     
  49. Parspsq

    Parspsq

    Joined:
    Jul 14, 2021
    Posts:
    11
  50. rehtse_studio

    rehtse_studio

    Joined:
    Jul 25, 2013
    Posts:
    24
Thread Status:
Not open for further replies.