Acces void method from another script

Hello ladies and gentlemen,

I’m learning basic movement scripts and work on getting my feet wet a bit at the moment, and now I encountered a problem I can not solve on my own. Would you help me out?

Both scripts are attached to the same gameObject (Cube). However, I want to outsource the many different methods and proccessing tasks to other scripts and make my core-script as clean as possible. The movement script works perfectly fine when I put it on Update(), but when i put it into another script and try to access it from my core-script, it doesn’t work. doesn’t put out an error, but just pauses the game. Here is my work:

Movement

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

public class Movement : MonoBehaviour
          
{

   

     public void checkMovement(float speed)
    {
       float GetAxisHor = Input.GetAxis("Horizontal");
       float GetAxisVer = Input.GetAxis("Vertical");


        if (Input.GetButtonDown("Jump"))
        {
            transform.Translate(0, 2, 0);
        }

        if (GetAxisHor != 0)
        {

            transform.Translate((GetAxisHor * speed) * Time.deltaTime, 0, 0);
        }


        if (GetAxisVer != 0)
        {


            transform.Translate(0, 0, (GetAxisVer * speed) * Time.deltaTime);

        }


    }

       

   

}

Core

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

public class CubeCore : MonoBehaviour {


     Movement Movement;

    float GetAxisHor = Input.GetAxis("Horizontal");
    float GetAxisVer = Input.GetAxis("Vertical");

    void Update () {

        Movement.checkMovement(1f);

    }
}

Sounds like your “other script” needs to have a reference to the script your trying to do this method call on. Like if your in another script, and you want to call “checkMovement()” from that script, you would have a reference to it (for simplicity you would drag and drop assign this in the editor) by just using “public Movement _movement;” as the definition in the other script, and call it using “_movement.getMovement();” through the other script.

Alternatively, you could have both script attached to the same gameobject, and have a private reference instead, and use GetComponent() in start or awake to get a reference to the other script.

A third option, probably not a good one, is to make the method static, and it can be called from anywhere without a reference, but this is not really what you should do in this situation I don’t think.

1 Like

Thank you MD_Reptile, it worked! Thank you for taking your time have a nice day!

1 Like

No problem, good luck!