1

Hey I was wondering why can I use a function with no return value "void". But if I make a function that has same name as the script name I can make a function can anyone please clarify this?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Parameters  {


    public Parameters()
    {
//why am I able to make this function
    }
}
Daniel
  • 14,004
  • 16
  • 96
  • 156
Jerry
  • 43
  • 6
  • 2
    Possible duplicate of [Constructor in C#](https://stackoverflow.com/questions/33693253/constructor-in-c-sharp) – derHugo Jan 09 '19 at 18:31

1 Answers1

0

A function defined like this is a constructor, used for initializing an object.

More info on this here:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors

Fábio Junqueira
  • 2,701
  • 21
  • 20
  • thanks a lot so you mean that I can make multiple new objects using the constructor in the given script? – Jerry Jan 09 '19 at 18:29
  • That function will be called when you do the following in your code: var parameters = new Parameters(); // a new Parameters object is initialized using the constructor you defined – Fábio Junqueira Jan 09 '19 at 18:31
  • Ah okay i think I get it you can use it for setting the values of the object which own the class i guess? – Jerry Jan 09 '19 at 18:33
  • Yep, they are used to set default values and add behavior to an object initialization – Fábio Junqueira Jan 09 '19 at 18:35