How can I pass data between two levels?

本文介绍了一种通过公共变量、DontDestroyOnLoad、GameObject.Find和GameObject.GetComponent来实现跨场景信息传递的方法,包括使用代码示例进行详细说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问:

How do I pass information from my existing level to a new level that I'm about to load?


回答1:

The way I approach this is by taking any properties that need to be accessed from more than one scene and making them public variables in a script that is added to an empty GameObject and then I call Object.DontDestroyOnLoad on that object so it will persist through scene changes. Then it's a simple matter of using GameObject.Find to get thatGameObject from a script in the new scene and GameObject.GetComponent to get the script. Then you can access the public variables of a persistent object from any script.

P.S. - GameObject.Find is fast but there's no need to call it every frame. To reference the persistent object script from another script, do something like this:

SomeObjectInTheNewSceneScript.js (pick a better name)

// if your persistent script is named `PersistenScript.js`
private persistentScript : PersistentScript;

function Start () {
    // Start runs once early on and makes the connection to the other script
    // so you don't have to do it every frame.

    // if your persistent game object is named `Persistent Object`
    var persistentGameObject : GameObject = GameObject.Find("Persistent Object");
    persistentScript = persistentGameObject.GetComponent(PersistentScript);
}

then you can set/get properties of persistentScript anywhere else in SomeObjectInTheNewSceneScript


回答2:

DontDestroyOnLoad, static, PlayerPrefs to hold variables between scenes.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值