首页 > 解决方案 > 无法在 Unity 中正确使用其他脚本中的变量

问题描述

我有以下问题,所以我不能使用其他脚本的变量。在我的游戏中有难度选择屏幕,当用户选择它的级别时,它应该为变量提供适当的值。脚本如下所示:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class DifManager : MonoBehaviour
{
public float dif;

public void easy()
{
    dif = 1.05f;
    SceneManager.LoadScene("matchlenght");
}

public void normal()
{
    dif = 1.15f;
    SceneManager.LoadScene("matchlenght");
}

public void hard()
{
    dif = 1.4f;
    SceneManager.LoadScene("matchlenght");
}
}

在游戏场景的另一个脚本中,我想使用 dif 变量来设置 DifficultyMultiplier,它看起来像这样:

using UnityEngine;

public class Ball2 : MonoBehaviour
{

private matchlength mlength;
public float difficultMultiplier;
public float minXspeed = 0.8f;
public float maxXspeed = 1.2f;

public float minYspeed = 0.8f;
public float maxYspeed = 1.2f;
public DifManager d;
private Rigidbody2D ballRigidbody;
private GameObject secondPaddle;

// Start is called before the first frame update
void Start()
{
    d = gameObject.GetComponent<DifManager>();
    secondPaddle = GameObject.Find("Paddle2");
    difficultMultiplier = d.dif;
    mlength = gameObject.GetComponent<matchlength>();
    ballRigidbody = GetComponent<Rigidbody2D>();
    ballRigidbody.velocity = new Vector2(Random.Range(minXspeed, maxXspeed) * (Random.value > 0.5f ? 
     -1 : 1), Random.Range(minYspeed, maxYspeed) * (Random.value > 0.5f ? -1 : 1));
    
}

我仍然收到关于 Null 引用的错误,所以我认为获得正确值是有问题的。我究竟做错了什么?请帮我。

标签: variablesscripting

解决方案


我已经复制了这两个类,一切正常,所以问题是由另一个变量引起的,或者,

这两个类在同一个游戏对象中吗?这是我发现导致此异常的唯一方法...如果是这样,

使用此行获取“DifManager”

d =  GameObject.Find("yourGameObject").GetComponent<DifManager>();

或者

Public GameObject s // the game object have "DifManager" class

 d = s.GetComponent<DifManager>();

如果不,

尝试调试您的代码...

看看异常指的是哪里?

Ball2.Start () (at Assets/Scripts/Ball2.cs:23)

编辑:

如评论中所示,问题是不同场景中的 2 个类,因此GameObject.Findpublic GameObject将给出 null

要解决此问题,请使用PlayerPrefs

而不是 为所有状态dif = 1.05f添加PlayerPrefs.SetFloat("dif", 1.05f);dif

而不是difficultMultiplier = d.dif;添加difficultMultiplier = PlayerPrefs.GetFloat("dif");

并删除“d”


推荐阅读