c# - 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
}
}
}
解决方案
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 (ScriptA
and ScriptB
)
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 Monobehaviour
and simply creating an instance like so: var scriptB = new ScriptB();
推荐阅读
- python - 如何删除第一次出现的字母?
- javascript - 折叠和展开 div 而不出现滚动条
- javascript - 在 React 和 JSX 中使用状态值对数组进行排序
- webrtc - WebRtc,onaddstream,接收,流,不显示?
- node.js - 在生产服务中构建 Vue.js
- python - python3运行旧版脚本
- azure-active-directory - Microsoft Graph API 调用 /me 端点失败并出现错误:compactToken 80049217
- python - 如何使用这个“|”转换数据 pandas 中用于推荐系统的符号
- android - 异步执行任务时阻塞Android上的主线程
- javascript - 通过提交将文本输入到超链接