How do I call a method

I just want to know how to call a method. All the videos on youtube are how to call methods from another script. How do I do it?

void Mymethod()
{
       //random code
}


void Start()
{
      //I want to call the method and have it run the code
}

You just call it!

void Start()
{
  Mymethod();
}

If you do that and it doesn’t work, start sprinkling Debug.Log() calls around to see what code actually is running.

Some folks may suggest using,

this.Mymethod();

and that is technically correct as well, and actually equivalent.

If the method is in the same script, you just call it, like @Kurt-Dekker showed. If it’s on another script, you need a reference to an instance of that script to call it like so:

// Attach this script to some object
public class MyOtherScript : MonoBehavior {

  public void MyMethod() {
    // random code
  }
}
// Attach this script to some other object (or even the same one!)
public class MyScript : MonoBehavior {
  public MyOtherScript myOtherScriptInstance; // << Drag and drop the object containing the other script here in the inspector in Unity Editor

  void Start() {
    // This part calls the method
    myOtherScriptInstance.MyMethod();
  }
}

@Kurt-Dekker Thats what I have been trying… It’s giving me an error. I will send you my code.

    using System.Collections;
    using System.Collections.Generic;
    using System.Numerics;
    using UnityEngine;
    using Vector3 = UnityEngine.Vector3;
    
    public class PickUp1 : MonoBehaviour
    {
    
        public static bool IngredientCollected1 = false;
    
    
    
    
    
        void Update()
        {
            RaycastHit hit;
    
            if (Input.GetKeyDown("e"))
            {
                if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit))
                {
                    Debug.Log("Raycast Hit!");
                    if (hit.transform.CompareTag("Selectable")) Debug.Log("Object is selectable");
                    {
                        Debug.Log("If statement successful");
                        PickUpFunction();
                    }
                }
            }
        }
        
            public void PickUpFunction()
        {
    
            GetComponent<Rigidbody>().useGravity = false;
            IngredientCollected1 = true;
            gameObject.transform.Translate(0, 1000, 0);
        }
    }

The error is on line 28.

I’m sure there’s more to the story than that.

What error
what line

etc

Also, when you see line 34 indented like that, that MIGHT be a problem with your parentheses mismatching or your braces, or both.

I think you have an extra closing parenthesis here:

                if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit))

Also this seems problematic:

                    if (hit.transform.CompareTag("Selectable")) Debug.Log("Object is selectable");

You probably want to put that Debug.Log inside the brackets for the if statement. Right now the Debug.Log is the only conditional code and everything after it will run no matter what.

1 Like

If you look in the code on line 27 I did put a debug.log and it never ran.

It’s weird that it indented like that. In the actual script it isn’t.

Humor me. I mispoke, I meant that it will always run as long as the line right before it runs. As in, it’s not conditional on the if statement on line 25.

Oh ok makes sense.

@PraetorBlue @Kurt-Dekker sorry about that… the code I sent you was from another forum post… Here is the current code.

using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using UnityEngine;
using Vector3 = UnityEngine.Vector3;

public class PickUp1 : MonoBehaviour
{

    public static bool IngredientCollected1 = false;





    void Update()
    {
        RaycastHit hit;

        if (Input.GetKeyDown("e"))
        {
            if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit))   
            {
                Debug.Log("Raycast Hit!");
                if (hit.transform.CompareTag("Selectable")) Debug.Log("Object is selectable");
                {
                    Debug.Log("If statement successful");
                    PickUpFunction();
                }
            }
        }
    }
       
        public void PickUpFunction(Transform targ)
    {

        var rb = targ.GetComponent<Rigidbody>();
        if (rb != null) rb.useGravity = false;
        IngredientCollected1 = true;
        gameObject.transform.Translate(0, 1000, 0);
    }
}

And here is the error on line 28. “There is no argument given that corresponds to the required formal parameter ‘tart’ of ‘PickUp1.PickUpFunction(Transform)’”

The function requires a Transform argument.

Line 28 calls that function WITHOUT giving it a Transform.

Welp I don’t understand what that means how do I give it a transform

The error message here is pretty clear. “PickUpFunction” is expecting an argument of type Transform. You can tell because it has a Transform inside the parentheses where you are declaring it:

PickUpFunction(Transform targ)

But you are calling it without providing any argument:

PickUpFunction();

My best guess is you want to pass in the transform of the thing your raycast hit? So it would look like this:

PickUpFunction(hit.transform);

I assume you’re trying to follow a tutorial. Otherwise, if you don’t understand what arguments are why did you add one to your function declaration?

Thank you so much… I have been trying to get this script to work for days!

See my avatar photo? When I have trouble understanding something I try to explain it to my dog and most of the time I realize where my misunderstanding lies, the dog goes “woof” and gets a treat, and off I go onto the next issue.

Always best to try and find out WHAT you’re doing with each piece of code, not just what magic characters to type. Otherwise you’ll be stuck in weird error mode the rest of your life.

Unfortunately, I don’t know enough about C# and Unity and I am trying my hardest to learn so no matter how many times I say it I don’t know the solution. Hopefully someday I will…

Youtube is far from the ideal learning tool for programming. Just googling ‘How to call a method in C#’ will yield you more than enough reading material to actually understand what you are trying to do.I got this as the first link. Granted, it will take some time to read and even more to understand. Weeks/Months actually to really sink into your brain, but there is no way around it.

It’s insert swear word tedious to learn programming, but that is just how it is. Read all the documentation you can get your hands on and google the another swear word here out of the puzzle pieces you are missing. I can’t even count
the number of times i have to pull out google each day. Also it’s way faster then having to wait for some forum member to answer you.

Familiarize yourself with the keywords, you’ll see there are much less than in any ‘normal’ language.
Can’t be that bad then, ehh…:wink:
Same for the operators, not half as scary as math class :smile:
Those are the most fundamental building blocks you will need to actually understand C# (and other languages to a certain degree).
From there on out, things will become more and more fun, as you will slowly begin to think about what you want to do and less about how you can do it. Just don’t give up :wink: