Home > Back-end >  Is it possible from getting a public void from another C# file?
Is it possible from getting a public void from another C# file?

Time:03-23

I'm quite new to C#, and I'm using it for coding a game on Unity. I have a file named GameTools.cs that helps me with commands so that I don't have to do too much. It basically makes my code simpler and shorter. Now with the code...

//GameTools.cs
public void DoSomething() {
    //some code
    //some more code
}

And inside my file IntroBehavior.cs has the same void as shown above.

//IntroBehavior.cs
void Start() {
    DoSomething(); //command shown above
}

Will this work? Do I have to specify something inside IntroBehavior that will be able to run code from GameTools?

CodePudding user response:

in c# all functions belong to classes. They are either instance methods, or static

Instance methods operate in instances of the class

public class User{
      void Login();   <<< === instance method
}

used like this

 var u1 = new User();
 u1.Login();

Static methods dont operate on instances of classes

public class User{
       static User CreateUser();  <<<<<= static
       Login();   <<< === instance method
}

Here you use them like this

  var u2 = User.CreateUser();

See that you can mix the 2. If you only want static methods in a class (to be sure ) then do

public static class User{
       static CreateUser();  <<<<<= static
       //Login();   <<< not allowed
}

So you want

static public class GameTools{ 
   public static void CallSomething() {
    //some code
    //some more code
   }
}

Now in you other file

 void Start() {
    GameTools.CallSomething(); //command shown above
  }

Of course that method has to be in a class too.

  •  Tags:  
  • c#
  • Related