Skip to main content
gamedev.net
🔒 Locked 🎮 Unity

Unity basic Script question

Started by tmer1 Feb 4, 2015 at 8:40 AM 3 replies 2.4k views
Original Post
tmer1
tmer1

The code below works and displays a value of 10 in the console. My question is how does this work, because we never gave the int "number" a value?


using UnityEngine;
using System.Collections;

public class VariablesAndFunctions : MonoBehaviour
{   
    int myInt = 5;
    
    
    void Start ()
    {
        myInt = MultiplyByTwo(myInt);
        Debug.Log (myInt);
    }
    
    
    int MultiplyByTwo (int number)
    {
        int ret;
        ret = number * 2;
        return ret;
    }
}
Brother Bob
Brother Bob

The variable number is a function parameter, and you gave it a value by passing myInt to the function when you called MultiplyByTwo.

tmer1
tmer1

        myInt = MultiplyByTwo(myInt);

What is this line doing ?

and what is "return"

SimonForsman
SimonForsman

        myInt = MultiplyByTwo(myInt);

What is this line doing ?

and what is "return"

it sets the value of myInt to the value returned by the "MultiplyByTwo" function.

The multiplybytwo function works like this

[source]
//this a function named MultiplyByTwo that returns an integer
//the first int on the line specifies the type of data the function will return)
//MultiplyByTwo is the functions name
//and it takes one integer parameter that will be named "number" inside the function (int number)
int MultiplyByTwo (int number)
{
int ret; //create a temporary integer variable named "ret"
ret = number * 2; //set the value of ret to number * 2 //remember, number has whatever value we pass to the function (in your example it has the same value as myInt)
return ret; //return the value stored in ret.
}
[/source]
[size="1"]I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!
Kaustek
Kaustek

Because it's actually:

myInt = MultiplyByTwo(number)

Whatever you place between the parenthesis, is what becomes "number" .

Think of it this way (not functional code, just demonstrating the process)



myInt = 5;

     Start()
     {  
          //Pass myInt which is 5 into MultiplyByTwo
          myInt = MultiplyByTwo(5);
     }

     int MultiPlyByTwo(int 5)
     {
          int ret;
          //Since we had 5 passed in as an argument, number is 5
          //Multiply the int passed in by 2, and assign it to ret
          ret = 5 * 2;
          //Return the value of ret to the caller (Start.myInt)
          return 10;
     }

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.