Code Saying http://codesaying.com Let The Code Say Mon, 06 Jul 2020 13:30:09 +0000 en-US hourly 1 https://wordpress.org/?v=5.5 Playing Video in Unity http://codesaying.com/playing-video-in-unity/?utm_source=rss&utm_medium=rss&utm_campaign=playing-video-in-unity http://codesaying.com/playing-video-in-unity/#respond Mon, 06 Jul 2020 13:30:08 +0000 http://codesaying.com/?p=712 Ever stuck on how to render a video on a TV screen in a game? Lets us learn the concept of playing a video in Unity. You can import many different formats of video file into Unity. Unity stores such imported video files as VideoClip assets. A Video Clip is an imported video file, which the Video Player…

The post Playing Video in Unity appeared first on Code Saying.

]]>
Ever stuck on how to render a video on a TV screen in a game? Lets us learn the concept of playing a video in Unity.

You can import many different formats of video file into Unity. Unity stores such imported video files as VideoClip assets. A Video Clip is an imported video file, which the Video Player component uses to play video content. The playing video also accompanies audio content, if it has any. Typical file extensions for video files include .mp4, .mov, .webm, and .wmv.

To check the video file compatibility in unity, click here.

The Video Player component

Video Player component is used to attach video files to GameObjects, and play them on the GameObject’s Texture at run time.

By default, the Material Property of a Video Player component is set to MainTex, which means that when the Video Player component is attached to a GameObject that has a Renderer, it automatically assigns itself to the Texture on that Renderer (because this is the main Texture for the GameObject).

You can also set the following specific target for the video to play on, using the Render Mode property of Video Player:

  • A Camera plane
  • A Render Texture
  • A Material Texture parameter
  • Any Texture field in a component

Playing a video already in Assets

If you already have a video clip in your asset folder, you can simply set the Source property of Video Player component to Video Clip and drag and drop your video clip in the inspector. Alternatively, you can set the video clip in script using clip property.

    public VideoPlayer myVideoPlayer;
    public VideoClip myClip;
    myVideoPlayer.clip = myClip;

You can tick the property Play On Awake if you want to play the video the moment the Scene launches. Otherwise you can trigger the video playback with Play() command at another point during run time.

    myVideoPlayer.Play();

Playing Video from url in Unity

You might be having a video on server which you want to load on runtime. Here is how we can do it:

    private IEnumerator playVideoInThisURL(string _url)
    {
        myVideoPlayer.source = UnityEngine.Video.VideoSource.Url;
        myVideoPlayer.url = _url;
        myVideoPlayer.Prepare();

        while (myVideoPlayer.isPrepared == false){
           yield return null; 
        }
        myVideoPlayer.Play();
    }

Here, we have waited till the video player successfully prepared the content to be played.

Note, the url can also contain the path of the file.

Downloading and Saving Video from Url

The above line of code plays the video directly from the url. Alternatively, you can download the video file and then play the video from this path. The line of code below downloads the video clip and saves it at Application.persistentDataPath.

    private IEnumerator loadVideoFromThisURL(string _url)
    {
        UnityWebRequest _videoRequest = UnityWebRequest.Get(_url);
        yield return _videoRequest.SendWebRequest();

        if (_videoRequest.isDone == false || _videoRequest.error != null)
        {
            yield return null;
        }
        else
        {
            Debug.Log("Video Done - " + _videoRequest.isDone);
            byte[] _videoBytes = _videoRequest.downloadHandler.data;
            string _pathToFile = Path.Combine(Application.persistentDataPath, "video.mp4");
            File.WriteAllBytes(_pathToFile, _videoBytes);
            StartCoroutine(this.playVideoInThisURL(_pathToFile));
            yield return null;
        }
    }

Now we have learnt the art of playing video in Unity. Drop in your comments for any queries or feedback.

Happy Coding!

The post Playing Video in Unity appeared first on Code Saying.

]]>
http://codesaying.com/playing-video-in-unity/feed/ 0
Action Callback in Unity http://codesaying.com/action-callback-in-unity/?utm_source=rss&utm_medium=rss&utm_campaign=action-callback-in-unity http://codesaying.com/action-callback-in-unity/#respond Sat, 27 Jun 2020 21:18:25 +0000 http://codesaying.com/?p=690 Delegate is a famous way to implement Callbacks in C#. Action is one such generic delegate type. Action Callbacks can be very handy in Unity programming. Let us learn how to use Action Callback in Unity. What is an Action? Action is a generic delegate type defined in the System namespace. Action objects return no values.…

The post Action Callback in Unity appeared first on Code Saying.

]]>
Delegate is a famous way to implement Callbacks in C#. Action is one such generic delegate type. Action Callbacks can be very handy in Unity programming. Let us learn how to use Action Callback in Unity.

What is an Action?

Action is a generic delegate type defined in the System namespace. Action objects return no values. So we can say that Action type is similar to a void method. For example:

    void Start()
    {
        System.Action<string> printAction = new System.Action<string>(Display);
        printAction("Welcome to CodeSaying");
    }

    void Display(string message)
    {
        Debug.Log(message);
    }

Here, we have created an Action named printAction. Action<string> implies that the method assigned to this action should have one argument of type string. Consequently, a method named Display has been assigned to printAction. Note that Display() also has a string argument.

Another way of assigning method to an Action is by not using the new keyword

    System.Action<string> printAction = Display;
    printAction("Welcome to CodeSaying");

Using Lambda Expressions with Action in Unity

Instead of using a separate method to define the Action, we can use Lambda Expressions as follows:

    void Start
    {
        Action<int> printAction = i => Debug.Log(i);
        printAction(10);
    }

Using Action Callback in Unity

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of action.

Delegate provides a way to pass a method as argument to other method.

For instance, we have to hit an API to get a response. In such case, we can use Action Callback. Let us see how:

    void callApi()
    {
        StartCoroutine(FetchData(ApiAction));
    }
    
    string url = "https://postman-echo.com/get?foo1=bar1";
    IEnumerator FetchData(System.Action<string, bool> callback)
    {
        UnityWebRequest getData = UnityWebRequest.Get(url);
        yield return getData.SendWebRequest();
        if (getData.isDone == false || getData.error != null)
            callback(getData.error, false);
        else
            callback(getData.downloadHandler.text, true);
    }
    void ApiAction(string response, bool isSuccess)
    {
        if (isSuccess)
            Debug.Log(response);
    }

Here, the Coroutine FetchData takes an Action type as argument which further encapsulates a method with two input parameters : string and bool. When this coroutine is invoked from CallApi function, the data is fetched from server and, the callback ApiAction is fired with response(string) and isSuccess(bool) as arguments.

We could have even used a lambda expression here to simplify the code:

    void callApi(){
        StartCoroutine(FetchData((response, isSuccess) =>
        {
            if (isSuccess)
            {
                Debug.Log(response);
            }
        }));
    }

Using lambda expression, we have defined what action should be taken on receiving the callback inside the callApi function without the need to define ApiAction function.

Drop in your queries in the comment section.

Happy Coding!

The post Action Callback in Unity appeared first on Code Saying.

]]>
http://codesaying.com/action-callback-in-unity/feed/ 0
Create a math game for kids using Unity Scripting http://codesaying.com/create-a-math-game-for-kids-using-unity-scripting/?utm_source=rss&utm_medium=rss&utm_campaign=create-a-math-game-for-kids-using-unity-scripting http://codesaying.com/create-a-math-game-for-kids-using-unity-scripting/#respond Sat, 13 Jun 2020 16:15:49 +0000 http://codesaying.com/?p=681 Kids games are quite popular these days. And maths is a subject that a student normally fears. How about creating a math game for kids in Unity? It would be learning in a fun way. Let us see a simple way to create a math game for kids using Unity Scripting. The problem set used…

The post Create a math game for kids using Unity Scripting appeared first on Code Saying.

]]>
Kids games are quite popular these days. And maths is a subject that a student normally fears. How about creating a math game for kids in Unity? It would be learning in a fun way. Let us see a simple way to create a math game for kids using Unity Scripting.

The problem set used in the code includes addition, subtraction, multiplication and simple algebraic equations.

An interesting fact about this code is that there are no inbuilt set of questions. Questions are randomly generated. Thus everytime a kid opens the game, he would get a new question. No repetitions!

Random Addition and Subtraction Question Generator

Note that “questionText” string stores the question as a string.

    // Returns the answer in int to the question stored in string questionText
    string questionText;
    int sumOrMinusQuestion(){
        int operand1 = Mathf.FloorToInt(Random.value * 100);
        int operand2 = Mathf.FloorToInt(Random.value * 100);

        int isMinusOrPlus = Mathf.FloorToInt(Random.value * 2);
        //Is it a + or - question
        if (isMinusOrPlus == 0)
        {
            questionText = operand1 + "-" + operand2 + " = ? ";
            return (operand1 - operand2);
        }
        else
        {
            questionText = operand1 + "+" + operand2 + " = ? ";
            return (operand1 + operand2);
        }
    }

Random Multiplication Question Generator

    // Returns the answer in int to the question stored in string questionText
    int multiplyQuestion()
    {
        int operand1 = Mathf.FloorToInt(Random.value * 50);
        int operand2 = Random.Range(2, 10);
        questionText = operand1 + "*" + operand2 + " =? ";
        return (operand1 * operand2);
    }

Random Multi-Operand Question Generator

Example: (23+ 24)*2?

    int multiOperandQuestion()
    {
        int operand1 = Mathf.FloorToInt(Random.value * 30);
        int operand2 = Mathf.FloorToInt(Random.value * 20);
        int operand3 = Random.Range(1,10);
        int isMinusOrPlus = Mathf.FloorToInt(Random.value * 2);
        if(isMinusOrPlus == 0){
            questionText = "("+operand1 + "-" + operand2 + ")*"+operand3+ " = ?";
            return ((operand1 - operand2)*operand3);
        }else{
            questionText = "("+operand1 + "+" + operand2 + ")*" + operand3 + " = ?";
            return ((operand1 + operand2) * operand3);
        }

    }

Random Algebraic Equation

It would be a simple algebraic equation to find x. Example: 2x+2=4. Find x?

 int algebraicQuestion(){
        int answer = Mathf.FloorToInt(Random.value * 30);
        int operand1 = Random.Range(1,10);
        int operand2 = Mathf.FloorToInt(Random.value * 80);
        int isMinusOrPlus = Mathf.FloorToInt(Random.value * 2);
        if (isMinusOrPlus == 0)
        {
            questionText = operand1 + "*x - " + operand2 + " = " + ((operand1*answer) - operand2)+ ". Find x.";
        }
        else
        {
            questionText = operand1 + "*x + " + operand2 + " = " + ((operand1 * answer) + operand2)+ ". Find x.";

        }
        return answer;
    }

Determining Answer Choices

You can either ask the user to type in the correct answer or you can ask him to chose from a list of options. Here is a code snippet to show three different answers to the user to select from

 //this list contains the 3 different answer for the user.
List<int> answerChoices = new List<int>();
//answer is the correct answer to the question created above. 
void randomAnswerGenerator(int answer)
    {
        correctAnswerIndex = Mathf.FloorToInt(Random.value * 3);
        for (int i = 0; i < 3; i++)
        {
            if (i == correctAnswerIndex)
            { //If this is the index for the correct answer, put correct answer here
                answerChoices.Add(answer);
            }
            else
            {
                int newAnswer = -1;
                int randOpt = Mathf.FloorToInt(Random.value * 2); //Should we add or subtract the random number
                int randBase = Mathf.FloorToInt(Random.value * 5) + 1; //Plus 1 so it doesn't equal zero. Change the 5 to modify how much the generated answers will differ from the real answer
                if (randOpt == 0)
                { //Add
                    newAnswer = answer + randBase;
                }
                else
                { //Subtract
                    newAnswer = answer - randBase;
                }
                answerChoices.Add(newAnswer);
            }
        }
    }

Using the above code, you can create a mini math game in a jiffy.

Happy Coding!

The post Create a math game for kids using Unity Scripting appeared first on Code Saying.

]]>
http://codesaying.com/create-a-math-game-for-kids-using-unity-scripting/feed/ 0
Coroutines in Unity: Part 3 – Usage http://codesaying.com/coroutines-in-unity-part3-usage/?utm_source=rss&utm_medium=rss&utm_campaign=coroutines-in-unity-part3-usage http://codesaying.com/coroutines-in-unity-part3-usage/#respond Sat, 25 Apr 2020 18:52:03 +0000 http://codesaying.com/?p=656 In the previous parts, we learned the basics of Coroutines in Unity and some interesting facts about them. In this part, we will learn when we can use coroutines in Unity. Downloading data from the server When you are downloading data from internet, let say hitting the server for a GET or POST request, coroutines…

The post Coroutines in Unity: Part 3 – Usage appeared first on Code Saying.

]]>
In the previous parts, we learned the basics of Coroutines in Unity and some interesting facts about them. In this part, we will learn when we can use coroutines in Unity.

Downloading data from the server

When you are downloading data from internet, let say hitting the server for a GET or POST request, coroutines are used. Here are some examples:

GET Request
   public IEnumerator CallGetApi(string serverUrl)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(serverUrl))
        {
            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();
            if (!webRequest.isNetworkError)
            {
                Debug.Log(webRequest.downloadHandler.text);
            }
        }
    }
POST Request
    string serverUrl;
    string formKey;
    string formValue;
    public IEnumerator CallPostApi()
    {
        WWWForm wForm = new WWWForm();
        wForm.AddField(formKey, formValue);
        using (UnityWebRequest www = UnityWebRequest.Post(serverUrl, wForm))
        {
            yield return www.SendWebRequest();
            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log(www.downloadHandler.text);
            }
        }
    }

Usage of Coroutines in Unity over update

We mostly use the Update function to perform periodic tasks. However, this function is called many times per second. You can use a coroutine when you do not need periodic task to repeat every frame. The example can be seen here.

Execute a task after an event occurs

If we want to run a task after an event occurs, we can make use of coroutines using WaitUntil() CustomYieldInstruction. WaitUntil suspends the coroutine execution until the supplied delegate evaluates to true. Lets say I want to wait till timer > 0, and show the game over screen as soon as timer< 0, we will use:

   IEnumerator WaitForTimer(){
        yield return new WaitUntil(()=> timer < 0);
        Debug.Log("Show Game Over screen");
    }

The condition inside WaitUntil should be a bool condition. The coroutine waits till this condition is false and as soon as this condition returns true, the coroutine completes its execution.

Coroutines in Unity can be used to spread an effect over a period of time

Lets say you want to show a fading effect. If you put the loop in Update, you will not be able to see the transition. However, coroutines are helpful in these cases.

IEnumerator Fade() 
{
    for (float ft = 1f; ft >= 0; ft -= 0.1f) 
    {
        Color c = renderer.material.color;
        c.a = ft;
        renderer.material.color = c;
        yield return new WaitForSeconds(0.1f);
    }
}

This concludes the Coroutines tutorial.

Happy Coding!

The post Coroutines in Unity: Part 3 – Usage appeared first on Code Saying.

]]>
http://codesaying.com/coroutines-in-unity-part3-usage/feed/ 0
Coroutines in Unity: Part 2 – Interesting facts http://codesaying.com/coroutines-in-unity-part2-interesting-facts/?utm_source=rss&utm_medium=rss&utm_campaign=coroutines-in-unity-part2-interesting-facts http://codesaying.com/coroutines-in-unity-part2-interesting-facts/#respond Sat, 25 Apr 2020 14:28:19 +0000 http://codesaying.com/?p=612 In the previous part, we learnt about the basics of coroutines in Unity. Let us now learn some important and interesting points regarding Coroutines. Effect of Disabling an object on Coroutines in Unity: Disabling a gameobject, i.e. using SetActive(false) stops a coroutine. Also, calling Destroy(example) (where example is a MonoBehaviour instance) immediately triggers OnDisable. The…

The post Coroutines in Unity: Part 2 – Interesting facts appeared first on Code Saying.

]]>

In the previous part, we learnt about the basics of coroutines in Unity. Let us now learn some important and interesting points regarding Coroutines.

Effect of Disabling an object on Coroutines in Unity:

Disabling a gameobject, i.e. using SetActive(false) stops a coroutine.

Also, calling Destroy(example) (where example is a MonoBehaviour instance) immediately triggers OnDisable. The coroutine is thus processed, effectively stopping it. Finally, OnDestroy is invoked at the end of the frame.

However, disabling a MonoBehaviour does not stop a coroutine.

Script Execution order affects Coroutines in Unity

The script execution order affects the execution of coroutine as well. For instance, lets say, I have two scripts: Script1 and Script2. These scripts have an execution order of 100 and 120 respectively (i.e. Script1 runs first). Further, in both scripts, I call a Coroutine in Start() function. 

So, the execution order of functions is:

Start() of Script1
Start() of Script2
Coroutine of Script1
Coroutine of Script2

StartCoroutine is a method of MonoBehaviour

StartCoroutine is a public method of the MonoBehaviour. Thus, you need a MonoBehaviour class or an object of MonoBehaviour to call a coroutine.

Only one coroutine can wait for another coroutine

Lets us understand this with an example

     void Start ()
     {
         Coroutine f1 = StartCoroutine(firstcoroutine ());
         StartCoroutine(waitingCoroutine1 (f1));
         StartCoroutine(waitingCoroutine2 (f1));
     }

    IEnumerator firstcoroutine()
    {
        yield return new WaitForSeconds(3);
    }

    IEnumerator waitingCoroutine1(Coroutine c)
    {
        yield return c;
        Debug.Log("end waitingCoroutine1");
    }

    IEnumerator waitingCoroutine2(Coroutine c)
    {
        yield return c;
        Debug.Log("end waitingCoroutine2");
    }

Here, we have three coroutines where waitingCoroutine1 and waitingCoroutine2 wait for firstcoroutine at the yield statement. On running this script, you will get a unity log stating:

Another coroutine is already waiting for this coroutine! Currently only one coroutine can wait for another coroutine!“.

Consequently, Debug.Log(“end waitingCoroutine2”); statement is never executed. This is because waitingCoroutine1 is already waiting for firstcoroutine, so waitingCoroutine2 cannot simultaneously wait for firstcoroutine.

Coroutines in Unity cannot be started on an inactive GameObject

Lets say you have a script Execution1 attached to gameobject: Object1

public class Execution1 : MonoBehaviour
{
    public IEnumerator ExecuteIt()
    {
        yield return null;
        Debug.Log(" Coroutine Execution1");
    }
}

Another script RunExecution has a function that accesses the ExecuteIt function of Execution1. This script is attached to Object2.

public class RunExecution : MonoBehaviour
{
    public Execution1 executeRoutine1;

    void Start()
    {
       executeRoutine1.StartCoroutine(executeRoutine1.ExecuteIt());
    }
}

If Object1 is disabled, ExecuteIt throws an exception:

“Coroutine couldn’t be started because the game object ‘Object1’ is inactive!”

However, if we had written the following in RunExecution

    void Start()
    {
       StartCoroutine(executeRoutine1.ExecuteIt());
    }

The ExecuteIt function is called as the calling script is placed on Object2 which is still active.

WaitForSeconds is dependent on TimeScale

The following Coroutine will not work when Time.timeScale is equal to 0.

    public int timer = 60;
    public IEnumerator Timer()
    {
        while (timer > 0)
        {
            Debug.Log("inside timer");
            yield return new WaitForSeconds(1);
            timer--;
        }
        Debug.Log("Game Over");
        yield return null;
    }

This is because timeScale affects all the time and delta time measuring variables. Thus when timeScale = 0, WaitForSeconds waits indefinitely.

Coroutines in Unity can be stopped only at the yield statement

It means that whenever you try and stop the coroutine, any lines written before the yield statement will execute irrespective of stopping the coroutine.

To explain this, lets take the example of the above Timer Coroutine. You can notice the Debug statement in the while loop. Whenever you try and stop this coroutine, this debug will always run.

We will learn about when to use Coroutines in the next part.

Happy Coding!

The post Coroutines in Unity: Part 2 – Interesting facts appeared first on Code Saying.

]]>
http://codesaying.com/coroutines-in-unity-part2-interesting-facts/feed/ 0
Coroutines in Unity: Part 1 – Basics http://codesaying.com/coroutines-in-unity-part1-basics/?utm_source=rss&utm_medium=rss&utm_campaign=coroutines-in-unity-part1-basics http://codesaying.com/coroutines-in-unity-part1-basics/#respond Sat, 25 Apr 2020 14:25:14 +0000 http://codesaying.com/?p=608 As per Unity docs, a coroutine is a function that can suspend its execution (yield) until the given YieldInstruction finishes. In other words, coroutines in Unity work like normal functions till they encounter a YieldInstruction. At this point, the coroutine is paused and the control returns to the function which called the coroutine in the…

The post Coroutines in Unity: Part 1 – Basics appeared first on Code Saying.

]]>

As per Unity docs, a coroutine is a function that can suspend its execution (yield) until the given YieldInstruction finishes. In other words, coroutines in Unity work like normal functions till they encounter a YieldInstruction. At this point, the coroutine is paused and the control returns to the function which called the coroutine in the first place. Further, the coroutine continues its execution normally after the yield condition is met.

Using the Coroutines in Unity

A coroutine is a function which has a return type of IEnumerator and it includes a yield return statement somewhere in the body. To set a coroutine running, you need to use the StartCoroutine function.

The yield return null line pauses the execution and is resumed in the following frame. 

Here is an example of a coroutine that counts down the timer from 60 to 0.

    void Start()
    {
        StartCoroutine("Timer");
    }

    public int timer = 60;
    public IEnumerator Timer()
    {
        while (timer > 0)
        {
            yield return new WaitForSeconds(1);
            timer--;
        }
        Debug.Log("Game Over");
        yield return null;
    }

There are other ways of using the StartCoroutine function:

StartCoroutine(Timer());

or

 IEnumerator coroutine = Timer();
 StartCoroutine(coroutine);

Note: StartCoroutine is a public method of the MonoBehaviour. Thus, you need a MonoBehaviour class or an object of MonoBehaviour to call a coroutine.

Benefits of Coroutines over update

Coroutines can be used as a way to spread an effect over a period of time, but it is also a useful optimization. We mostly use the Update function to perform periodic tasks. However, this function is called many times per second. You can use a coroutine when you do not need periodic task to repeat every frame. An example of this might be an alarm that warns the player if an enemy is nearby. The code might look something like this:

    bool ProximityCheck()
    {
        for (int i = 0; i < enemies.Length; i++)
        {
            if(Vector3.Distance(transform.position,enemies[i].transform.position) < dangerDistance)
            {
                return true;
            }
        }
        return false;
    }

If there are a lot of enemies then calling this function every frame might introduce a significant overhead. However, you could use a coroutine to call it every tenth of a second:

    IEnumerator DoCheck()
    {
        while(true)
        {
            if(ProximityCheck()){
                //run... the enemy is near!
            }
            yield return new WaitForSeconds(.1f);
        }
    }

This would greatly reduce the number of checks carried out without any noticeable effect on gameplay.

Stopping a coroutine

You can stop a coroutine with StopCoroutine and StopAllCoroutines

StopCoroutine has three function overloads:

A string function naming the active coroutine

Use this to stop the coroutine which initially started with a string.

StopCoroutine(“Timer”);

The IEnumerator variable used earlier to create the coroutine.

Use this to stop the coroutine which started with IEnumerator as above. 

StopCoroutine(coroutine);

The Coroutine to stop the manually created Coroutine.

Use StopCoroutine with the Coroutine used for creation.

i.e., if you have started a coroutine as below: 

Coroutine f1 = StartCoroutine(Timer());

you can stop coroutine using

StopCoroutine(f1);

Note: Using StopCoroutine(Timer()); will not stop the coroutine.

Yield Instructions that can be used

WaitForEndOfFrameWaits until the end of the frame after Unity has rendererd every Camera and GUI, just before displaying the frame on screen.
WaitForFixedUpdateWaits until next fixed frame rate update function.
WaitForSecondsSuspends the coroutine execution for the given amount of seconds using scaled time.
WaitForSecondsRealtimeSuspends the coroutine execution for the given amount of seconds using unscaled time.
WaitUntilSuspends the coroutine execution until the supplied delegate evaluates to true.
WaitWhileSuspends the coroutine execution until the supplied delegate evaluates to false.

We will learn some interesting facts about Coroutines in the next part.

Happy Coding!

The post Coroutines in Unity: Part 1 – Basics appeared first on Code Saying.

]]>
http://codesaying.com/coroutines-in-unity-part1-basics/feed/ 0
Parse Xml in Unity3D http://codesaying.com/parse-xml-in-unity3d/?utm_source=rss&utm_medium=rss&utm_campaign=parse-xml-in-unity3d http://codesaying.com/parse-xml-in-unity3d/#respond Mon, 20 Apr 2020 18:30:39 +0000 http://codesaying.com/?p=641 Have a .xml file that needs parsing in unity? Let us learn what is an xml file and how you can parse xml in unity3d. What is an Xml? XML stands for eXtensible Markup Language. It is a software- and hardware-independent tool for storing and transporting data. It can be used to save your data…

The post Parse Xml in Unity3D appeared first on Code Saying.

]]>
Have a .xml file that needs parsing in unity? Let us learn what is an xml file and how you can parse xml in unity3d.

What is an Xml?

XML stands for eXtensible Markup Language. It is a software- and hardware-independent tool for storing and transporting data. It can be used to save your data in Unity.

XML documents must contain one root element that is the parent of all other elements.

<root>
  <child>
    <subchild>.....</subchild>
  </child>
</root>

This line is called the XML prolog:

<?xml version="1.0" encoding="UTF-8"?>

The XML prolog is optional. If it exists, it must come first in the document.

In XML, it is illegal to omit the closing tag. All elements must have a closing tag. <child> has closing tag </child>. Also, XML tags are case sensitive. 

Here is an example of an xml:

<?xml version="1.0"?>
<PlayerData>
   <lives>3</lives>
   <currentLevel>1</currentLevel>
</PlayerData>

This xml corresponds to a class PlayerData with two variables: playerLives and currentLevel.

public class PlayerData
{
    public int lives;
    public int currentLevel;
}

Parse XML in Unity3D

When File is present at Application.persistentDataPath

We use XmlSerializer for parsing the data.

   string filePath = Path.Combine(Application.persistentDataPath, "filename.xml"); 
    PlayerData LoadData()
    {
        if (File.Exists(filePath))
        {
            string fileText = File.ReadAllText(filePath);
            XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
            using (StringReader reader = new StringReader(fileText))
            {
                return (PlayerData)(serializer.Deserialize(reader)) as PlayerData;
            }
        }
        return null;
           
    }

Here, first we check if the file exists. Then we deserialize the StringReader to return an object of the type PlayerData in this case.

When File is present in Resources Folder

   string fileName = "fileName";
    XmlSerializer serializer = new XmlSerializer(typeof(PlayerData));
    string data = Resources.Load<TextAsset>(fileName).text;
    using (StringReader reader = new StringReader(data))
    {
        playerData = (serializer.Deserialize(reader)) as PlayerData;
    }

Saving an Xml File

Now, if we want to save the player data to an xml file, we can do this like:

   string filePath = Path.Combine(Application.persistentDataPath, "filename.xml"); 
    void SaveData(PlayerData data)
    {
        var serializer = new XmlSerializer(typeof(PlayerData));

        using (var stream = new FileStream(filePath, FileMode.Create))
        {
            serializer.Serialize(stream, data);
        }
    }

We Serialize the FileStream to save the PlayerData object (here data) in the xml file at path given by filePath.

It is not recommended to use Resources folder when saving data in an xml because there isnt an actual “Resources” folder available in build.

Happy Parsing!

The post Parse Xml in Unity3D appeared first on Code Saying.

]]>
http://codesaying.com/parse-xml-in-unity3d/feed/ 0
Cron Job in Nodejs http://codesaying.com/cron-job-in-nodejs/?utm_source=rss&utm_medium=rss&utm_campaign=cron-job-in-nodejs http://codesaying.com/cron-job-in-nodejs/#respond Sun, 19 Apr 2020 15:24:01 +0000 http://codesaying.com/?p=583 In this blog, we will learn how to create a cron job in nodejs. For this, we will be using node package node-cron. Source code of this package can be found on Github using this link. So lets get started with it. First install node-cron as under Then, in the code, import this package as…

The post Cron Job in Nodejs appeared first on Code Saying.

]]>
In this blog, we will learn how to create a cron job in nodejs. For this, we will be using node package node-cron. Source code of this package can be found on Github using this link.

So lets get started with it. First install node-cron as under

npm install --save node-cron

Then, in the code, import this package as

var cron = require("node-cron");

and then you can schedule cron jobs as

cron.schedule("* * * * * *", () => {
    console.log("running a task every second");
  });

In the above example, we create a cron job and parameter passed to schedule function are * * * * * * . Explanation of this is as

Values allowed

fieldvalue
second 0-59
minute0-59
hour0-23
day of month1-31
month1-12 (or names)
day of week0-7 (or names, 0 or 7 are sunday)

Operators than can be used

OperatorUsage
/for step values
,value list separator
range of values

These operators have been explained in the Examples section.

Examples of Cron Job in NodeJS

Run cron job every day at 10:30:20 AM

cron.schedule("20 30 10 * * *", () => {
    console.log("running a task everyday at 10:30am");
  });

Run cron job on the first of every month

cron.schedule("0 0 1 * *", () => {
    console.log("running a task on the 1st of every month at 00:00");
  });

Run cron job every hour

cron.schedule("0 * * * *", () => {
    console.log("running a task hourly");
  });

There is another way for doing so.

‘/’ operator helps you to get step values as illustrated in the table earlier. It can be used in the following way. If you want a cron job to run every hour, you can write */1 in the place holder for an hour. Similarly, you can write */5 in the place holder for an hour if you want the cron job to run every 5 hours. Example of running cron job every hour is here:

cron.schedule(" 0 */1 * * *", () => {
    console.log("running a task hour");
  });

Run cron job after every 10 mins

cron.schedule(" */10 * * * *", () => {
    console.log("running a task hour");
  });

Run cron job on a particular date

cron.schedule(" 0 0 1 11 *", () => {
    console.log("runs the task on 1st November at 00:00 hrs every year");
  });

Run cron job using multiple values

Lets say you want to run a cron job on 1,2,4 and 5 minute:

cron.schedule('1,2,4,5 * * * *', () => {
  console.log('running every minute 1, 2, 4 and 5');
});

Run cron job using a range

If you want a cron job to run from every minute 1-5.

cron.schedule('1-5 * * * *', () => {
  console.log('running every minute to 1 from 5');
});

Run cron using name

For month and week day you also may use names or short names.  e.g

cron.schedule('* * * January,September Sunday', () => {
  console.log('running on Sundays of January and September');
});

or we can also use short names

cron.schedule('* * * Jan,Sep Sun', () => {
  console.log('running on Sundays of January and September');
})

Happy Scheduling!

The post Cron Job in Nodejs appeared first on Code Saying.

]]>
http://codesaying.com/cron-job-in-nodejs/feed/ 0
Life System in Unity http://codesaying.com/life-counter-in-unity/?utm_source=rss&utm_medium=rss&utm_campaign=life-counter-in-unity http://codesaying.com/life-counter-in-unity/#respond Wed, 01 Apr 2020 10:29:17 +0000 http://codesaying.com/?p=554 We all must have played games in which we need lives to continue playing. Some of these games include Candy Crush Saga, Candy Crush Soda and so on. Every unity developer would have made; or would need to make a life system in their development career. So, let us learn to create a life system…

The post Life System in Unity appeared first on Code Saying.

]]>
We all must have played games in which we need lives to continue playing. Some of these games include Candy Crush Saga, Candy Crush Soda and so on. Every unity developer would have made; or would need to make a life system in their development career. So, let us learn to create a life system in Unity in an easy way.

The important parameters in creating the life system are
– the maximum number of lives a player can get,
– the time in which a life replenishes , and
– a counter that keeps track of the number of lives the player has

    //The max lives that a player can have, let us take 5
    int maxLives = 5;

    //Each life replenishes in 15minutes or 900 seconds
    float lifeReplenishTime = 900f;

    // The number of lives that the player has
    int _lives;
    public int lives{
        set {
            _lives = value; 
            PlayerPrefs.SetInt("Lives", _lives);
        }
        get {
            return _lives;
        }
    }

Now, we need a counter that determines the time lapsed:

    public double timerForLife;

We update the parameter timerForLife in the Update function.

private void Update()
 {
        // life counter needs update only if lives are less than maxLives
        if (lives < maxLives)
        {
            timerForLife += Time.deltaTime;
            //when timerForLife becomes greater than 900sec, we update a life
            if (timerForLife > lifeReplenishTime)
            {
                lives++; //you get a life after 15 minutes
                //It is advised to use UpdateLives(timerForLife) here instead of lives++;
            }
        }
 }

    //PlayerPref "LifeUpdateTime" stores the value in string of the time when the life counter lives was last updated
    void UpdateLives(double timerToAdd ){
        if (lives < maxLives)
        {
            int livesToAdd = Mathf.FloorToInt((float)timerToAdd / lifeReplenishTime);
            timerForLife = (float)timerToAdd % lifeReplenishTime;
            lives += livesToAdd;
            if (lives > maxLives)
            {
                lives = maxLives;
                timerForLife = 0;
            } 
        }
        PlayerPrefs.SetString("LifeUpdateTime", DateTime.Now.ToString());
    }

We have now created a basic life system. But we also need the lives to replenish even when the game is shut or running in background. So that whenever the player relaunches the game, he gets his updated lives.

Update the life counter in Unity when the app goes to background

For this, we need to save the time at which the app goes to background. We will make use of the OnApplicationPause function of Unity.

DateTime  timeOfPause;
void OnApplicationPause(bool isPause){
        if (isPause)
        {
            //save the system time at which the application went in background 
            timeOfPause = System.DateTime.Now;
        }
        else
        {
            if(timeOfPause == default(DateTime)){
                timeOfPause = System.DateTime.Now;
            }
            float timerToAdd = (float)(System.DateTime.Now - timeOfPause).TotalSeconds;
            timerForLife += timerToAdd;
            UpdateLives(timerForLife);
        }
    }

Update the life counter in Unity whenever the game is relaunched

We update the life counter in the Awake function

    void Awake () {
      
        if(!PlayerPrefs.HasKey("Lives")){
            PlayerPrefs.SetString("LifeUpdateTime", DateTime.Now.ToString());
        }
        lives = PlayerPrefs.GetInt("Lives", maxLives);

        //update life counter only if lives are less than maxLives
        if (lives < maxLives)
        {
            //timerToAdd calculates the time lapsed till since the game was last shut down
            float timerToAdd = (float)(System.DateTime.Now - Convert.ToDateTime(PlayerPrefs.GetString("LifeUpdateTime"))).TotalSeconds;
            //update life counter depending upon how much time has been lapsed
            UpdateLives(timerToAdd);
        }
    }

Display the time left for a new life

    public string showLifeTimeInMinutes()
    {
        float timeLeft = lifeReplenishTime - (float)timerForLife;
        int min = Mathf.FloorToInt(timeLeft / 60);
        int sec = Mathf.FloorToInt(timeLeft % 60);
        return min + ":" + sec.ToString("00");
    }

In the similar way, you can calculate the timer for creating and upgrading buildings, upgrading troops, etc in games like Clash of Clans.

One problem that the developer faces in creating a life system in Unity is that the player tends to changes the system time (time of his device) in order to gain life. To overcome this issue, it is advised to fetch the time from server instead of using System.DateTime.Now.

If you have any queries, feel free to comment.

Happy Coding!

The post Life System in Unity appeared first on Code Saying.

]]>
http://codesaying.com/life-counter-in-unity/feed/ 0
Time.deltaTime in Unity3D http://codesaying.com/time-deltatime-in-unity3d/?utm_source=rss&utm_medium=rss&utm_campaign=time-deltatime-in-unity3d http://codesaying.com/time-deltatime-in-unity3d/#respond Sat, 11 Jan 2020 17:33:18 +0000 http://codesaying.com/?p=530 It is very important for a Unity Developer to have a sound understanding of Time.deltaTime. Let us learn the basics of Time.deltaTime in Unity3D with some examples. What is Time.deltaTime? Time.deltaTime is the completion time in seconds since the last frame. It is read only. Therefore you cannot modify it! This property provides the time…

The post Time.deltaTime in Unity3D appeared first on Code Saying.

]]>
It is very important for a Unity Developer to have a sound understanding of Time.deltaTime. Let us learn the basics of Time.deltaTime in Unity3D with some examples.

What is Time.deltaTime?

Time.deltaTime is the completion time in seconds since the last frame. It is read only. Therefore you cannot modify it! This property provides the time between the current and previous frame. But what does that mean?

We are aware of the Update method in Unity3D. Time.deltaTime in layman terms would be the time lapse between two update methods. Let’s say there are 10 lines of code in the Update Method. So, Time.deltaTime would determine how much time does it take to execute the lines of code in one frame. This property is a variable value as its value would depend upon how much time one frame takes to execute which further depends upon how much lines of code needs to be executed.

Points to note:

  • FixedUpdate uses fixedDeltaTime instead of deltaTime.
  • Unity can call OnGUI multiple times per frame. Therefore, it is not advisable to rely on Time.deltaTime inside OnGUI method.

Time.deltaTime in relation with fps

FPS is frames per second and the time taken for completion of one frame is Time.deltaTime. In other words, we can say,

fps = 1/Time.delaTime

or

Time.DeltaTime = 1/fps

Therefore, when fps is 60, Time.deltaTime is = 0.0166666 seconds

Usage of Time.deltaTime in Unity3D

Creating a Timer

    private float timer = 0.0f;
    void Update()
    {
        timer += Time.deltaTime;
        //Game Over after 60 seconds
        if(timer > 60){
            //Game Over
        }
    }

Smooth Translation of an object independent of Frame Rate

Let us use static speed for translation of an object for movement in x-axis, lets say speed = 5 as below:

    private int speed = 5;
    void Update()
    {
        transform.Translate(speed , 0 , 0);
    }

Lets test the lines of code on a device with fps equal to 60 (i.e. 60 frames in one second). The object moves 5 units in 1 frame(as speed=5). The distance moved by object in 60 frames or 1 second is 60*5 = 300 units

Now, lets test this code on a device with fps equal to 30. The object still moves 5 units in 1 frame as speed = 5. However, the distance moved by object in 30 frames or 1 second is 30*5 = 150 units.

Therefore, using static value, an object on a device with higher fps moves faster than that on a lower fps device, which is not what is desired.

Lets see what happens when we use Time.deltaTime.

    void Update()
    {
        transform.Translate(Time.deltaTime , 0 , 0);
    }

The above line of code gives a smooth translation in x-axis as the object will always move independent of the Time Frame i.e. if the fps falls low or high, the translation is linear.

Lets say the fps is 60, i.e. 60 frames in one second. Time for each frame is 0.016666666 as explained formerly. The distance moved by object in 1 second is 1 unit(0.0166666*60 frames)

If the fps is 30, i.e. 30 frames in one second, time for each frame is 0.03333. The distance moved by object in 1 second is 1 unit(0.03333*30 frames)

Therefore, the object moves over the same distance irrespective of the device performance.

So, Time.deltaTime is used for actions that need to be independent of frame rate.

Happy Coding!

The post Time.deltaTime in Unity3D appeared first on Code Saying.

]]>
http://codesaying.com/time-deltatime-in-unity3d/feed/ 0