Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Random Destination..understanding

Discussion in 'Scripting' started by Quincey, Feb 28, 2020.

  1. Quincey

    Quincey

    Joined:
    Aug 14, 2019
    Posts:
    46
    Hello again,

    I'm posting yet another forum to ask for some knowledge and understanding since I'm trying to learn how to program and write code on my own. I hope this post doesn't make me look completely incompetent, but if so it's cool I'm just trying to learn and get better at knowing what's really going on in scripts. I've discovered a pretty cool tutorial that displays a game object moving to different random positions. I've included the code, but the main reason I'm posting this is I'd like some clarity on a few lines of code please. The lines of code are #23, #25, and mainly #29.

    1) Line 23 is the void OnTriggerEnter(Collider other) ---> its this speaking for the collider on the object that's suppose to randomly move around the scene? Or any other game object that enters the collider?
    2) Line 25 is if (other.gameObject.CompareTag("Spider)) ---> what and why does it start off with "other.gameObject" what exactly does the "other." mean?
    3) Line 29 is this.gameObject.transform.position = new Vector3(xPos, 1, zPos) ---> I have no idea what this line means and why words like "this." and why "gameObject" is used instead of "GameObject"



    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class RandomDest : MonoBehaviour
    6. {
    7.     public int xPosition;
    8.     public int zPosition;
    9.  
    10.  
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.        
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.        
    21.     }
    22.  
    23.     void OnTriggerEnter(Collider other)
    24.     {
    25.         if (other.gameObject.CompareTag("Spider"))
    26.         {
    27.             xPosition = Random.Range(-23, 20);
    28.             zPosition = Random.Range(24, -23);
    29.             this.gameObject.transform.position = new Vector3(xPosition, 1, zPosition);
    30.         }
    31.     }
    32. }
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    Hi,
    1. The RandomDest script will be attached to some gameobject which has a collider. When this collider (which is used as trigger) gets entered, the OnTriggerEnter method will be executed. So when something walks 'into' RandomDest, then this method gets called.
    2. It says other.gameObject, because it cares about the other GameObject of the collision. After all, we always know our own. The 'Collider other' parameter of the OnTriggerEnter function is filled with the gameobject triggering the collision. So the thing that walks into RandomDest, would be 'other'.
    3. First of all, 'GameObject' (with a capital G) is a type, while 'gameObject' refers to the shortcut reference to your own gameObject. Every Monobehaviour script must be attached to a GameObject, so with gameObject you get the reference to your own object. The 'this' refers to 'this' script. It's not needed there. Imagine your script had an attribute called 'other'. If you wrote 'other' inside the OnTriggerEnter method, it would not be clear whether you meant the 'other' (parameter) or the 'other (your own class attribute). Default, a programm always takes the one from the closer scope, so in this case the 'other' (parameter) would be taken. But what if you wanted to reference your own class variable instead? Then you would need to write this.other, which tells the program that you mean the class variable. So it's mostly there so you can lazily reuse variable names for methods and in the class. There may be other uses i forgot since i literally last used it years ago. Last but not least, the line as a whole makes it so that the object gets moved to a different (random) location on the x and z axis. The values for where you are moved to are calculated at lines 27+28. So basically, what this does is when you touch this object, it teleports away. That's basically it.
    That was a lot of questions for a rather short script. Did you look into some C# and Unity tutorials? I can recommend the youtube series on game development by Sebastian Lague, which explains most relevant topics for programming and Unity in a well structured and easy to understand way:
    A couple things may not be explained there, but it would be a good start to get a knowledge foundation and some experience with the example tasks he gives you.
     
    Kurt-Dekker and Quincey like this.
  3. Quincey

    Quincey

    Joined:
    Aug 14, 2019
    Posts:
    46
    Yoreki,

    Hey thanks a million for the thorough breakdown as to what I asked I hope it wasn't too overwhelming, but I'm really trying to understand C# programming. For that matter just programming in general I find it very intriguing, but super hard and confusing whenever I get tons of compiler errors and have no idea what's causing them. I'll make sure I check out the guide you sent me and start there and take a ton of notes so I'll be able to reflect on what's happening until I fully master the basics. You sir are a livesaver and thanks for taking time to help me understand what's going on with this script.
     
    Kurt-Dekker likes this.
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,970
    Fully 100% of what @Yoreki wrote above is Really Good Stuff(tm), and I personally admire and applaud your genuine efforts to understand this stuff. And you WILL understand it, especially when you go around asking great questions like this. Stick with it.

    I'm going to add a little bit more to the Good Stuff that Yoreki posted above:

    - everything in a Unity scene is a GameObject, and it may have one or more GameObjects hierarchically above or below it. It's like a filesystem tree that can be changed anytime.
    - GameObjects have Components on them (or "plugged into" them if you prefer), anywhere from one Component to many (they always have either a Transform or RectTransform)
    - Components may be things like Monobehaviours, or other in-engine things like Camera, Light, etc. But they are all Components and can only live on GameObjects.
    - things like Materials and Textures are broadly called Assets, and usually come off the disk, but not always. You can create your own Materials and Textures at runtime. Assets generally may be "plugged into" public fields on Components to change the behavior of Components.

    Functions like OnTriggerEnter() and Update() and all are only special by agreement with Unity: Unity will call those functions when certain conditions are met, AND your script derives from Monobehaviour, AND your script is on an active GameObject, etc. Now you can always call those functions yourself too; they're just functions after all.

    Here is also some cool graphic layout of how things are processed in Unity over the lifecycle of a GameObject and all of its Components:

    https://docs.unity3d.com/Manual/ExecutionOrder.html

    Every one of those bubbles is a special function (or family of functions) that Unity may call in your script, if it exists.
     
    Quincey likes this.
  5. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,890
    As for the 'gameObject' part, you can right-click on MonoBehaviour and select Go To Definition to see what it provides. It inherits from Behaviour, which inherits from Component, which is where the 'gameObject' property is. Keep using 'Go To Definition' on the types to find it.
     
  6. Quincey

    Quincey

    Joined:
    Aug 14, 2019
    Posts:
    46

    That's the best motivation I've heard all day today I really appreciate the kind words. I was very reluctant to post that thread, because I didn't want to look bad or embarrass myself, but I said oh well the worst that can happen is people comment with hateful words which won't kill me.
    This programming is completely out of my comfort zone it's the whole logic behind writing these precise lines of code. It's sooooo hard and frustrating and I'm praying to God that He will grant me the endurance to see all this struggling turn into grace and smooth sailings.
    I've been looking at countless YouTube videos trying to learn and figure out how to do things. Some of the material is outdated but I still watch to educate myself. I will say this though...NOT having any help or nobody to Skype to ask basic questions when I hit a brick wall for days is very depressing :(
     
  7. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,970
    And I applaud you even louder for that.

    ALWAYS feel free to post here! As long as your question is on-point, we would ALL love to chip in to your lifelong brain expansion program. There are a ton of great people here, each with their own forte.
     
  8. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,890
    There is an Official Unity Discord to chat with people.
     
  9. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    I couldnt agree with Kurt more. Always ask questions if you are genuinely stuck. As long as it's a honest question, people will be happy to help you. And eventually you may become one of the people helping others in return :)

    And i only put in the part about 'a honest question' since now and then there are literally people expecting others to fix their projects or basically work for them for free, which obviously people arent exactly fond of. Then there are those who dont describe their problems, dont use code tags, .. the list goes on. Some people seem to not really care about getting their problem solved when opening a thread. But your post really is a good example for how you should ask questions.

    Keep in mind that, while watching videos is always a great start, programming really is 'learning by doing'. So always follow up something you read or saw with a little bit a practice, where you use it yourself. Especially at the beginning, it can be easy to read through something, not quite understand where and why it is useful, and then forget half of it since your brain doesnt really know where to put it (at least for me). So making use of this new 'theoretical knowledge' makes it harder to forget, and already adds one possible use-case to your mental model of how to approach problems.

    And i can only again recommend the already linked series, as it's very well structured (only telling you what you need to know, then what you can do with it, expanding your knowledge as it becomes required for new tasks and so on), and also offers examples and tasks so you can test your knowledge and see what can be done with it. This way you should get a good understanding of how things are connected and what is used for what problem / situation!
     
    Quincey likes this.
  10. Quincey

    Quincey

    Joined:
    Aug 14, 2019
    Posts:
    46
    Yoreki,

    Something you said stood out to me and I wanted to ask you a personal question. With programming game, website, etc. does it ever get easier per say? Can programming ever be truly mastered? The answer I'm expecting to hear is "no it's never really mastered, but you can have a strong grasp on programming" or something along those lines.
    When I think about the people that work at these AAA gaming studios I wonder if they ever encounter things that gives them a very hard time. "The learning by doing" has a very thin double edge line with me because I'm literally trying to code at a minimal of 2-3 hrs a day. The only really issue I'm having is understanding why I'm typing the code I see from videos. It's the practical knowledge and the "know-how" that makes this super frustrating and confusing because I can't ask a question and get a reply immediately you know.
     
  11. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,386
    If you're still copying code from videos, then I'd say you haven't quite gotten to the "doing" part of "learn by doing". I'd say "doing" is more like imagining a problem and trying to come-up with your own solution with what you've learned already. Use what you've learned to create something new that's not in the tutorial.

    If you have a big block of code that you've copied from a tutorial, and you really want to know how it works, try changing certain things about it. Decide- "I have an enemy script, but how do I make it faster or slower?", "Instead attacking of the player, how do I make it attack another enemy?" Things like that. Try to create your own variations. If you cant figure out what a function does or what a property is, look it up in the manual. Simply copying what you're seeing is not enough, for the exact reason that you already mentioned, so actually go in and play with it. Set-up new problems for yourself to solve.
     
  12. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,970
    Yes it does, but a good engineer (indeed any good creator) simply moves the baseline up. Once you can easily throw together simple projects in Unity, you'll find yourself working to make more-complex and more-involved projects.

    The big picture to keep in mind is that it actually is engineering. Every decision you make is a tradeoff, and the more decisions you make, the better you will get at predicting and considering the tradeoffs of effort vs reward.

    One of the biggest problems I see on this forum is people coming in and saying "I don't know much about programming but I want to make my own MMO." Making an MMO is an extremely advanced topic.

    The closest analogy would be, "Hey, I haven't done a lot of ironwork but I wanna try and build the Eiffel Tower. Where do I start?"

    Bite off small chunks and always be open to backing away from a project temporarily and learning more from other projects, then you'll find you can go back to things you couldn't do before, and now suddenly you can do them.

    Also, Yoreki wrote "learning by doing" and I'm gonna stand behind that even more. You gotta DO it in order to master it, just like almost anything complicated in life.
     
  13. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    As others said, yes it can be 'mastered'. However, it is worth mentioning that 'programming' is not one topic, but several different fields that just use the same tools (one or multiple programming languages, as well as theoretical and algorithmic knowledge, data structures, ...). A backend developer for a small company developing apps may not necessarily know a lot about GUIs.. or networking.. or procedural generation.. or gamedevelopment or.. the list goes on. He probably specialized in one part and is very efficient at solving problems in this category. And that's basically what programming is. Problem solving. On that regard, always keep in mind 'Divide and Conquer'. If you have a larger, complex problem you need to solve, divide it into smaller ones until they become easy to solve, then 'conquer' these smaller problems. Solving all small problems, solves the large problem.

    Anyways, after you successfully understood something you can add that topic to your toolbelt. And when you already know how to use a lot of different tools, learning to use new ones becomes faster. The same goes for programming languages by the way, and they may even be a better example. Right now you are still in the phase where you (probably) struggle with syntax or semantic a bit, but eventually you will fully understand how C# works. At that point, learning a new language (especially another object oriented one, like Java which is extremely similar) will be very easy, to the point where you can mostly do it in a couple days. After all, all object oriented programming languages use objects, inheritance, and so on. All programming languages in general use some form of loops, conditions, variable assignments and so on. These things stay the same, the only thing that changes is syntax and semantics of the language. It gets a bit more complicated for other categories of programming languages (like a functional one: Haskell), but even there certain principles stay the same.
    Coming back to a bit more Unity-related examples: if you build a character controller, and are now facing the task of building a controllable cannon / tower, then you will probably know how to do it. The problems seem very different at first, but in the end both are mostly about rotating an object using mouse or keyboard inputs, and moving an object in some direction (possibly using physics). Some other parts, like how to 'spawn in' the cannon ball, can then easily be looked up, since you already know how the general approach to this problem would look like.
    I hope this example makes sense.
     
    Quincey likes this.
  14. Quincey

    Quincey

    Joined:
    Aug 14, 2019
    Posts:
    46

    What a dope summary man I had NOOOOO idea programming was that complex and covered things I wasn't even aware of or even heard like procedural generation and all the other stuff you mentioned. This is going to be one long voyage to get super comfortable with Unity and C#. After reading everyone's honest feedback and candor I think it's best if I set aside my project and only focus on the basics and I mean B.A.S.I.C.S.
    I long for the day when I can go onto the Unity forum site and give accurate responses and help others. I'm going to Walgreens and buying a composition notebook and I'm going to take some serious notes and study basic code scripts so I can understand and once that happens I'll implement the "doing" phase where I take small code and make variations to get different desired outcomes. Once I can do this I think I'll be happy and my confidence will improve. Right now I'm drowning and this is a bad predicament to be in. I want to thank you and all the others that took time to reply and share some valuable insight.

    V/r,
    Quincey
     
    Yoreki likes this.
  15. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    Dont feel threatened by the huge amount of things there are to learn. Set yourself small goals and get there step by step. I always find it easier to learn new stuff, when you have an actual goal in mind. So after learning the basics, set yourself a small, comparably easy game as a goal that really interrests you. Like, for example, a blocky 3d version of snake, or pong, or a platformer. Something that interrests you, either on a technical level or just because you like the game. Then figure out how to implement it. Make sure to find incremental tasks that actually interrest you, so you keep being interrested in learning new stuff. Then, step by step, experience and knowledge builds on its own.

    Also, while there are a lot of different fields (some of which i mentioned), they all rely on mostly the same tools and the same basics after all. While someone working with procedural generation will have experience with certain involved algorithms or things like perlin noise, he will still build on the same semantic and algorithmic basics as, say, a networking developer (who instead has more experience with sockets, client-server systems and so on).
    So start with the basics, set yourself goals that actually interrest you, and if you keep at it, you will eventually arrive at a point where you can 'easily' expand your knowledge to implement some missing feature into your game or learn about new fields.