【发布时间】:2022-06-29 22:44:43
【问题描述】:
我正在尝试将 ScriptManager 分配给 ObjectManager,并使用以下行:
ObjectManager = GameObject.Find("ScriptManager");
我已多次检查以确保“ScriptManager”的拼写正确,我什至尝试直接从 Unity 复制粘贴名称。
我在运行时收到此错误:
"UnassignedReferenceException: Mining 的变量 ObjectManager 没有被赋值。 您可能需要在检查器中分配 Mining 脚本的 ObjectManager 变量。 UnityEngine.GameObject.GetComponent[T] () (在 :0) Mining.Sell () (at Assets/Mining.cs:49)"
很遗憾,我不能直接从检查器分配变量,因为附加代码的对象是使用预制件加载的。
这里是完整的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Mining : MonoBehaviour
{
public GameObject ObjectManager;
public Text WorkerCountText;
public float MiningSpeed;
public float WorkersInMine;
public float MiningMultiplyer;
public Collider2D collider;
public GameObject DropDown;
private float WorkerCount;
private float MineWorth;
private float Cash;
// Start is called before the first frame update
void Start()
{
ObjectManager = GameObject.Find("ScriptManager");
collider = GetComponent<Collider2D>();
DropDown.SetActive(false);
}
// Update is called once per frame
void Update()
{
Cash = ObjectManager.GetComponent<GenerateItems>().Money;
WorkerCount = ObjectManager.GetComponent<GenerateItems>().Workers;
MineWorth = ObjectManager.GetComponent<GenerateItems>().MineCost;
WorkerCountText.text = "Workers:" + WorkerCount;
}
public void Sell()
{
ObjectManager.GetComponent<GenerateItems>().Money = Cash + MineWorth;
Object.Destroy (this);
}
}
【问题讨论】: