Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by youngapprentice · Aug 06, 2012 at 07:34 PM · functionparameter

Why pass parameters into a function?

Hi, all! I know I just posted, and I don't mean to be a pest, but I have another totally separate question.

Why would I pass parameters into a function? This may sound silly, but wouldn't:

 var start = 0.1;
 
 function MakeStart(){
     Debug.Log(start);
 }
 
 function Update(){
     MakeStart();
     }

Be exactly the same as:

 var start = 0.1;
 
 function MakeStart(number : float){
     Debug.Log(number);
 }
 
 function Update(){
     MakeStart(start);
 }


? It seems to me that they are identical. So what is the advantage of passing parameters into a function?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Dragonlance · Aug 06, 2012 at 08:28 PM

Hi!

You use functions with parameters i.e.

a) If you want to call a public the function from another class.

b) If you want to reuse a function and make the rest of the code more readable.

c) If you do not want to allocate the memory for the parameter all the time.

d) Some other cases


Example for a)

You hava a rocket that hits a collider with a Script called Enemy. The enemy has an applyDmg function that you call from the other script:

 public function applyDmg(value : float) {
    health = health - value;
 }


Example for b) is taken from the MouseOrbit Script

     function LateUpdate () {
     if (target) {
         x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
         y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
   
   y = ClampAngle(y, yMinLimit, yMaxLimit);
          
         var rotation = Quaternion.Euler(y, x, 0);
         
         if (Input.GetAxis("Mouse ScrollWheel") < 0) // back
         {
             distance -= Time.deltaTime *10.0f;
 
         }
         if (Input.GetAxis("Mouse ScrollWheel") > 0) // forward
         {
             distance += Time.deltaTime * 10.0f;
         }
         
         var position = rotation * Vector3(0.0, 0.0, -distance) + target.collider.bounds.center;
         
         transform.rotation = rotation;
         transform.position = position;
     }
     
         
 }
 function ClampAngle (angle : float, min : float, max : float) {
  if (angle < -360)
  angle += 360;
  if (angle > 360)
  angle -= 360;
  return Mathf.Clamp (angle, min, max);
 }



Example for c) is only called once the lifetime of the object, so why waste memory and keep the variable as class member. On the other hand if it is called in the update Function, I would do it like your first piece of code.

 var start = 0.1;
 
 function MakeStart(){
     Debug.Log(start);
 }
 
 function Update(){
     MakeStart();
 }



There are other cases. But you are right, often it is wise to have a member variable in the object because if you would call your MakeStart every Update(), there will be a lot of overhead creating a new variable and passing it to the function.

So I would say the conclusion is: Sometimes you really need parameters in functions because you can not send your data otherwise. Sometimes it is wiser to use parameters, because your code will be better to read and cleaner. Sometimes it is a trade between speed and amount of memory uses - so you have to decide what will be better performing.

Hope that helps =)

Comment
Add comment · Show 5 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image whydoidoit · Aug 06, 2012 at 08:29 PM 0
Share

I should point out that passing a variable in a parameter doesn't allocate heap space (just stack space) which helps from a garbage collection point of view. But otherwise you are right, no point copying variables around it all takes time.

avatar image fafase · Aug 06, 2012 at 08:35 PM 0
Share

I think if the variable is not global then you would have to pass it since it does not exist at compilation.

Ex:

 if(smg){
     var aVariable:float = 22;
     Fct(aVariable);
 }

 function Fct(v:float){
    print(v); 
 }
 
avatar image youngapprentice · Aug 06, 2012 at 09:01 PM 0
Share

Thank you for all of the lovely answers! I understand the use of it now. Just bare with me here: If I want to have an Object Lerp one thing or another I usually end up making and re-making variables used in other scripts. Are you saying that ins$$anonymous$$d of completely re-writing it, I can create a public function in a script, attach it to an empty that I just dont destroy on load, and I will be able to access that function and utilize it as long as parameters are fed to it?

avatar image Dragonlance · Aug 06, 2012 at 09:37 PM 0
Share

Yes you could do something like a Utility Library. You will even not have to take care about "destroy on load" - This is only usefull if you want to store data of some type and use it from one scene to the other.

I am not completely sure about utility classes in javascript, because I use C# mostly. $$anonymous$$aybe in js you will be forced to attatch it to an object, because all scripts are a inherit from $$anonymous$$onoBehaviour in unitys javascript (but i am not 100% sure about this)

You can call functions like this from everywhere:

 static function $$anonymous$$ultiply(float x, float y) : float {
     return x*y;
 }

Say this is in a File called $$anonymous$$yFunctions.js

Then you can just call

 var result = $$anonymous$$yFunctions.$$anonymous$$ultiply(10.0, 15.0);
avatar image youngapprentice · Aug 07, 2012 at 12:25 AM 0
Share

Wow you just made my life. I'm sorry this is the very last question. Your examples are great, but I feel like your 'a' example is worded strangely. When you say 'the other script' are you talking about a script called 'Enemy', or are you saying that 'Enemy' contains the function and that the script attached to the rocket calls it and the rocket is ultimately affected by this?

avatar image
0

Answer by whydoidoit · Aug 06, 2012 at 07:58 PM

Parameters enable a function to operate in many different ways or on different values without cluttering your code up with endlessly more variables that are used for just one purpose which can get confusing very fast. For instance it wouldn't be easy to call the same function twice as part of a calculation if they didn't have parameters.

      var numberOne : float;
      var numberTwo : float;
 
      function AddTwoNumbers()
      {
            return numberOne + numberTwo;
      }

      function Update()
      {
             //Works but verbose and messy
             numberOne = 10;
             numberTwo = 20;
             Debug.Log(AddTwoNumbers());
 
             //Lets say we want to call the function on the result
             //to double it - this doesn't work
             numberOne = AddTwoNumbers();
             numberTwo = AddTwoNumbers();
             Debug.Log(AddTwoNumbers());

             //So it would have to be this
             var result = AddTwoNumbers();
             numberOne = result;
             numberTwo = result;
             Debug.Log(AddTwoNumbers());
      }

Perhaps this is easier:

       function AddTwoNumbers(numberOne : float, numberTwo : float)
       {
              return numberOne + numberTwo;
       }

      function Update()
      {
             Debug.Log(AddTwoNumbers(10,20));
             Debug.Log(AddTwoNumbers(10,20), AddTwoNumbers(10,20));
             //Or
             var result = AddTwoNumbers(10,20);
             Debug.Log(AddTwoNumbers(result, result));
             
      }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image whydoidoit · Aug 06, 2012 at 08:00 PM 0
Share

You example shows a case where you could do either - presu$$anonymous$$g $$anonymous$$akeStart is very specific there is not need to give it parameters.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

10 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Source code for library function "RecalculateNormals()"? 4 Answers

Array Problem - Error Code BCE0022 1 Answer

Function as parameter? 1 Answer

How to pass Predicate to a Coroutine? 1 Answer

Defining Parameters in a Function 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges