0
\$\begingroup\$

I am trying to add a random number to an existing number. I am able to get the output in Unity console, but in the inspector, I can see that the public variable is on a non stop loop.

This is my inspector view, with the final result selected.

I intend to produce the result when I press the enter key. Is this an efficient way, or can I improve on the code? I am a beginner, and passionate to learn.

Here's the code:

using UnityEngine;
using System.Collections;

public class LearningScript : MonoBehaviour
{
    public int number1 = 5;
    public int number2 = 10;
    public int number3=20;
    public int finalResult;
    public string statement = "NO KEY PRESSED";

    void Update()
    {
        input ();
        if (Input.GetKeyDown (KeyCode.Return))
            Debug.Log (finalResult);
    }

    void Start(){}

    int addnumbers(int num1,int num2)
    {
        int additionResult = num1 + num2;
        return additionResult;
    }

    void input()
    {
        int randomNumber = Random.Range (1, 10);
        finalResult=    addnumbers (number1, randomNumber); 
    }   
}
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

As stated, your problem is in calling input() on each Update(). You would replace your Update function as follows (be particularly mindful of the closing brackets on the if statement):

void Update() {
    if (Input.GetKeyDown (KeyCode.Return)) {
        input ();
        Debug.Log (finalResult);
    }
}

Given the context of the question, lets have a closer look at why this is the problem.

The Update Method

The Update() method comes from MonoBehaviour. You will notice that at the top, your class is called LearningScript : MonoBehaviour. The : MonoBehaviour offers extension of the original MonoBehaviour class that provides most of the functionality, in Unity.

Update() is a re-iterating method that will call on each game update. You should use this as your main starting point for logic that repeats itself, but use caution: Updating too much can easily lead to freezing. In this case, you are actually not doing anything to freeze your game. You are simply refreshing finalResult so quickly that it overrides any real-time changes you may make, often quicker than you would notice.

By ensuring you only update your input when you need to, i.e. when the user first presses the Enter button, you ensure that your code is far more efficient.

void Update() {
    if (Input.GetKeyDown (KeyCode.Return)) {
        input ();
        Debug.Log (finalResult);
    }
}

Notes on MonoBehaviour methods

Update is but one of many methods you can implement from the original MonoBehaviour class. While it is easily the most common, you will quickly find yourself using other methods, such as Start, FixedUpdate and OnCollisionEnter(Collision other). You can find a good list, linking you to instructions on each method, under "Messages" in the Unity API listing for MonoBehaviour.

Start is as commonly used as Update, as it provides the entry point for code to set up your class. As a result, it is also provided by default, when you create a new script. In your above code, you set everything up when you declare the variables, and could completely remove the Start() {..} function without any change to your script.

Notes on if statements

In your original statement, you write it as follows:

if(input)
    doSomething;

This is not the wrong way to do it; in fact, it is often a matter of opinion. You will notice that my solution writes it as follows:

if(input) {
    doSomething;
    doSomethingElse;
}

This part is important: With the use of multiple lines, you must use enclosing "squiggly brackets" ({ }). If you do not, it can cause errors. What is worst; it can cause errors later in your class, as your compiler may interpret the statement entirely different to how you intend, and only realise there is a problem when later lines of code do not make sense given its misunderstanding. Long story short, if you have this problem, Unity could very well tell you it is a completely different problem, on a completely different line. It is important to know that these things do happen, and can lead to some very frustrating moments. Think of it as character building - even the best of us have those stories where we banged our head against a brick wall for hours only to have someone point out the obvious problem after a minute of review.

Notes on naming conventions

Naming conventions are even more debatable, when it comes down to the semantics of how we should name things. One major thing I will point out is the use of capital letters to start each new word in a name. You seem to be following this standard, except for your classes. While you surely would have no problem interpretting addnumbers, most would tell you it should be addNumbers.

A personal preference of mine is to start with a lower case, if I am naming a variable, or upper case, if I am naming a method. So I would use AddNumbers. This just makes it easier to quickly identify the variables and the methods.

\$\endgroup\$
0
0
\$\begingroup\$

That is because you call input() in the Update method, which is called each frame. Put your input() in the input-taking if block.

void Update()
{  
     if (Input.GetKeyDown (KeyCode.Return))
     {
        input ();
        Debug.Log (finalResult);
     }   
}

Now input only gets called once you press down Return.

\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .