C# 与来自不同场景的对象交互Unity 5

C# 与来自不同场景的对象交互Unity 5,c#,unity3d,unity5,C#,Unity3d,Unity5,下午好!我制作了一个主菜单,您可以在其中创建RPG角色,在这个菜单中,我可以从输入字段/按钮中获取值,这些字段/按钮可以从属性中添加/删除值,等等。所有内容都存储在一个名为CustomCharacterSheet的类中,现在,这个对象有一个DontDestroyOnLoad脚本,允许它移动到下一个场景,即第一层 在我的playerbehavior类中,我有一个方法,它接受CustomCharacterSheet对象并读取其值,然后使用适当的值创建一个角色,问题是当我想使用该方法在playerbe

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

在我的playerbehavior类中,我有一个方法,它接受CustomCharacterSheet对象并读取其值,然后使用适当的值创建一个角色,问题是当我想使用该方法在playerbehavior中的Awake()上生成角色时,该方法需要CustomCharacterSheet类型的对象才能执行,但如何告诉该方法来自主菜单的CustomCharacterSheet是必须读取的对象?我试过GameObject.Find();但它会告诉我它不能将游戏对象强制转换为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
}

}

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

既然您说脚本已附加到游戏对象,那么您需要做的就是调用
gameObject.Find(“ObjectName”)
和该对象的名称,然后您就可以使用
GetComponent
访问脚本
CustomCharacterSheet

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

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

这里的每个人都可以阅读代码。请向我们提供一些你有虚拟代码的东西。非常感谢,早些时候就弄明白了,但仍然给你一个复选标记,以感谢你的帮助!干杯@CNUT不会命名变量
gameObject
,因为当您从
monobhavior
继承时,已经声明了该变量。你会遇到这样的问题。@程序员哦,是的,你是对的。我完全忘了,谢谢。