Jadon Erwin
Jadon Erwin

Reputation: 661

Error: "NullReferenceException: Object reference not set to an instance of an object" for 2 scripts on one object in Unity

There is a chance this is a duplicate, but I have tried and tried to get this to work and it's probably something simple.

I'm trying to get two scripts to interact on one object. I would like a basic generic physics script that will handle all the interactions for all my objects.

Script 1:

// Simple Player1

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


public class Player1 : MonoBehaviour
{
    Physics physics_script;

    void Start(){
        physics_script = gameObject.GetComponent<Physics>();
    }

    // Update is called once per frame
    void Update() {
        physics_script.helloWorldFromAnotherScript();
    }
}

Script 2:

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

public class Physics : MonoBehaviour
{
    void Start(){
    }

    void Update() {   
    }

    public void helloWorldFromAnotherScript()
    {
        Debug.Log("Hello world from player");
    }
}

Edit: I'm pretty sure the problem is here:

But I can't change it to save my life.

Upvotes: 1

Views: 132

Answers (1)

Rub&#233;n Cant&#243;n
Rub&#233;n Cant&#243;n

Reputation: 124

It should work. Are you sure you have BOTH scripts added to the gameObject? At the image I only see player1, and I doubt if Physics it's added. Elsewhere you can make physics_scripts public or serialize them(with [SerializeField]) and you will be able to drag'n'drop at the editor the script to the formfield. Thats allows you to not use the GetComponent<> at start. Remember to delete start and update methods if you dont use them.

Upvotes: 1

Related Questions