首页 > 解决方案 > C# - 调用另一个脚本失败

问题描述

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

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
        }
    }
}

标签: c#nullreferenceexception

解决方案


It Unity GameObjects can have Components. The method GetComponent<T>() gets a reference to the component T from the current GameObject.

So if your GameObject has both components (ScriptAand ScriptB)

enter image description here

then this will return a "not-null" reference to the instance of ScriptB:

public class ScriptA : MonoBehaviour {

    ScriptB scriptB;

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

If you GameObject does not have the component ScriptB, then the Method GetComponent<T>() will return null.

If ScriptB is a component from another GameObject then you will need a reference to that other GameObject and call it via OtherGamoeObject.GetComponent<T>() If ScriptB is not even a Script that changed the GameObject and simply (for example) contains some Math-Calculations or so, then I would suggest not making it inherit from Monobehaviourand simply creating an instance like so: var scriptB = new ScriptB();


推荐阅读