【问题标题】:Interacting with objects from different Scenes Unity 5 [duplicate]与来自不同场景的对象交互 Unity 5 [重复]
【发布时间】:2017-07-25 04:01:17
【问题描述】:

下午好!我已经制作了一个主菜单,您可以在其中创建您的 RPG 角色,在这个菜单中,我可以从输入字段/按钮中获取值,这些输入字段/按钮可以从属性等中添加/减去值。所有内容都存储在一个名为 CustomCharacterSheet 的类中,现在这个对象有一个 DontDestroyOnLoad 脚本,允许将其移动到下一个场景,即第一级。

在我的 playerbehavior 类中,我有一个方法,它采用 CustomCharacterSheet 对象并读取其值,然后使用适当的值创建一个字符,问题是当我想使用该方法在 Awake() 上生成字符时在 playerbehavior 中,该方法需要 CustomCharacterSheet 类型的对象才能执行,但是我如何告诉该方法来自主菜单的 CustomCharacterSheet 是必须读取的?我试过 GameObject.Find();但它会告诉我它不能将 GameObject 转换为 CustomCharacterSheet 类。

这是虚拟代码:

CustomCharacterSheetClass {
//Values, this was created into an object in the main menu with a DontDestroyOnLoad() script to be moved into the 1st Scene
}


PlayerBehavior Class {

private void generatePlayer(CustomCharacterSheet cs){
//Do Stuff, this method requires the CCS in order to pull data from it and generate the player
}

void Awake(){
generatePlayer();//This is inside the playerBehavior class and needs to reach the CustomCharacterClass created in the main menu that was later moved to the 1st Scene
}

}

【问题讨论】:

  • 这里的每个人都可以阅读代码。请提供给我们一些
  • 你有虚拟代码。

标签: c# unity3d unity5


【解决方案1】:

GameObject.Find 用于按名称查找某个游戏对象,而不是用于查找脚本。

既然你说脚本附加到一个游戏对象,你需要做的是用该对象的名称调用GameObject.Find("ObjectName"),然后你可以使用GetComponent访问脚本CustomCharacterSheet

public class GetComponentGenericExample : MonoBehaviour
{
    void Start()
    {
        GameObject gObject = GameObject.Find("ObjectName")
        CustomCharacterSheet ccSheet = gObject.GetComponent<CustomCharacterSheet>();
    }
}

GetComponent 允许您访问游戏对象的任何组件。

【讨论】:

  • 非常感谢,早点想通了,但仍然给你一个复选标记以表示帮助!干杯!
  • @CNuts 没有命名变量gameObject,因为当您从MonoBehaviour 继承时已经声明了该变量。你会遇到this等问题。
  • @Programmer 哦,是的,你是对的。我完全忘记了,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
相关资源
最近更新 更多