错误。错误:"NullReferenceException.Object reference not set to an instance of an object 在Unity中,一个对象上有2个脚本,"对象引用未设置为对象的实例"。

问题描述 投票:1回答:1

这有可能是重复的,但我试了又试,可能是简单的东西。

我试图让两个脚本在一个对象上进行交互,我想要一个基本的通用物理脚本来处理我所有对象的所有交互。我想要一个基本的通用物理脚本,它将处理所有对象的所有交互。

脚本1: 脚本2: 脚本3: 脚本4: 脚本5: 脚本6: 脚本7: 脚本8:

// 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();
    }
}

脚本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");
    }
}

编辑:我很确定问题就出在这里。

但我无法改变它来拯救我的生活。

unity3d unityscript
1个回答
1
投票

它应该工作.你确定你有BOTH脚本添加到gameObject?在图像上,我只看到player1,我怀疑物理学是否被添加.在其他地方,你可以使physics_scripts公开或序列化他们(与[SerializeField]),你将能够拖'n'drop在编辑器的脚本到formfield。这样你就可以不用在开始时使用GetComponent<>,如果你不使用它们,记得删除开始和更新方法。

© www.soinside.com 2019 - 2024. All rights reserved.