C#-调用另一个脚本失败

时间:2019-02-20 06:55:43

标签: c# nullreferenceexception

我创建了两个脚本。一个包括变量和方法。第二个脚本的任务是调用第一个脚本并访问其组件。但是我收到以下错误:

ThisScriptWillCallAnotherScript.Update()(在Assets / Scripts / ThisScriptWillCallAnotherScript.cs:21)

我尝试删除它所指的行,但错误仍然存​​在。 知道我做错了什么吗?

脚本1:

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

public class ThisScriptWillBeCalledInAnotherScript : MonoBehaviour {

    public string accessMe = "this variable has been accessed from another script";

    public void AccessThisMethod () {
        Debug.Log ("This method has been accessed from another script.");
    }
}

脚本2:

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

public class ThisScriptWillCallAnotherScript : MonoBehaviour {

    // below we are calling a script and giving a name//
    ThisScriptWillBeCalledInAnotherScript callingAScript;

    void Start () {
        //here we are using GetComponent to access the script//
        callingAScript = GetComponent<ThisScriptWillBeCalledInAnotherScript> ();
        Debug.Log ("Please press enter key...");
    }

    // Update is called once per frame
    void Update () {

        if (Input.GetKeyDown (KeyCode.Return)) {
            Debug.Log ("this is the script we just called " + callingAScript);
            Debug.Log (callingAScript.accessMe); // we are accessing a variable of the script we called
            callingAScript.AccessThisMethod (); // we are calling a method of the script we called
        }
    }
}

1 个答案:

答案 0 :(得分:1)

Unity GameObjects可以具有组件。 方法GetComponent<T>()从当前GameObject获取对组件T的引用。

因此,如果您的GameObject同时具有两个组成部分(ScriptAScriptB

enter image description here

这将返回对ScriptB实例的“非空”引用:

public class ScriptA : MonoBehaviour {

    ScriptB scriptB;

    // Use this for initialization
    void Start () {
        scriptB = GetComponent<ScriptB>(); //Not null if GameObject has ScriptB component.
    }
}

如果您的GameObject没有组件ScriptB,则方法GetComponent<T>()将返回null。

如果ScriptB是另一个GameObject的组件,则您需要引用该另一个GameObject并通过OtherGamoeObject.GetComponent<T>()对其进行调用 如果ScriptB甚至不是更改GameObject的脚本,并且仅仅(例如)包含一些Math-Calculations,那么我建议不要使其继承自Monobehaviour,而只需创建一个实例,例如:{{1 }}