[英]Unable to get variables from script in other game object
我试图生成6个随机整数,然后将它们分配给6个不同的对象,但是我发现,简单地在对象内生成整数会导致每个数字都相同,因为它们都在相同的时间加载。 要变通解决此问题,我试图连续生成6,以便时钟时序不同并给出不同的数字。 我试图弄清楚如何访问这6个变量。
我已经尝试过使用'GetComponent <>()'和'GameObject.Find(“”)'一起使用多种不同格式,并将生成的脚本存储在单行为变量中(我认为这可能使我困惑),然后尝试通过将脚本存储在其中的变量访问数字。但是,当我这样做时,Unity表示脚本中没有数字变量(在我的情况下为Num1,Num2等)。
这就是我所拥有的,在验证变量生成有效的前提下,我只会显示试图获取变量的代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class NumberButton : MonoBehaviour
{
public int Num;
public GameObject Game;
void Start()
{
MonoBehaviour Game = GameObject.Find("Game").GetComponent<GameInit>();
print(Game.name);
if (gameObject.name == "Button1")
{
Num = Game.Num1;
}
else if (gameObject.name == "Button2")
{
Num = Game.Num2;
}
//There are 4 more of these, 1 for each button, I realize this is terrible code etiquette.
GetComponent<TextMesh>().text = Num.ToString();
}
}
如果可行,应该根据按钮的名称为每个按钮分配变量,以便Button1从存储在GamObject“游戏”中的GameInit脚本中获取Num1。 实际上,没有从GameInit抓取任何东西,尽管GameInit中的变量不为0,但抓取器对象中的所有Num变量都等于0。
编辑
抱歉,我误解了您的问题所在。 编译器告诉您,这些变量在MonoBehaviour对象中不存在,因为MonoBehaviour没有这些变量。
你需要改变
MonoBehaviour Game = GameObject.Find("Game").GetComponent<GameInit>();
至
GameInit Game = GameObject.Find("Game").GetComponent<GameInit>();
原版的
由于声望低,我目前无法发表评论,因此我将以其作为答复。
首先,GameInit.Start()中是否发生数字生成? 如果是这样,则有可能在GameInit.Start()之前调用了Start()按钮,因此所有变量在访问时均为默认值0。 为确保不是这种情况,请将数字生成代码放在GameInit.Awake()中。
另外,为确保MonoBehaviour对象没有发生轨迹,请尝试以下操作:
...
if (gameObject.name == "Button1")
{
Num = GameObject.Find("Game").GetComponent<GameInit>().Num1;
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.