How does classes overloading work in Unity?
Create an ‘Empty Object’ and attack SomeOtherClass.cs
// SomeOtherClass.cs using UnityEngine; using System.Collections; public class SomeOtherClass : MonoBehaviour { void Start() { SomeClass myClass = new SomeClass(); //The specific Add method called will depend on //the arguments passed in. int mysum = myClass.Add(1, 2); string mytext = myClass.Add("Hello ", "World"); Debug.Log(mysum); // 3 Debug.Log(mytext); // Hello World } public class SomeClass { //The first Add method has a signature of //"Add(int, int)". This signature must be unique. public int Add(int num1, int num2) { return num1 + num2; } //The second Add method has a sugnature of //"Add(string, string)". Again, this must be unique. public string Add(string str1, string str2) { return str1 + str2; } } }
We have overloading when we call a class that has 2 or more methods with the same name.
In the script: – public int Add(int num1, int num2) – and – public string Add(string str1, string str2)
have the same name but the parameters are different and Unity can recognize them as unique.
Reference:
unity3d.com/learn/tutorials/topics/scripting/method-overloading?playlist=17117