Search Unity

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

[Tutorial] Classic 2D Snake in C#

Discussion in 'Community Learning & Teaching' started by raiden, Sep 30, 2012.

  1. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Hi all, recently I was googling around for some old classic games, and i ran across the old classic Snake game and thought, that would be cool to write in Unity, so I did. Then I decided to make a tutorial out of it, so that I can show others some intermediate C# techniques.

    Keep in mind the focus of this is purely programming. What you'll be doing is building the game from 4 sounds and nothing else but code.

    Here is the web player: 2D Snake Game

    Here is the tutorial documentation: 2D Snake Tutorial

    Here are the 4 sounds used in the game: 2D Snake Game Sounds

    Although I recommend building everything from the documentation, if your interested in the project files, you can get them here: 2D Snake Game Project Files

    The goal is to show you how singletons work, and how you can use programming to build things at run time. The code is clean and well commented, so you shouldn't have any issues following along, but please let me know if you do have any questions, I'll be glad to help you as much as I can.

    Hope you enjoy!

    -Raiden
     
    Last edited: Apr 2, 2017
    jhocking and LadyAth like this.
  2. GTGD

    GTGD

    Joined:
    Feb 7, 2012
    Posts:
    436
    Thanks for sharing this tutorial. I've been trying to nail down my understanding of Singletons and what I can use them for and I believe I do have a fair understanding now. I've gotten through most of the tutorial and I really like your code and comment structure and in fact I'm intending to change over to your style from my current style.

    Does using Singletons and dynamic instantiation improve performance versus relying on the Update function, if statements, and GameObject.Find? I always try to type as little code as possible but I'm always looking to write more efficient code.

    Thank you.
     
  3. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Hi GTGD, thank you for your comments. I'm glad you like my style of coding. I'm constantly striving to write clean, commented and well structured code so that it makes it easy to go back to old projects and know what's going on. :)

    Using singletons, I believe do improve performance. Things like: GameObject.Find(), FindWithTag() will give you a performance hit, so it's important even when your not using singletons to cache objects and/or components in Start() so that Unity doesn't do routine lookups each time you reference them (for me even if it is once).

    There is only 1 drawback to using singletons, and that is as far as I know your allowed only 1 instance of the object you are accessing, so for example in the tutorial if you wanted to have multiple "Food" objects, then the Instance would only be the first stored instance of the any 1 of the multiple Food objects created in scene, therefore giving you a possible incorrect reference.

    Let me know if you have any other questions, I'll be looking at other classic's to see what I can come up with next.

    Thanks again

    -Raiden
     
  4. Ramsar

    Ramsar

    Joined:
    Jul 22, 2012
    Posts:
    34
    Thanks for the thorough tutorial. It's always nice to have some new text based tutorials.

    I've got some (slightly more ambitious) suggestions :)
    - A classic RTS? Remaking the original Red Alert would be fun.
    - Or a hack 'n slash RPG like the original Diablo?
    - Or the original Grand Theft Auto?
     
  5. wav

    wav

    Joined:
    Dec 7, 2011
    Posts:
    4
    Great Tutorial, really helped me understand singletons a bit better.

    One thing though - the food.cs and ScreenDeath.cs sections seem to be missing from the pdf!

    Otherwise, top notch, thank you!
     
  6. scarpelius

    scarpelius

    Joined:
    Aug 19, 2007
    Posts:
    966
    Is the movement of the snake made on purpose that slow/hard? Haven't got the chance to look at code to see if is something wrong.
     
  7. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Thank you all for your replies.

    Good catch wav, I'm updating the docs, i'll have them done soon.

    The movement style does not mimic the original, it's just a style i picked. The idea was increment the speed each time you ate a food and grew a tail, so it actually gets a little more difficult the longer you get, well as long as your holding down the key to move :).

    -Raiden
     
  8. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Just wanted to let everyone know, the tutorial pdf has been updated to include Food.cs and ScreenDeath.cs, as well as some typo fixes.

    Thanks

    -Raiden
     
  9. jimmyzhou

    jimmyzhou

    Joined:
    Jun 13, 2013
    Posts:
    1
    excellent article ,thank you very much for giving so detail sample.
     
  10. SChan

    SChan

    Joined:
    Jul 20, 2013
    Posts:
    2
    First of all, thank you so much for making this tutorial. It has helped me tremendously in learning how to use C# and Unity to make this game.

    I do have a question. A lot of the code (as you also stated in the PDF) are very similar if not, exactly the same, but just in different script files. To further your stress on good coding, wouldn't it have been better to create an interface or a parent class with those repeated methods and then create new classes that inherit from them? This way, the Lives script will only have the "UpdateLivesText" method while it inherits all the other methods.

    I'm not sure if you purposely left it out because it's a beginner's tutorial or Unity doesn't like polymorphism/inheritance or whatever, so any insights as to why you decided to repeat code (which is considered against the OOP way) would be great.

    Thanks,

    SChan
     
  11. SubZeroGaming

    SubZeroGaming

    Joined:
    Mar 4, 2013
    Posts:
    1,008
    Excellent job my friend.
     
  12. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Thanks so much for the great comments.
    I agree SChan, repeatable code is not well designed OOP programming, but to be honest, I don't do much coding around inheritance or polymorphism. I used some repeat code, mainly just to keep the objects methods to themselves only, and well its also a way I consider a simpler style of programming, by having similar functions written out, but keeping them within each objects class.

    Somewhere down the road, I'll step it up, and if I come up with another tutorial similar to this, I'll add in more intermediate solutions.

    @Ramsar
    Probably won't be a tutorial to that degree, but I like your ideas. :)

    Thanks again everyone.

    -Raiden
     
  13. SChan

    SChan

    Joined:
    Jul 20, 2013
    Posts:
    2
    Awesome. I'll be looking forward to your tutorials. Thanks again for all that you do for everyone.
     
  14. Noctys

    Noctys

    Joined:
    Aug 23, 2013
    Posts:
    37
    Thanks for this code - it helped me out with learning how to program games in Unity only using code. That being said there is a TON of repeat code that could be moved to methods and/or base classes. Especially with items like Lives Scores, ScreenBorder ScreenField, also with the movement of the snake. Using singletons for things like that instead of objects makes programming more difficult in the long run.

    In a previous post you said: "used some repeat code, mainly just to keep the objects methods to themselves only, and well its also a way I consider a simpler style of programming, by having similar functions written out, but keeping them within each objects class."

    I agree that it makes it easier to read but not when it comes to maintaining code. Anytime you find yourself cutting and pasting code you should be asking: Could I create a base-class or a method to do this?

    It would be really good for you, and future reader of this tutorial, if you were to go back and create this using good OO deign principles. Either way though thanks for this tutorial as it did help me out a lot on the Unity end of things.
     
    Last edited: Aug 23, 2013
  15. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    I agree completely Noctys, so I have gone back through, looked at some areas you mentioned and re-programmed them in a much more logical manner.

    To All: The pdf and project file links have been updated at the start of this thread

    I would really be interested in everyone's thoughts as to how I have removed duplicate code and made it more useful. I like my results, because not only have I made reusable code with the helper scripts, but it allowed me to reduce the overall number of scripts for the game. I have also introduced Method Overloading, you'll see how it is used in the helper scripts.

    One thing I would like to point out, is I am not using Inheritance in any of my code, the reason being is that there are no relationships with any of the games objects, Inheritance should be used on a "is a" basis, and all of my objects are on a "has a" basis. Example: SnakeGame is simply the container for the games items, so to me it wouldn't make sense for SnakeGame to Inherit because all of the objects used in SnakeGame are simply what it "has", and not what it "is".

    I hope that makes sense, but I am definitely open for suggestions or improvements. I'm not an advanced programmer, i just like to think i can halfway code :D

    Hope everyone enjoys the updates and learns a few things.

    -Raiden
     
    Noctys likes this.
  16. paffy

    paffy

    Joined:
    Oct 3, 2013
    Posts:
    1
    how can you make the snake starts by itself? ex you dont have to press forward, but the snake it should go by itself forward, and you just controll the left right, up down arrows...and maybe a bit smaller the design... Thanks a lot for this game, im beginner, but just asked about how can the snake go forward by itself :) thanks a lot again man, we appreciate this help.
     
    Last edited: Oct 3, 2013
  17. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Hi paffy, I'm glad you like the tutorial.

    We can achieve auto movement for the snake very easy and it only requires some minor changes in 1 script. Open up Snake.cs and look at lines: 19-26 for this:
    Code (csharp):
    1.  
    2. // direction enum for clarification
    3. public enum Direction
    4. {
    5.     UP,
    6.     DOWN,
    7.     LEFT,
    8.     RIGHT
    9. }
    Now we want to create a new field of type Direction, so add this underneath the above code in your Snake.cs:
    Code (csharp):
    1.  
    2. public Direction mState = Direction.LEFT
    Ok, so next thing we need to do is make some changes in our UpdateSnake method, scroll down, starting at line 99, and make the following changes:
    Code (csharp):
    1.  
    2. // are we moving up                            
    3. if (InputHelper.GetStandardMoveUpDirection())
    4. {
    5.     //yield return StartCoroutine(MoveSnake(Direction.UP));
    6.     mState = Direction.UP;
    7.     //Debug.Log ("We are moving UP");
    8. }
    9.    
    10. // are we moving left
    11. if (InputHelper.GetStandardMoveLeftDirection())
    12. {
    13.     //yield return StartCoroutine(MoveSnake(Direction.LEFT));
    14.     mState = Direction.LEFT;
    15.     //Debug.Log ("We are moving LEFT");
    16. }
    17.            
    18. // are we moving down
    19. if (InputHelper.GetStandardMoveDownDirection())
    20. {
    21.     //yield return StartCoroutine(MoveSnake(Direction.DOWN));
    22.     mState = Direction.DOWN;
    23.     //Debug.Log ("We are moving DOWN");
    24. }
    25.            
    26. if (InputHelper.GetStandardMoveRightDirection())
    27. {
    28.     //yield return StartCoroutine(MoveSnake(Direction.RIGHT));
    29.     mState = Direction.RIGHT;
    30.     //Debug.Log ("We are moving RIGHT");
    31. }
    Notice we commented out directly moving the snake and we are simply setting the mState Direction field. Now we code in moving the snake based on Direction. Right below the above lines of code, add this:
    Code (csharp):
    1.  
    2. // run the snake movement constant based on Direction
    3. yield return StartCoroutine(MoveSnake(mState));
    4.  
    Save your script, and there you go, your snake should be off and running by itself, and will keep moving based on your keyboard input. If you have any issues, or questions, please let me know.

    -Raiden
     
  18. Aoi cyou

    Aoi cyou

    Joined:
    Oct 15, 2013
    Posts:
    1
    The article mentioned overloading, does unity support default parameters C#?
     
  19. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Hi Aoi cyou, could you provide some more details? You can use any type of field as a parameter (float, int, List<>, etc.). I'm not quite sure what your asking.

    -Raiden
     
  20. omelchor

    omelchor

    Joined:
    Jun 15, 2011
    Posts:
    20
    Excellent.
     
  21. zero_null

    zero_null

    Joined:
    Mar 11, 2014
    Posts:
    159
    Can I ask a Question. Raidan ???? Are u still there??? I know the post is about 2 years old. I need you help man
     
  22. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Would like to thank everyone for their comments. Also, I received an email from Nadav, which pointed out an error in the documentation. The SnakeGame.cs Initialization method was not calling the proper Create methods for the GUIHelper script. I have corrected the pdf tutorial, it is updated in above in my first post. Thanks to Nadav for finding that. :)

    Also, was just playing around with the game today, it's still fairly easy with the controls setup the way they are, but i thought i would share a pretty decent score with everyone.

    $HighScore.png

    -Raiden
     
    Last edited: Apr 2, 2014
  23. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Sure, ask away, I'll do my best to help you out.

    -Raiden
     
  24. abajurcu

    abajurcu

    Joined:
    Apr 29, 2014
    Posts:
    1
    Hi Raiden,
    Thanks for the great tutorial.its help me alot to understanding basics of Unity. (im just beginner)
    Do you have any tutorials like this around ?

    regards
     
  25. AttractiveWatermelon

    AttractiveWatermelon

    Joined:
    Jun 21, 2014
    Posts:
    1
    Hey Raiden,
    Just as i was starting this, i followed the tutorial along and i got this error after the GUIHelper part...
    Assets/Scripts/Utils/GUIHelper.cs(68,45): error CS0120: An object reference is required to access non-static member `UnityEngine.Component.guiTexture'
    Do you know how to fix this? Thanks.
     
  26. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Hi DatEagleEye, sorry for the late reply.

    I could not duplicate that error, unzipping that original project and also comparing it to the docs, everything worked for me. Make sure your methods in GUIHelper are static, and double check your code with the code files in the original project to see if there is a mistake. I'd be happy to check your project if you'd like to send me a link.

    -Raiden
     
  27. pecko95

    pecko95

    Joined:
    Jun 29, 2014
    Posts:
    2
    Hey ! First of all, I'd like to say, thank you very much for the whole tutorial and effort that you've put into it, as it is really helpful, especially for me, because im still a beginner with Unity and programming.

    I would like to ask you this. Since I want to make this game, apart from being a platform (PC) game, I'd also like to make it for Android. So, my question is, how can I make the buttons that I will assign to the screen(left,right,up,down) to react when they will be touched, and then according to the button that i've touched on the screen, the snake to move? I hope that you'll answer back, as this is important for me =) Thanks again!
     
  28. SamSony

    SamSony

    Joined:
    Jul 6, 2014
    Posts:
    2
  29. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Hi pecko95, sure its not all that difficult to add buttons for touch, and as long as your user interface does not get to complex with lots of buttons and labels, we can use Unity's OnGUI to do this. I'll post the fix here.

    You'll need to open up Snake.cs in monodevelop and add to the top of the script:
    Code (CSharp):
    1. private float moveNextDelay = 0.0f;
    I put mine on a line by itself, on Line 18 in the script.

    Next you'll need to add some additional OnGUI code in order to draw the buttons and create the mobile interaction to move the snake. We already have the OnGUI() method in Snake.cs, it is responsible for drawing and displaying our snake on screen, we just need to add some code to it, to handle buttons for touching.

    So in Snake.cs script, find the OnGUI() method, and under:

    Code (CSharp):
    1.  
    2. for (int i = 0; i < snakeLength; i++)
    3. {
    4.     GUI.DrawTexture(snakePos[i], snakeIcon[i]);
    5. }
    6.  
    add this code it:

    Code (CSharp):
    1.  
    2. // our first button - Moves the snake "up"
    3. if (GUI.RepeatButton(new Rect(30, Screen.height-70, 120, 60), "Move Up") && Time.time > moveNextDelay)
    4. {
    5.     StartCoroutine(GUIMoveSnake(Direction.UP));
    6. }
    7.      
    8. // our second button - Moves the snake "right"
    9. if (GUI.RepeatButton(new Rect(200, Screen.height-70, 120, 60), "Move Right") && Time.time > moveNextDelay)
    10. {
    11.     StartCoroutine(GUIMoveSnake(Direction.RIGHT));
    12. }
    13.      
    14. // our third button - Moves the snake "left"
    15. if (GUI.RepeatButton(new Rect(Screen.width - 320, Screen.height-70, 120, 60), "Move Left") && Time.time > moveNextDelay)
    16. {
    17.     StartCoroutine(GUIMoveSnake(Direction.LEFT));
    18. }
    19.      
    20. // our fourth button - Moves the snake "down"
    21. if (GUI.RepeatButton(new Rect(Screen.width - 150, Screen.height-70, 120, 60), "Move Down") && Time.time > moveNextDelay)
    22. {
    23.     StartCoroutine(GUIMoveSnake(Direction.DOWN));
    24. }
    25.  
    if you get errors, no worries, here is the entire OnGUI method, you can simply copy/paste over yours and it should run fine.

    Code (CSharp):
    1.  
    2. // ---------------------------------------------------------------------------------------------------
    3. // OnGUI()
    4. // ---------------------------------------------------------------------------------------------------
    5. // Unity method, called every frame automatically. Used for displaying GUI elements
    6. // ---------------------------------------------------------------------------------------------------
    7. void OnGUI()
    8. {
    9.     for (int i = 0; i < snakeLength; i++)
    10.     {
    11.         GUI.DrawTexture(snakePos[i], snakeIcon[i]);
    12.     }
    13.  
    14.     // our first button - Moves the snake "up"
    15.     if (GUI.RepeatButton(new Rect(30, Screen.height-70, 120, 60), "Move Up") && Time.time > moveNextDelay)
    16.     {
    17.         StartCoroutine(GUIMoveSnake(Direction.UP));
    18.     }
    19.      
    20.     // our second button - Moves the snake "right"
    21.     if (GUI.RepeatButton(new Rect(200, Screen.height-70, 120, 60), "Move Right") && Time.time > moveNextDelay)
    22.     {
    23.         StartCoroutine(GUIMoveSnake(Direction.RIGHT));
    24.     }
    25.      
    26.     // our third button - Moves the snake "left"
    27.     if (GUI.RepeatButton(new Rect(Screen.width - 320, Screen.height-70, 120, 60), "Move Left") && Time.time > moveNextDelay)
    28.     {
    29.         StartCoroutine(GUIMoveSnake(Direction.LEFT));
    30.     }
    31.      
    32.     // our fourth button - Moves the snake "down"
    33.     if (GUI.RepeatButton(new Rect(Screen.width - 150, Screen.height-70, 120, 60), "Move Down") && Time.time > moveNextDelay)
    34.     {
    35.         StartCoroutine(GUIMoveSnake(Direction.DOWN));
    36.     }
    37. }
    38.  
    39. // coroutine handler to feed the direction and movement ot MoveSnake method
    40. IEnumerator GUIMoveSnake(Direction mDirection)
    41. {
    42.     moveNextDelay = Time.time + moveDelay;
    43.  
    44.     yield return StartCoroutine(MoveSnake(mDirection));
    45. }
    46.  
    You can test this out by building to Android, and touch and hold one of the buttons, you will see the snake move accordingly.

    ---------------------------------------------------------------------------------------------------------------------------------------------

    Now I'll explain the code some.

    We started with:
    Code (CSharp):
    1. private float moveNextDelay = 0.0f;
    We create a variable to hold an amount of time in order to create the delay between the snakes movement, and in our GUIMoveSnake method, we update it to Time.time (the current elapsed time in the game) + moveDelay (our games actual delay amount). So what happens, when we play the game, let's say for example we press the "Up" button on the GUI, GUIMoveSnake will get called, and the very next line, we update moveNextDelay to equal Time.time + moveDelay. So what this does is put our variable moveNextDelay ahead of Time.time in the amount of current time of the game plus moveDelay, so when we press the same "Up" button again, it will check:
    Code (CSharp):
    1. && Time.time > moveNextDelay
    and see that Time.time is not greater that moveNextDelay, so it will delay until it has reached a number past it, and then execute it again.

    Thats a really great way to create a pause between something, for examples things like firing a weapon or throwing a projectile, you can do the same thing for those types of games.

    So backing up a little, we need to draw the buttons, and we need a specific type of button. That's whats happening with:
    Code (CSharp):
    1. GUI.RepeatButton(new Rect(Screen.width - 320, Screen.height-70, 120, 60), "Move Left")
    GUI.RepeatButton takes parameters, just like many of the methods we created in our snake game, such as TextureHelper, we pass parameters (variables). So in our RepeatButton we pass a new Rect, this sets up the "x" & "y" position of the button, and the width and height of the button, we can also add a string to display on top of the button, this is handy for describing to the user, what the button is for.

    We wrap the GUI.RepeatButton in an "if" statement, because we want to run some logic, if that button is pressed. Also, last thing to note on GUI.RepeatButton, it returns true, as long as it is held down, this is different than the regular GUI.Button (it only returns true 1 time when its pressed). So this is exactly what we need.

    So we have 4 buttons, with different positions on screen, and they all call a Coroutine, GUIMoveSnake, which we pass the direction we want the snake to go in. This is how parameters helps us, it makes more sense to call 1 method passing the direction which is decided by which button we push, rather than make 4 methods driving the snake in each of 4 directions.

    So the rest of GUIMoveSnake, simply yields the movement of the snake, and once that is done in MoveSnake, we have executed all the logic, and we wait for the next button press to repeat the process over again.

    ---------------------------------------------------------------------------------------------------------------------------------------------

    Well, that was a bit long winded, but I hope that helps you out. Good luck in all your game projects!

    -Raiden
     
  30. pecko95

    pecko95

    Joined:
    Jun 29, 2014
    Posts:
    2
    Thanks A LOT! This really helped me with what I've wanted to achieve and I hope it didn't took too much of your free time to write this code + the EXPLANATION which is a really great thing to actually explain to me what the code means :D Thanks again, this was really helpful =)
     
  31. Ac6057

    Ac6057

    Joined:
    Mar 22, 2014
    Posts:
    5
    Hi, Soon Project file will be posted for you Check our android game on google play store plz, dawnload n share and if you like this game then give rate it.. Take a look at "Snake Run" - https://play.google.com/store/apps/details?id=com.Puppetflurry.SnakeRunn&hl=en Snake Run - Android Apps on Google Play play.google.com Snake Run - Android Apps on Google Play play.google.com

    Snake Run - Android Apps on Google Play
    play.google.com
     
  32. The_Thinker

    The_Thinker

    Joined:
    Dec 6, 2013
    Posts:
    38
    ....I thought this was a easy beginner game to make...
     
  33. DuJiaxing

    DuJiaxing

    Joined:
    Jun 17, 2015
    Posts:
    1
    I can't see , i want to learn more, This is my mail . Can you send me? d479829212@163.com
     
  34. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    @DuJiaxing, oops, so sry bout that. I have updated the links at the very top in my original post.

    To all, also I have rebuilt this project in Unity 5.

    Enjoy!

    -Raiden
     
  35. risheebatra

    risheebatra

    Joined:
    Jul 2, 2015
    Posts:
    1
    Dear Raiden,

    I've been following your tutorial but for some reason, when I press play in the Unity program, the Score and Lives do not display. (I've copied the code directly from the tutorial). I thought the problem might be that the colors overlap, or maybe the text is too small, but I've played around with them and don't think those are the problems. I did initialize them in the GameManager, and the hierarchy does display "Score" and "Lives," so I'm having trouble figuring out what I should do now.

    Thank you very much for your time!
     
  36. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    @risheebatra

    Hi, Go back in your Score.cs and Lives.cs scripts and make sure you have the Initialize code setup properly. This is where you will define the GUIText object and initialize it's text and pixelOffset fields.

    Here is the Initialize method for the Score:

    Code (CSharp):
    1. // ---------------------------------------------------------------------------------------------------
    2.     // Initialize()
    3.     // ---------------------------------------------------------------------------------------------------
    4.     // Initializes Score
    5.     // ---------------------------------------------------------------------------------------------------
    6.     public void Initialize()
    7.     {
    8.         print("Score initialized");
    9.        
    10.         // make sure our localScale is correct for a GUItexture
    11.         transform.position = Vector3.zero;
    12.         transform.rotation = Quaternion.identity;
    13.         transform.localScale = Vector3.one;
    14.        
    15.         // add our GUIText component
    16.         gameScoreText = gameObject.AddComponent<GUIText>();
    17.        
    18.         // we define the initial text of the GUIText.text
    19.         gameScoreText.text = "Score: ";
    20.        
    21.         // we intialize the GUIText properties
    22.         gameScoreText.pixelOffset = new Vector2(10,758);
    23.     }
    and here is the Initialize method for the Lives:

    Code (CSharp):
    1. // ---------------------------------------------------------------------------------------------------
    2.     // Initialize()
    3.     // ---------------------------------------------------------------------------------------------------
    4.     // Initializes Lives
    5.     // ---------------------------------------------------------------------------------------------------
    6.     public void Initialize()
    7.     {
    8.         print("Lives initialized");
    9.        
    10.         // make sure our localScale is correct for a GUItexture
    11.         transform.position = Vector3.zero;
    12.         transform.rotation = Quaternion.identity;
    13.         transform.localScale = Vector3.one;
    14.        
    15.         // add our GUIText component
    16.         gameLivesText = gameObject.AddComponent<GUIText>();
    17.        
    18.         // we define the initial text of the GUIText.text
    19.         gameLivesText.text = "Lives: ";
    20.        
    21.         // we intialize the GUIText properties
    22.         gameLivesText.pixelOffset = new Vector2(944,758);
    23.     }
    Notice in both below the comment: "add our GUIText component" we are add ing a GUIText component and returning it to the declared instance at the top of the script. Then we are setting the text field of the GUIText component to "Score:" and "Lives:" and finally we define a pixelOffset so that it will position on screen correctly.

    As long as you have the code setup properly in the Initialize methods for both Score.cs and Lives.cs, you should be able to see them on screen.

    Also note, this game is setup in a landscape view of 1024x768. Lastly, here is the example image of what you see after you call:

    Code (CSharp):
    1. // build our Score object
    2. Score.Instance.Initialize();
    3.        
    4. // build our Lives object
    5. Lives.Instance.Initialize();
    in the GameManager.cs Start() method.

    https://dl.dropboxusercontent.com/u/96068012/Tutorials/Uni2DSnake/images/GameScore-Lives.tiff

    Let me if you have anymore problems.

    -Raiden
     
  37. 8Observer8

    8Observer8

    Joined:
    Apr 29, 2015
    Posts:
    99
  38. Artemis_Toh

    Artemis_Toh

    Joined:
    Nov 2, 2015
    Posts:
    2
    all the links are down. could you fix it? getting a 404 error in all the links to dropbox.
     
  39. raiden

    raiden

    Joined:
    Feb 8, 2009
    Posts:
    333
    Sorry about that, links are updated now.

    -Raiden
     
  40. NinjaBoyLao

    NinjaBoyLao

    Joined:
    May 6, 2017
    Posts:
    1
    Fixing to necro the living S*** out of this post..

    Is there a way I can find a playable version to try and convert the legacy UI elements to the new UI system? Any help is appreciated
     
  41. oshawottking

    oshawottking

    Joined:
    Jul 6, 2018
    Posts:
    2
    I am very new to Unity. Just started this project. Looks great so far, however, Unity doesn't use GUITexture anymore. In the screenborder script, what words do I replace GUITexture with, or is there another way to fix this. If that part of the script isn't necessary, what will happen if that script isn't used.
    Thanks.