通过脚本传递数据

时间:2019-05-05 21:28:34

标签: c# unity3d

我想在SendScript中使用函数“ example_func”,但出现此问题:

  

NullReferenceException:对象引用未设置为的实例   对象SendScript.Menu_Action_GoToArtists(System.String sceneName)   (在Assets / Scenes / SendScript.cs:23)

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

public class SendScript : MonoBehaviour 
{
    private ReceiveScript receiveScript;

    public void Start () 
    {
        receiveScript = FindObjectOfType<ReceiveScript>();
    }

    public void Menu_Action_GoToArtists(string sceneName)
    {
        receiveScript.example_func();
    }
}    

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

public class ReceiveScript : MonoBehaviour 
{
    public void example_func()
    {
        print("It works");
    }
}

1 个答案:

答案 0 :(得分:0)

有些事情可能会出错并导致此问题:

1)您的ReceiveScript组件未设置为世界上任何对象(最有可能的情况)

2)开始调用未找到ReceiveScript(请参阅1) 您可以通过在“开始”中进行以下操作轻松检查:

public void Start () 
{
    if(receiveScript = FindObjectOfType<ReceiveScript>())
    {
        Debug.Log("Found Script!");
        return;
    }
    Debug.Log("Didn't find script!");
}

尝试一下,看看会说什么。