unity3d 我不能分配我的游戏对象变量,请协助

weylhg0b  于 2023-04-07  发布在  其他
关注(0)|答案(3)|浏览(205)

我试图将ScriptManager分配给ObjectManager,并使用了以下行:

ObjectManager = GameObject.Find("ScriptManager");

我已经检查了多次,以确保“ScriptManager”拼写正确,我甚至尝试直接从Unity复制粘贴名称。
我在运行时收到此错误:
“UnassignedReferenceException:尚未分配采矿的变量ObjectManager。您可能需要在检查器中分配采矿脚本的ObjectManager变量。UnityEngine.GameObject.GetComponent[T]()(at<3be1a7ff939c43f181c0a10b5a0189ac>:0)Mining.Sell()(at Assets/Mining.cs:49)”
遗憾的是,我不能直接从检查器中分配变量,因为带有代码的对象是使用Prefab加载的。
下面是完整的代码:

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);
}
}
9w11ddsr

9w11ddsr1#

我会改变你如何分配ScriptManager到ObjectManager的方式。函数Find()不是很可靠,如果层次结构或游戏对象名称发生变化,该函数将无法找到所需的游戏对象。
有多种方法可以将游戏对象分配给ObjectManager,包括更可靠的函数FindObjectOfType(),或者简单地创建变量:
public GameObject;
并将您的ObjectManager从层次结构中拖动到ScriptManager GameObject中的检查器中。
注意:如果你想使用ObjectManager的任何函数,你需要在ScriptManager的Start函数中获取该组件。

hmae6n7t

hmae6n7t3#

我发现了如何修复它!
对于任何人想知道,该对象的攻击是一个预制件。只有当玩家购买的项目加载。这意味着它是不加载时开始()被执行。将该行移动到Sell(),添加(),并在单击按钮时remove分配它。这修复了错误。感谢所有试图帮助的人,我现在也在使用FindGameOBjectWithTag而不是Find来确保它总是工作

相关问题