我想在Unity中创建一个简单的移动应用,让用户选择一个相框,然后用它做一些事情。
因此,我在scene1中有一个预制件(相框)列表。在应用启动时向用户显示该场景。
一旦用户触摸这些框架之一,他就会被引用到场景2。这是我的代码,用于确定触摸了哪些帧:FrameSelection.cs
附加到FrameList
gameObject。
void Update()
{
if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began)
{
Touch touch = Input.touches[0];
Ray ray = Camera.main.ScreenPointToRay(touch.position);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.Log(hit.transform.name);
if (frameList.Contains(hit.transform.gameObject))
{
//Switch scene
}
}
}
但是如何将选定的预制件从场景1传递到场景2?我希望仅在场景2中实例化预制件,具体取决于场景1中选定的预制件。
在scene2中,我有一个脚本,当用户触摸屏幕时会实例化对象:ObjectSpawner.cs
void Update()
{
if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began)
{
Touch touch = Input.touches[0];
Ray ray = Camera.main.ScreenPointToRay(touch.position);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
placedObject = Instantiate(objectToSpawn, hitObject.point,hitObject.transform.rotation);
...
我试图通过在DontDestroyOnLoad
脚本中使用FrameSelection.cs
来避免在场景切换时造成破坏,但是在加载scene2时仍然获得了MissingReferenceException
。
void Awake()
{
DontDestroyOnLoad(transform.gameObject);
}
我很乐意提供帮助!
答案 0 :(得分:1)
另一个选择是使用脚本对象。它们是精巧的小数据容器,可用于存储复杂的对象。该数据独立于场景和类而持久。它们不涉及很多额外的代码,而Unity开发人员则需要熟悉它们,因为它们确实使您摆脱了在尝试编码持久性数据时可能遇到的一些讨厌的漏洞。
答案 1 :(得分:0)
我想得太多了,可以通过实现我附加到frameList的单例模式来解决它。因此,选定的帧通过场景切换保持不变。还是谢谢@whathm