Nullreferenceexception: Object Reference not set to an instance of an Object gameController.Update Unity 2D

Asked

Viewed 8 times

0

I’m starting to develop games now, and I was trying to make a system for when the player was at a certain distance from the object and pressed space the object moved in the direction the player was looking, but I’m getting the following error: Nullreferenceexception: Object Reference not set to an instance of an Object gameController.Update() (at Assets/Scripts/gameController.Cs:23)

I tried everything but I could not solve, follow the classes

public class gameController : MonoBehaviour
{
    public static playerController player;
    public static movables movables;
    public static Vector2 direction;

    // Start is called before the first frame update
    void Start()
    {
        player = GetComponent<playerController>();
        movables = GetComponent<movables>();
       
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space)){
            if(movables.distance <= 0.20)
                movables.move();
        }
    }

}
public  class movables : gameController
{
    //Variáveis
    static Rigidbody2D rgbd2d;
    [SerializeField] public static float speed = 0.0f;
    

    private GameObject playerObj;
    private GameObject obj;
    public float distance;
    
    Vector2 d1,d2;

    void Start()
    {
        rgbd2d = GetComponent<Rigidbody2D>();
        playerObj = GameObject.FindGameObjectWithTag("Player");
        obj = GameObject.FindGameObjectWithTag("Object");

    }
    // Update is called once per frame
    void Update()
    {
       distance = distanceToPlayer();
    }

    public void move()
    {
        rgbd2d.velocity = gameController.direction * speed * 10;
    }

    public float distanceToPlayer()
    {
        if(playerObj != null){
            d1 = new Vector2(playerObj.transform.position.x, playerObj.transform.position.y);
            Debug.Log(d1);
            d2 = new Vector2(obj.transform.position.x, obj.transform.position.y); 
        }
        return Vector2.Distance(d1, d2);
    }
}

I’d appreciate it if someone would help me.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.