Basic Unity Skills



    Good day, dear Khabarovsk!

    Every developer wants to create his own game faster, but how to do it? This article discusses the basic skills to reduce development time in a Unity environment.

    Skill # 1 - Work with the project structure


    To maintain order in the project, you need to understand its structure. It can be represented as follows:

    1. Models - stores all models used in the project
    2. Prefabs - stores all model templates
    3. Textures - stores all textures
    4. Materials - stores all materials
    5. Scripts - stores all scripts
    6. Sounds - stores all sounds
    7. Animations - stores all animations

    If you have complex objects, for example, a character, a separate folder is created for him, where the above structure is repeated.


    Character folder structure

    Another approach would be to create the folders described above, and to place parts of the object in each folder, that is, for the character’s animation, the following structure will be.


    Animation folder structure

    Skill # 2 - Working with a hierarchy of objects in the scene


    To simplify working with sets of identical objects, they can be combined into groups where an empty object acts as a parent.

    This will help to easily turn off the light throughout the location or indoors. Find out the location of all objects.

    Each element is called relative to what it is, at the end a postfix of the parent object is added. For example, a gold bar in a cave will be called “goldBar_cv1”, where cv1 means cave1, and a tree in the forest “tree_frt1”, where frt1 means forest1. For postfix, the first letter of the word, the first letter of the second syllable and the last letter of the word are taken.


    An example of a hierarchy of objects on a scene

    Skill # 3 - Working with visual presentation


    Unity has 3 main light sources:

    1. Directional Light - an analogue of the Sun
    2. Point Light - analogue of a bulb
    3. Spotlight - analogue of a flashlight

    If there is light, then there must be a source of light. For example, in a cave it cannot be light if the character does not have a torch (for a torch, spot light is suitable).

    Use PostProcessing to apply effects.

    image
    The scene without post-processing

    image
    The scene with post-processing

    UPD from thenonsense :

    In addition to visually presented light sources, there are also global light settings: tab on top of Window , Lighting item, Settings sub-item. There you can, for example, tighten up the lighting of the environment, install a skybox, add fog. Actually, it is here that you need to look if you asked yourself the question “deleted all light sources, but it’s all the same light on the stage as in the daytime”. By the way, you can get into these settings already while the game is running in the editor so that you can immediately see the changes on the fly. However, after closing the game mode, the settings will return to the state they were before the start of the game test. So you have to climb into this window again and adjust the values. A useful detail - if, for example, you wanted to change the color of the lighting (Ambient color in the Environment Lighting group), then on the panel with the palette pay attention to the Hexadecimal item - the number of the current color is indicated in the window, you can copy it and paste it into the same field later , when game mode is off. The same trick is useful for adjusting the color of the fog and so on.

    In the same way, while running in game mode, you can change some parameters of objects through the editor - the values ​​of variable scripts moved to the visibility zone, enable / disable rendering of the object mesh, and so on. The main thing is not to get carried away so as not to break something. After the game mode is turned off, the changed values ​​will be restored. This does not apply to some individual elements, for example, if you edited the terrain texture in the included game mode, then its changes will be saved.


    Skill # 4 - Work with the camera


    Need to find an object on stage? Click 2 times on the name of the object in the hierarchy.

    Want to fly across the stage from 1 person? Hold down RMB and move with the WASD keys, Shift acceleration.

    Want to see the scene from different angles? Take advantage of Gizmos (Gizmos).


    Gizmo Location

    Skill # 5 - Work with objects


    Want to add a character to the scene? Add the RigidBody and CapsuleCollaider components. RigidBody tells the engine that solid state physics should be applied to this object.

    Want to check the collision of a character with an object? Add the MeshCollaider component to the object and in the character script in the OnCollisionEnter function check the tag of the object that the character encountered.

    An example of the implementation of checking the collision of a character with an object
        private void OnCollisionEnter(Collision collision)
        {
            switch (collision.gameObject.tag)
            {
                case "Moneys":
                    Destroy(collision.gameObject);
                    // Do something
                    break;
                case "TrapSpikes":
                    hitPoints -= 5.5;
                    break;
            }
        }
    



    UPD from thenonsense :
    It is not always necessary for a character to use a rigidbody; management methods may be different. But a collider for a character will be required almost always, unless you are going to calculate collisions in a more tricky way. Unity also has several specific controllers / colliders - it is better to read the documentation to understand them in more detail. But it's better to start with simple examples on YouTube.

    As for those objects that the character encounters. Mesh Collider should usually be hung on those objects whose complex shape is one way or another important for you to take into account the collision. If it’s just a button, it’s better to get by with simpler colliders like Box Collider. In addition, you may have to make a simpler, invisible collision grid for particularly complex 3D objects and hang the Mesh Collider on it, and not on the visible object itself.

    About button colliders, it is worth remembering that in their component of the collider you need to check the Is Trigger box so that the script can handle the click event. A rigidbody component must be assigned to any barrels, boxes, and other objects that must simply beautifully physically react to collisions and fall under the influence of gravity.


    Skill # 6 - Import Models


    Consider the procedure using the example of importing a model from Blender. It is assumed that you have already made a scan, applied a texture or selected materials.

    1. Position the model in zero coordinates (center relative to the axes)
    2. Set Scale to One
    3. Remove unnecessary objects (camera, light source)
    4. Save the model in .fbx format
    5. Transfer file to Unity
    6. Pull into folders - Model to Models, Material to Materials, etc.
    7. Create model prefab
    8. Work further with prefabs


    UPD from thenonsense :

    Blender


    Please note that if blender materials are assigned to the model, then they will be transferred in a simplified form and will clutter up the list of materials.
    You don’t have to do complex development and texturing in Blender at all - an easier way is to go through all the elements of the model and select the Data item in the window on the right . This is an icon in the form of a triangle looking down with three dots between the Modifiers (wrench) and Material (pink ball) items. In it, click on + next to the UV Maps graph.- there appears an automatic sweep with a chess ball icon. This needs to be done for each element of the model and only then export. Then already in Unity it will be possible to apply material with a tile texture to this part, and if this is not done, then the material will only paint the part in a solid color. (If you later deformed the model element, then discard the sweep and reassign it so that it is not stretched).

    If your model consists of different elements, then already in Unity you can move individual elements of your model or disable them. This can be useful in various situations.

    How to texturize a model in a simple way.


    First you need some 512 to 512 tile textures. Add it in the same way as the 3D model via Import New Asset (remember that a suitable folder should be selected). At the same time, on the right, in the inspector, at the added texture in the Default window, set the Max Size parameter to 512. And then click Apply . Now the texture is ready to add it to the material or, say, it can now be painted terrane. Pay attention to the very first point - Texture Type, now it is in default mode, but when you need to load a normal map, an image for a translucent sprite, and so on, you will need to set the appropriate setting there.
    Next we need to create the material. We go again to the menu above -Assets , the drop-down list Create , Material (again, do not forget that the material will be created in the folder that is currently selected). You drive in the name of the material and in the inspector open the Albedo item (until we stop at other parameters, but the principle is similar), where you search and assign your previously loaded texture. Nearby there is a color window that can additionally tint your texture, as well as Metalic and Smoothness sliders to add glare or dullness. The Tiling size parameter is also useful, it is a few lines below.
    After the material is created, you can grab it and throw it directly onto the model or its elements, just don’t miss it, otherwise paint not what you need.

    Do not forget that the same texture can be used in different materials. For example, with impurities of different colors and / or different tile sizes.

    Prefabs.


    Usually the prefab is done something like this - they dragged the object onto the scene, then hooked its name in the hierarchy window and dragged it into the folder. Then there will appear a prefab based on the object, in the inspector the prefab will have a blue cube icon and it will be signed below the tag, Prefab.
    However, you don’t need to immediately do everything with prefabs. You can throw the object on the scene, then clone it with copy-paste and test it like that. If everything suits you, then transfer the object to the prefab, if not, for example, a bug has appeared in the model, then delete its copies from the scene, the model itself from the folder, fix it in the 3D package and import again.

    You can also shove some new child elements inside the prefab on stage. However, they will not become a full part of it, that is, they will not affect other copies of this prefab until you click the Apply button in the inspector on the line with the name Prefab.


    Skill # 7 - Implementing Logic


    Avoid costly operations. An example is determining the distance to an object.

    Costly Operation Example
    using UnityEngine;
    using System.Collections;
    public class ExampleClass : MonoBehaviour
    {
        public Transform other;
        void Example()
        {
            if (other)
            {
    // Считаем квадратный корень из суммы квадратов
    // В данном случае квадратный корень является дорогостоящей операцией
                float dist = Vector3.Distance(other.position, transform.position); 
                print("Distance to other: " + dist);
            }
        }
    }
    


    Faster Implementation Example
    using UnityEngine;
    using System.Collections;
    public class ExampleClass : MonoBehaviour
    {
        public Transform other;
        public float closeDistance = 5.0f;
        void Update()
        {
            if (other)
            {
                Vector3 offset = other.position - transform.position;
     // Считаем только сумму квадратов
                float sqrLen = offset.sqrMagnitude;
                // Возводим в квадрат расстояние, с которым мы сравниваем
                if (sqrLen < closeDistance * closeDistance)
                {
                    print("The other transform is close to me!");
                }
            }
        }
    }
    


    Read more about expensive operations here .

    Conclusion


    The above skills will significantly reduce time both during development and during project support.

    If you think that some topics are revealed superficially, please write in the comments about them in more detail.

    Also popular now: