Creating And Calling Methods In Unity

Introduction

This blog demonstrates creating and calling methods in Unity.

Prerequisites

Unity Environment version5.6.1

Once again, refer to my previous article to get started.

  • Scripting with C# in Unity

Creating and calling methods (Functions)

Step 1

First, you have to open the Unity project. Create terrain, trees, and water. Add skyboxes in your project. Create C# scripts and rename the script as MyScript.

Go to the mono develop-unity. The default methods will be displayed.

Write the coding like the following.

  1. using System.Collections;  
  2. using System.Collections.Generic;  
  3. using UnityEngine;  
  4. public class MyScript: MonoBehaviour {  
  5.     // Use this for initialization  
  6.     void Start() {  
  7.         int x = applyDamage(5, 100);  
  8.         print("player health:" + x);  
  9.     }  
  10.     int applyDamage(int damageAmount, int health) {  
  11.         return health - damageAmount;  
  12.     }  
  13.     // Update is called once per frame  
  14.     void Update() {}  
  15. }  

 

Save the program

Click on the My Script. The coding will be displayed into the right side. You cannot modify the coding here. Only modify the coding in mono develop.

Click on the Main camera. Go to the Inspector window. Select the My script.

Click on the My Script and select the Reset option.

Click on the “play” button. The game view will be displayed. Click into the console view. The output player health 95 is displayed.

Summary

I hope, you understood creating and calling methods (functions) in unity.

Next Recommended Reading Introduction To Unity Art Design