Search Unity

Official 2D Roguelike: Q&A

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

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

    Tekniko

    Joined:
    Jun 15, 2012
    Posts:
    50
    First off, I love these "intermediate" tutorials. I am getting sick and tired of learning how to write "Hello World!" to the game screen.

    Any way, I wanted to expand my game board so my first thought was to change the columns and rows value from 8 to say 12. This, unfortunately, did absolutely nothing. Does anyone know how to expand the game board?
     
  2. TizzyTool

    TizzyTool

    Joined:
    Dec 20, 2012
    Posts:
    6
    When you set a public variable's default value, it is just the first value for the Inspector when you put it in a scene. In this case, I believe the tutorial has you create a prefab of BoardManager, at which point the values are set to 8. If you change the values in that prefab, via the Inspector, it should change the size of the board
     

    Attached Files:

  3. TizzyTool

    TizzyTool

    Joined:
    Dec 20, 2012
    Posts:
    6
    Can someone explain how each of the tiles line up? Tile [i,j] seems to be placed at Vector3(i, j, 0), so the tile at index (0,1) is placed at position (0,1, 0). But each tile is 32x32px, so how is that rectified? I would have expected each tile to have to know how wide it is in order to place it next to its neighbor (e.g. Tile[0][1] would have to be offset by 32 pixels, placed at Vector(0, 32, 0)).

    Thanks in advance.
     
  4. TizzyTool

    TizzyTool

    Joined:
    Dec 20, 2012
    Posts:
    6
    Oh is it the sprite sheet's "Pixels per Unit" value?
     

    Attached Files:

  5. peteorstrike

    peteorstrike

    Unity Technologies

    Joined:
    Oct 4, 2013
    Posts:
    116
    Hi @TizzyTool

    It is indeed that setting! Each sprite is a 32x32 pixel image, so when Pixels per Unit is set to 32 it will fit exactly inside a 1 Unity-unit square. This way, you can just use nice round numbers to lay everything out and all the sprites will cleanly snap to Unity's grid.
     
  6. Tekniko

    Tekniko

    Joined:
    Jun 15, 2012
    Posts:
    50
    Thank you, that worked but now I have another issue. If I expand the board it just expands off the screen. So if I was to add 2 more rows of tiles, the game just adds them to the far right. This leaves the entire game board off centre. Do you or anyone else know how to set the board to always be in the centre?

    I also have another issue. The game window can be resized and so on but the assets never change size. So, basically, no matter what size I set the board to, there will never be more than 10 sprites in height being show at any time. Hopefully that made sense.
     
  7. tomtaichii

    tomtaichii

    Joined:
    Sep 2, 2013
    Posts:
    1
    I'm having the same problem as this guy, and I just can't figure out a fix! Its probably so stupidly obvious that I can't see it but could I get some help? I want to add scenes off to the side to do other stuff with but getting the Game Manager to pause or even reset is causing some major difficulties. I've tried forcing the variables to change through a function in the GameManager class but I'm just missing something.

    Anyone got any tips?

    Thanks
     
  8. Tekniko

    Tekniko

    Joined:
    Jun 15, 2012
    Posts:
    50
    Well, I wrote up a few paragraphs explaining how to do this but then my son came in and started spamming keys on my keyboard... Ugh, any ways, here is a link that should help you with pausing your game.

    Time Management
     
  9. Kiori

    Kiori

    Joined:
    Jun 25, 2014
    Posts:
    161
    You guys could add a section on multi-device/ multi res support for the whole game.
     
    Tekniko likes this.
  10. Papiertig0r

    Papiertig0r

    Joined:
    Jun 27, 2014
    Posts:
    4
    Thanks for the hint, I double checked all tags and layer properties also, but still nothing :/

    I added Debug.Log("Collision") in the private void OnTriggerEnter2D (Collider2D other) and the collision seems to be never triggered

    Sorry for the late answer, I was on vacation :)


    [edit]
    I forgot to reenable the boxCollider in MovingObject::Move after the Raycast, I knew it was something small >_o thank you guys anyways!
     
  11. cpjontek

    cpjontek

    Joined:
    Mar 15, 2015
    Posts:
    1
    I finished the tutorial a couple days ago and it works fine. I am trying to add a couple buttons on the game over screen that will allow the user to restart the game or quit the application. I made this script
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class RestartOrQuit : MonoBehaviour {
    5.  
    6.     // Use this for initialization
    7.     void Start () {
    8.    
    9.     }
    10.    
    11.     // Update is called once per frame
    12.     public void ChangeToScene(string LoadLevel)
    13.     {
    14.         Application.LoadLevel(0);
    15.     }
    16.     public void Exit()
    17.     {
    18.         Application.Quit();
    19.     }
    20. }
    this script is attached to a GameObject called MenuManager. Each button is tied to the MenuManager calling the appropriate function. I reference the buttons in the GameManager script and enable them in the GameOver() function. The quit button works but when I hit the restart button it just goes the next level, the player's health stays the same as when he died, the music doesn't restart and the game is essential stuck there. I've tried numerous workarounds such as setting the level to 0 and player health to 100 in the GameOver() function but can't seem to get a good result. Anyone know of an easier way to make a functional restart button with this game?
     
  12. oskar_olw

    oskar_olw

    Joined:
    Mar 17, 2015
    Posts:
    1
    I get the exact same error as thefreehunter. I have tried commenting out huge parts of the code but it doesn't seem to matter which lines are gone, still getting the NullPointers. As far as I can tell I have copied all your code exactly :S
     
  13. JymWythawhy

    JymWythawhy

    Joined:
    Jan 18, 2015
    Posts:
    25
    cpjontek, I believe the problem you are getting is from the "DontDestroyOnLoad" line of the Awake function of the GameManager. That stores the health of the player, and doesn't get reset when you reload the scene, so the player health is carried over between scenes. Normally, that is what we want. In your case, I think your "Restart" function will need to destroy the GameManager object, so that a new GameManager can be made.

    I haven't made a restart button myself, but that is how I would take a first stab at it, anyway.

    (Also, to the creator of the tutorial- fantastic job! I highly enjoyed it, and learned a lot (including about the DontDestroyOnLoad function).)
     
  14. lrg_mark

    lrg_mark

    Joined:
    Mar 16, 2015
    Posts:
    4
    I've been running into an issue where the enemies are not waiting for the player to finish moving before taking their moves. This is causing problems where sometimes enemies will move onto the player's square and prevent the player from being able to move off of them.

    My best guess is that this line in Player.cs:
    Code (CSharp):
    1. GameManager.instance.playersTurn = false;
    is being called before the move is actually completed.

    I've compared my scripts versus the provided ones in Completed and they seem correct. Is this just a bug in the tutorial code or could I potentially have something else incorrect elsewhere in the project that may be causing this to happen?

    It's worth noting that enemies will not move on top of the player if he is attacking a wall (as expected), which is why I don't think it's just a bug with the collision code in general.
     
  15. lrg_mark

    lrg_mark

    Joined:
    Mar 16, 2015
    Posts:
    4
    Digging further, if I set turnDelay to a higher value than 0.1, things will start working. I've triple checked and the moveTime for all units is set to 0.1 as intended, so I'm not sure why turnDelay would need to be set to a higher value to function correctly.
     
  16. ChiefTripodBear

    ChiefTripodBear

    Joined:
    Jan 13, 2015
    Posts:
    2
    I'm having a similar issue to papiertig0r, player won't interact with food, soda or the exit. I walk over them with no collisions. Enemies and walls are interacting ok.

    I'm guessing its because the raycast checks blocking layer and none of these items are ON the blocking layer but unless I'm mistaken this setup is correct. Adding them to the blocking layer causes a collision but now i can't interact with them. Double checked papiertig0r's problem (re-enabling boxcollider) but that isn't my problem. I even tried copying the complete moving object script onto my own, same.

    Food is tagged as food, on default layer and items sorting layer
    Soda is tagged as food, on default layer and items sorting layer
    exit is tagged as exit, on default layer and items sorting layer

    within box collider2d component, all are is_trigger, active and 0.9, 0.9.
     
  17. ProGaminGranny

    ProGaminGranny

    Joined:
    Mar 20, 2015
    Posts:
    1
    upload_2015-3-19_23-51-30.png
    Download doesn't work! I tried in multiple browsers many times, with firewall and Panda antivirus disabled. All it does is open a blank Unity window. This is pissing me off that there isn't any other friggin way to download it. In fact, I cannot download any kind of tutorial, they all have the same issue.

    Somebody please make a download elsewhere! And Unity, fix your silly way of downloading! You need an option for a download. Opening is bound to have problems.
     
  18. peteorstrike

    peteorstrike

    Unity Technologies

    Joined:
    Oct 4, 2013
    Posts:
    116
    @ProGaminGranny have you tried making a new project and opening the Asset Store window from within Unity (ctrl+9) to download the project? I can't say I've ever actually used the Open in Unity option from the website but I'll flag it up with the Asset Store folks and see if this is a known issue.
     
  19. JymWythawhy

    JymWythawhy

    Joined:
    Jan 18, 2015
    Posts:
    25
    Hey all,

    I wanted to get your opinion about where I should start on expanding this tutorial for learning purposes. I have heard that using a game object for every tile is a big no no after your map gets to be a certain size. I have heard two different work-arounds for that problem: 1) map the different tile graphics onto large meshes, so your 1000 sprite game objects turn into 2 larger ones. 2) Use an object pool system, like SpriteTiles, so that the only sprites that exist are the ones currently being seen by the camera- old ones are moved from the retreating edge of view to the incoming edge of view as you scroll, so you might have 1000 tile locations, but only 100 sprite game objects.

    Which do you think is a "better" or more "useful" approach? I know those are subjective, but I wanted your esteemed opinions.

    Thanks!
     
  20. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    That's a good suggestion I think. Will keep in mind going forward.
     
    CDMcGwire likes this.
  21. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    hey guys, sorry for the slow responses for a while I was getting emails notifying me of new posts in this thread but somehow it stopped. Anyway, I'll make an effort to watch the thread going forward. Let me try to answer some of the questions that have come up:

    @Fernando Mondo There actually isn't a mechanism to restart the game in the tutorial. That said if you make a button or keypress that destroys the Game Manager and reloads the scene it should restart properly. The GameManager is set to DontDestroyOnLoad so it needs to be manually destroyed.

    @JymWythawhy I'll have to ask around, I actually haven't done too much tile stuff with big maps. I'd give it a try first, how big is 'a certain size'? The object pooling approach sounds plausible but I'd make sure it's necessary first.
     
    Last edited: Mar 20, 2015
  22. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    @cpjontek see @JymWythawhy answer, you need to Destroy the GM to actually reset. It will be re-instantiated with default values by the Loader script.
     
  23. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    @Razzberry the lowest value for moveTime that works is 0.1, this is actually something I struggled with for a few days before deciding I had to move on. This is the only way I could get it to work so that all enemies and player move in sequence relatively quickly without moving onto each other's squares and breaking the game. The other issue with this that you may or may not have noticed is that the movetime accumulates as you add enemies, so the players movement gets slower. On a touchscreen people can't swipe that fast so I decided to leave it as is but it was something I ended up having to ship with I wasn't completely satisfied by. If anyone thinks of a better implementation I'm all ears!
     
  24. Matthew-Schell

    Matthew-Schell

    Joined:
    Oct 1, 2014
    Posts:
    238
    @ChiefTripodBear the pickups and exit actually aren't done using the Raycast, they're using OnTriggerEnter. Make sure that the player collider is on and that the pickups and exit are on Layer Default and set to isTrigger (sounds like they are). Then double check that the OnTriggerEnter calls in Player (113-146) are firing correctly when you move into those spaces.
     
  25. JymWythawhy

    JymWythawhy

    Joined:
    Jan 18, 2015
    Posts:
    25
    Hmm, I am not certain how big "a certain size" is- I have just heard that having large tile maps made out of game objects can lead to slow downs, especially on mobile. I will have to try some different methods and see what gives me the best result. It will be fun to learn the different approaches, and now that I have access to the Profiler (Thanks Unity!!!), I can see what is hogging the computer the most.
     
  26. beanshaped

    beanshaped

    Joined:
    Mar 23, 2015
    Posts:
    1
    Hi, great tutorial.

    By day I'm a Java developer and I'm new to c#.

    I have a specific question in relation to the AttemptMove function in the abstract class MovingObject. If we have the variable bool canMove, why do we need to check hit.transform == null? Is it not already checked via the Move function? So you can only move if nothing was hit.

    So can we not just use if (canMove) instead of if (hit.transform == null)?

    I think I'm definitely missing something here. Is it to do with the StartCoroutine function and it's async nature?

    Code (CSharp):
    1. //Set canMove to true if Move was successful, false if failed.
    2. bool canMove = Move (xDir, yDir, out hit);
    3.  
    4. //Check if nothing was hit by linecast
    5. if(hit.transform == null)
    6. //If nothing was hit, return and don't execute further code.
    7. return;
     
    Last edited: Mar 23, 2015
  27. Blackdrazon

    Blackdrazon

    Joined:
    Mar 3, 2015
    Posts:
    5
    I'm in the middle of Step 5 right now, after the board and game managers are first tested (though my problems may be from Step 4, when the board manager was written). I have two problems, one less serious than the other. The big problem are these sketchy lines that appear between certain tiles, especially the border. If you squint, you can also see them running below every other row, starting with the first:



    The second issue is also visible: there is only one enemy in the room, no matter how many times I reload. My level is indeed set to 3, but in the example video two enemies spawn. More enemies do show up on higher levels. Maybe I'm doing the math wrong, but it seems like level 3 should only have one enemy, but the video does show two...

    I'm using Unity 4.6, and I've attached the code into the following spoiler.

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

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    For what it's worth, and as far as I know, this is an editor resolution issue and won't show up in the build of your game.

    I'm not familiar enough with this project to comment on the other points, so will have to defer to Matt, but at this point I wouldn't worry about those artifacts unless you see them in your build.

    Have you tried making sure your editor window is the same resolution and aspect ratio as your output device? This may help.
     
  29. Blackdrazon

    Blackdrazon

    Joined:
    Mar 3, 2015
    Posts:
    5
    Hm, yes, you're right, going into Free Aspect and playing with the vertical size of the window fixes the problem. Thanks!
     
  30. MrConkin

    MrConkin

    Joined:
    Feb 11, 2013
    Posts:
    20
    I'm part way through video 5 where it asks me to test the scene (after setting up the GameManager script and assigning the prefabs to the arrays). However, every time I try to test I am met with an endless load and have to force close Unity. I've gone over the BoardManager and GameManager scripts a couple of times and verified them with the tutorial. Any ideas what might be happening?

    Not sure if this matters, but when I open up the project in Unity again it opens an Untitled scene and I have to manually open the Main scene again. Really want to get through this tutorial so any help is appreciated!
     
  31. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    This sounds like an infinite loop. I don't know this project very well, but, do many of the scripts at this point have a coroutine? And could that coroutine be missing a yield? Or no way to end? Look for a coroutine and triple check that the code it correct.
     
  32. MrConkin

    MrConkin

    Joined:
    Feb 11, 2013
    Posts:
    20
    No coroutines as far as I know. Considering I was so early on in the tutorial, I started from scratch and everything is working great. A bit frustrating not know what was wrong, but onwards I go! Thanks for the reply Adam.
     
  33. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Glad it worked out! Sorry we didn't find out why, but sometimes it's not worth finding out.
     
  34. samuel8891

    samuel8891

    Joined:
    Apr 1, 2015
    Posts:
    3
  35. samuel8891

    samuel8891

    Joined:
    Apr 1, 2015
    Posts:
    3
    Hi Matthew Schell,

    Congratulations in your initiative for this tutorial.

    I'm in part 5 (Writing the Game Manager) and in my project under the scripts in Game Manager it does not show the variables Exit, Wall Count, etc... like in the video so I can drag the prefabs. I'm using Unity 4.6 and it says there is an error in my BoardManager script but I copied and pasted like in the tutorial. It says "Assets/Scripts/BoardManager.cs(10,22): error CS0101: The namespace `Completed' already contains a definition for `BoardManager')"

    Sorry if my question seems dumb but I'm still new to game development, C# and Unity.
    I'm also sending 2 pictures attached to see if anyone can help me.
     
  36. Zergling

    Zergling

    Joined:
    Mar 24, 2015
    Posts:
    4
    Hi,

    Amazing tutorial! I can see that I have a lot to learn. I'm a new developer and just trying to learn how to follow the math of your object movement. I'm confused about the variable moveTime that you set as 0.1f. In the video, you state that the units are seconds. Later it is used as a parameter in the Vector3.MoveToward function:

    Vector3 newPosition = Vector3.MoveTowards(rb20.position, end, inverseMoveTime * Time.deltaTime);

    Assuming the moveTime is in units of seconds, by dimensional analysis, the third argument of MoveTowards would be dimensionless. But if you look at the reference for the function or the actual contents of the function, maxdistancedelta (the third argument) should be a distance. Meaning the units of MoveTime( ) are game units per second and the units of Time.deltaTime are seconds which leaves a distance of game units. Then the question becomes is MoveTime( ) is a speed and if not, what am I missing?

    The other things that confuses me is the concept of inverseMoveTime. Why create the reciprocal 0.1f instead of just setting the MoveTime() = 10, which is the same thing.

    Sorry if the question seems basic. Hope you can help clarify for me. Thanks
     
  37. Nomorewine

    Nomorewine

    Joined:
    Apr 2, 2015
    Posts:
    1
    Samuel, you might want to check this https://msdn.microsoft.com/en-us/library/z2kcy19k.aspx
    I'm new to C#, but my guess is if you remove the line (namespace ....) and the corresponding brackets, the error should be gone.
     
  38. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    Matt may have to get into the details, as I'm not that familiar with the inner details of this project.

    Some notes and clues:
    If you have a compile error, the scripts will not have been integrated properly into the project and the components won't be updated, as they failed to compile. SO - while you have an unfixed error, you won't see any of the new properties on the script component you have written.

    Code (csharp):
    1. "Assets/Scripts/BoardManager.cs(10,22): error CS0101: The namespace `Completed' already contains a definition for `BoardManager')"
    This tells you where the error is: in the script Assets/Scripts/BoardManager.cs on line 10 and the error is that "completed" has already been defined.

    See if you can track this down.

    This is probably related to using the "done" or "completed" version of the project, or duplicating / copy-pasting code fromt he completed material, which is separated from the work you are doing by the namespace "completed".
     
    jonathan-cedrim likes this.
  39. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    jonathan-cedrim likes this.
  40. samuel8891

    samuel8891

    Joined:
    Apr 1, 2015
    Posts:
    3
    Nomorewine you are the best man. I removed the line namespace and it worked.

    Adam Buckner thanks for your help.
     
  41. Unicorn_Rocket

    Unicorn_Rocket

    Joined:
    Dec 11, 2014
    Posts:
    1
    Thanks for this excellent tutorial. I'm working on extending from the tutorial to learn some other new concepts, and the first thing I did was implement a moving camera that follows the player. It works well, but of course, now I'm working on extending the board so its actually worth scrolling around.

    It seemed to me that changing the public int columns and rows in BoardManager would be the straightforward approach, but it has no effect. During BoardSetup(), we iterate over those columns and rows in for loops from 0 until x or y is < rows or columns + 1, and then we Instantiate() a floorTile. But setting columns or rows to a higher number, I still get the board from the tutorial

    I'm not sure how to begin to troubleshoot this. My suspicion is that something is going on between the Loader -> GameManager -> BoardManager referencing process and some kind of caching via use of the DontDestroyOnLoad, but I don't have much understanding of the loading/instantiating part of the platform and how it might store an old object.

    Any thoughts?

    TL;DR - Changing the columns/rows variables doesn't expand the size of the game board as expected.
     
  42. sfried

    sfried

    Joined:
    Apr 4, 2015
    Posts:
    3
    Hello,

    I'm trying to repurpose the script I found in this tutorial to be utilized in an overhead sprite-based 2D game a la Zelda. The problem I have is that I know nothing about C#, and I've been try my best to tinker around with variables within the script hoping it would help with character positioning. I couldn't quite get my character to move in a gridded space defined by particular boundaries.
     
  43. OboShape

    OboShape

    Joined:
    Feb 17, 2014
    Posts:
    836
    Evening @sfried. just to get a jump start with c#, probably best to visit the learn section and get the basics of the language under your belt, that way as you tinker and change parameters/variables you will have a better understanding of their principles. have a look through some of these tutorials.....

    http://unity3d.com/learn/tutorials/modules/beginner/scripting
     
  44. sfried

    sfried

    Joined:
    Apr 4, 2015
    Posts:
    3
    That seems like alot of reading. Is there anything that will let me be able to grasp C# in under an hour? I feel like I'm trying to learn 2 different languages here (Unity & C#), and I'm sort of constrained on time.
     
    Last edited: Apr 5, 2015
  45. Jaimito23

    Jaimito23

    Joined:
    Mar 18, 2015
    Posts:
    2
    I have been working on the roguelike tutorial and i am having a problem with the BoardManager script. I keep getting an error saying ArgumentException: The thing you want to instantiate is null.

    when i click on the error to see where it is it takes to the:

    Instantiate(tileChoice, randomPosition, Quaternion.identity);

    I have copied the code provided in the tutorial and I still get the error. here is the code i have

    Code (CSharp):
    1. using UnityEngine;
    2. using System;
    3. using System.Collections.Generic;       //Allows us to use Lists.
    4. using Random = UnityEngine.Random;      //Tells Random to use the Unity Engine random number generator.
    5.  
    6.  
    7. public class BoardManager : MonoBehaviour
    8. {
    9.     // Using Serializable allows us to embed a class with sub properties in the inspector.
    10.     [Serializable]
    11.     public class Count
    12.     {
    13.         public int minimum;             //Minimum value for our Count class.
    14.         public int maximum;             //Maximum value for our Count class.
    15.        
    16.        
    17.         //Assignment constructor.
    18.         public Count (int min, int max)
    19.         {
    20.             minimum = min;
    21.             maximum = max;
    22.         }
    23.     }
    24.    
    25.    
    26.     public int columns = 8;                                         //Number of columns in our game board.
    27.     public int rows = 8;                                            //Number of rows in our game board.
    28.     public Count wallCount = new Count (5, 9);                      //Lower and upper limit for our random number of walls per level.
    29.     public Count foodCount = new Count (1, 5);                      //Lower and upper limit for our random number of food items per level.
    30.     public GameObject exit;                                         //Prefab to spawn for exit.
    31.     public GameObject[] floorTiles;                                 //Array of floor prefabs.
    32.     public GameObject[] wallTiles;                                  //Array of wall prefabs.
    33.     public GameObject[] foodTiles;                                  //Array of food prefabs.
    34.     public GameObject[] enemyTiles;                                 //Array of enemy prefabs.
    35.     public GameObject[] outerWallTiles;                             //Array of outer tile prefabs.
    36.    
    37.     private Transform boardHolder;                                  //A variable to store a reference to the transform of our Board object.
    38.     private List <Vector3> gridPositions = new List <Vector3> ();   //A list of possible locations to place tiles.
    39.    
    40.    
    41.     //Clears our list gridPositions and prepares it to generate a new board.
    42.     void InitialiseList ()
    43.     {
    44.         //Clear our list gridPositions.
    45.         gridPositions.Clear ();
    46.        
    47.         //Loop through x axis (columns).
    48.         for(int x = 1; x < columns-1; x++)
    49.         {
    50.             //Within each column, loop through y axis (rows).
    51.             for(int y = 1; y < rows-1; y++)
    52.             {
    53.                 //At each index add a new Vector3 to our list with the x and y coordinates of that position.
    54.                 gridPositions.Add (new Vector3(x, y, 0f));
    55.             }
    56.         }
    57.     }
    58.    
    59.    
    60.     //Sets up the outer walls and floor (background) of the game board.
    61.     void BoardSetup ()
    62.     {
    63.         //Instantiate Board and set boardHolder to its transform.
    64.         boardHolder = new GameObject ("Board").transform;
    65.        
    66.         //Loop along x axis, starting from -1 (to fill corner) with floor or outerwall edge tiles.
    67.         for(int x = -1; x < columns + 1; x++)
    68.         {
    69.             //Loop along y axis, starting from -1 to place floor or outerwall tiles.
    70.             for(int y = -1; y < rows + 1; y++)
    71.             {
    72.                 //Choose a random tile from our array of floor tile prefabs and prepare to instantiate it.
    73.                 GameObject toInstantiate = floorTiles[Random.Range (0,floorTiles.Length)];
    74.                
    75.                 //Check if we current position is at board edge, if so choose a random outer wall prefab from our array of outer wall tiles.
    76.                 if(x == -1 || x == columns || y == -1 || y == rows)
    77.                     toInstantiate = outerWallTiles [Random.Range (0, outerWallTiles.Length)];
    78.                
    79.                 //Instantiate the GameObject instance using the prefab chosen for toInstantiate at the Vector3 corresponding to current grid position in loop, cast it to GameObject.
    80.                 GameObject instance =
    81.                     Instantiate (toInstantiate, new Vector3 (x, y, 0f), Quaternion.identity) as GameObject;
    82.                
    83.                 //Set the parent of our newly instantiated object instance to boardHolder, this is just organizational to avoid cluttering hierarchy.
    84.                 instance.transform.SetParent (boardHolder);
    85.             }
    86.         }
    87.     }
    88.    
    89.    
    90.     //RandomPosition returns a random position from our list gridPositions.
    91.     Vector3 RandomPosition ()
    92.     {
    93.         //Declare an integer randomIndex, set it's value to a random number between 0 and the count of items in our List gridPositions.
    94.         int randomIndex = Random.Range (0, gridPositions.Count);
    95.        
    96.         //Declare a variable of type Vector3 called randomPosition, set it's value to the entry at randomIndex from our List gridPositions.
    97.         Vector3 randomPosition = gridPositions[randomIndex];
    98.        
    99.         //Remove the entry at randomIndex from the list so that it can't be re-used.
    100.         gridPositions.RemoveAt (randomIndex);
    101.        
    102.         //Return the randomly selected Vector3 position.
    103.         return randomPosition;
    104.     }
    105.    
    106.    
    107.     //LayoutObjectAtRandom accepts an array of game objects to choose from along with a minimum and maximum range for the number of objects to create.
    108.     void LayoutObjectAtRandom (GameObject[] tileArray, int minimum, int maximum)
    109.     {
    110.         //Choose a random number of objects to instantiate within the minimum and maximum limits
    111.         int objectCount = Random.Range (minimum, maximum+1);
    112.        
    113.         //Instantiate objects until the randomly chosen limit objectCount is reached
    114.         for(int i = 0; i < objectCount; i++)
    115.         {
    116.             //Choose a position for randomPosition by getting a random position from our list of available Vector3s stored in gridPosition
    117.             Vector3 randomPosition = RandomPosition();
    118.            
    119.             //Choose a random tile from tileArray and assign it to tileChoice
    120.             GameObject tileChoice = tileArray[Random.Range (0, tileArray.Length)];
    121.            
    122.             //Instantiate tileChoice at the position returned by RandomPosition with no change in rotation
    123.             Instantiate(tileChoice, randomPosition, Quaternion.identity);
    124.         }
    125.     }
    126.    
    127.    
    128.     //SetupScene initializes our level and calls the previous functions to lay out the game board
    129.     public void SetupScene (int level)
    130.     {
    131.         //Creates the outer walls and floor.
    132.         BoardSetup ();
    133.        
    134.         //Reset our list of gridpositions.
    135.         InitialiseList ();
    136.        
    137.         //Instantiate a random number of wall tiles based on minimum and maximum, at randomized positions.
    138.         LayoutObjectAtRandom (wallTiles, wallCount.minimum, wallCount.maximum);
    139.        
    140.         //Instantiate a random number of food tiles based on minimum and maximum, at randomized positions.
    141.         LayoutObjectAtRandom (foodTiles, foodCount.minimum, foodCount.maximum);
    142.        
    143.         //Determine number of enemies based on current level number, based on a logarithmic progression
    144.         int enemyCount = (int)Mathf.Log(level, 2f);
    145.        
    146.         //Instantiate a random number of enemies based on minimum and maximum, at randomized positions.
    147.         LayoutObjectAtRandom (enemyTiles, enemyCount, enemyCount);
    148.        
    149.         //Instantiate the exit tile in the upper right hand corner of our game board
    150.         Instantiate (exit, new Vector3 (columns - 1, rows - 1, 0f), Quaternion.identity);
    151.     }
    152. }
     
  46. eL_Jay

    eL_Jay

    Joined:
    Nov 27, 2013
    Posts:
    7
    NEW:
    I have solved the problem there appears to be a missing closing curly bracket at the end in the supplied code.

    OLD
    Sadly the GameManager script in tutorial 4 renders my build useless.

    I have tried 3 versions of the GameManager script:
    1 Via the tutorial
    2 Via copying below the tutorial
    3 Custom script from the internet

    All these scripts keep giving me errors.

    A few of these errors where linked to file-conflict since the script in the assets/scripts folder and the assets/completed/scripts folder conflicted with each other.

    Now i have removed this completed map and copied the script from beneath the tutorial video 4 but i still keep getting errors.
    Assets/Scripts/GameManager.cs(55,1): error CS8025: Parsing error


    Any help would be appreciated.

    Script:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. namespace Completed
    5. {
    6.     using System.Collections.Generic;       //Allows us to use Lists.
    7.  
    8.     public class GameManager : MonoBehaviour
    9.     {
    10.  
    11.         public static GameManager instance = null;              //Static instance of GameManager which allows it to be accessed by any other script.
    12.         private BoardManager boardScript;                       //Store a reference to our BoardManager which will set up the level.
    13.         private int level = 3;                                  //Current level number, expressed in game as "Day 1".
    14.  
    15.         //Awake is always called before any Start functions
    16.         void Awake()
    17.         {
    18.             //Check if instance already exists
    19.             if (instance == null)
    20.              
    21.                 //if not, set instance to this
    22.                 instance = this;
    23.          
    24.             //If instance already exists and it's not this:
    25.             else if (instance != this)
    26.              
    27.                 //Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager.
    28.                 Destroy(gameObject);  
    29.          
    30.             //Sets this to not be destroyed when reloading scene
    31.             DontDestroyOnLoad(gameObject);
    32.          
    33.             //Get a component reference to the attached BoardManager script
    34.             boardScript = GetComponent<BoardManager>();
    35.          
    36.             //Call the InitGame function to initialize the first level
    37.             InitGame();
    38.         }
    39.      
    40.         //Initializes the game for each level.
    41.         void InitGame()
    42.         {
    43.             //Call the SetupScene function of the BoardManager script, pass it current level number.
    44.             boardScript.SetupScene(level);
    45.          
    46.         }
    47.      
    48.      
    49.      
    50.         //Update is called every frame.
    51.         void Update()
    52.         {
    53.          
    54.         }
    55. }
     
    Last edited: Apr 9, 2015
  47. eL_Jay

    eL_Jay

    Joined:
    Nov 27, 2013
    Posts:
    7
    I had exactly the same problem. using this script solved it for me, however I think there is bug in this code since during testing only 1 enem
    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using System;
    4. using System.Collections.Generic;
    5. using Random = UnityEngine.Random;
    6. public class BoardManager : MonoBehaviour {
    7.    [Serializable]
    8.    public class Count {
    9.      public int minimum;
    10.      public int maximum;
    11.      public Count(int min, int max) {
    12.        minimum = min;
    13.        maximum = max;
    14.      }
    15.    }
    16.    public int columns = 8;
    17.    public int rows = 8;
    18.    public Count wallCount = new Count(5, 9);
    19.    public Count foodCount = new Count(1, 5);
    20.    public GameObject exit;
    21.    public GameObject[] floorTiles;
    22.    public GameObject[] foodTiles;
    23.    public GameObject[] enemyTiles;
    24.    public GameObject[] wallTiles;
    25.    public GameObject[] outerWallTiles;
    26.    private Transform boardHolder;
    27.    private List<Vector3> gridPositions = new List<Vector3>();
    28.    void InitializeList() {
    29.      gridPositions.Clear();
    30.      for(int x = 1; x< columns - 1; x++) {
    31.        for(int y = 1; y < rows - 1; y++) {
    32.          gridPositions.Add(new Vector3(x, y, 0f));
    33.        }
    34.      }
    35.    }
    36.    void BoardSetup() {
    37.      boardHolder = new GameObject("Board").transform;
    38.      for(int x = -1; x< columns + 1; x++) {
    39.        for(int y = -1; y < rows + 1; y++) {
    40.          GameObject toInstantiate = floorTiles[Random.Range(0, floorTiles.Length)];
    41.          if(x == -1 || x == columns || y == -1 || y == rows)
    42.            toInstantiate = outerWallTiles[Random.Range(0, outerWallTiles.Length)];
    43.          GameObject instance = Instantiate(toInstantiate, new Vector3(x, y, 0f), Quaternion.identity) as GameObject;
    44.          instance.transform.SetParent(boardHolder);
    45.        }
    46.      }
    47.    }
    48.    Vector3 RandomPosition() {
    49.      int randomIndex = Random.Range(0, gridPositions.Count);
    50.      Vector3 randomPosition = gridPositions[randomIndex];
    51.      gridPositions.RemoveAt(randomIndex);
    52.      return randomPosition;
    53.    }
    54.    void LayoutObjectAtRandom(GameObject[] tileArray, int min, int max) {
    55.      int objectCount = Random.Range(min, max + 1);
    56.      for(int i = 0; i < objectCount; i++) {
    57.        Vector3 randomPosition = RandomPosition();
    58.        GameObject tileChoice = tileArray[Random.Range(0, tileArray.Length)];
    59.        Instantiate(tileChoice, randomPosition, Quaternion.identity);
    60.      }
    61.    }
    62.    public void SetupScene(int level) {
    63.      BoardSetup();
    64.      InitializeList();
    65.      LayoutObjectAtRandom(wallTiles, wallCount.minimum, wallCount.maximum);
    66.      LayoutObjectAtRandom(foodTiles, foodCount.minimum, foodCount.maximum);
    67.      int enemyCount = (int)Mathf.Log(level, 2f);
    68.      LayoutObjectAtRandom(enemyTiles, enemyCount, enemyCount);
    69.      Instantiate(exit, new Vector3(columns - 1, rows - 1, 0f), Quaternion.identity);
    70.    }
    71. }
    72.  
    y is rendered.

    P.s. my goal with this tutorial is not to learn C# (since i use JS), but another handson approach on unity itself.
     
  48. eL_Jay

    eL_Jay

    Joined:
    Nov 27, 2013
    Posts:
    7
    I lolled, learning a computer language in one hour!!!! Even HTML en SQL take more then an hour to learn. (and are the easiest languages i know about)

    Unity is the framework/sdk/IDE (i dont know the exact differences) in which u can use a scripting language like C# or Javascript. You have to learn both (the framework and a language) to use unity imo.
     
  49. yuvalk

    yuvalk

    Joined:
    Apr 9, 2015
    Posts:
    1
    I have a question about the 13 video (sound effects).

    You added the line "if (Move (xDir, yDir, out hit)) {" to check if the player can move, but shouldn't this line actually make the player move twice? I know it only moves once but I don't understand why.
     
  50. Adam-Buckner

    Adam-Buckner

    Joined:
    Jun 27, 2007
    Posts:
    5,664
    I don't know this project very well, but, have you double checked all the steps in the tutorial? This sounds like the code could be correct (I've not read it), but you may have missed a step in the editor portion? Do you need to associate / drag an element into a slot in the inspector?
     
Thread Status:
Not open for further replies.