简体   繁体   中英

Unity - How can i transfer an object from scene1 and instantiate it in scene2?

I want to create a simple mobile app in Unity which lets the user select a picture frame and then do some stuff with it.

So, i have a list of prefabs (Picture Frames) in scene1. This scene is shown to the user on app-start.

在此处输入图像描述

Example Picture of how it would look in my app: 在此处输入图像描述

Once the user touches on one of these frames, he gets refered to scene2. This is my code that determines which frames was touched: FrameSelection.cs is attached to 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
                }
            }
        }

But how can i pass the selected prefab from scene1 to scene2? I want the prefab only instantiated in scene2 depending on the selected prefab in scene1.

In scene2 i have a script that instantiates objects when the user touches on the screen: 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);
...

I tried to avoid destroy on scene switch by using DontDestroyOnLoad in my FrameSelection.cs script but im still getting a MissingReferenceException when scene2 is loaded.

    void Awake() 
    {
        DontDestroyOnLoad(transform.gameObject);
    }

I would be happy for any help!

Another option is to use Scriptable Objects. They are neat little data containers that can be used to store complex objects. This data persists independently of scenes and classes. They don't involve a lot of extra code and are something that Unity developers need to be familiar with because they do get you out of some nasty holes you can run into when trying to code for persistent data.

Architect your code with Scriptable Objects

I was overthinking this and i could solve it by implementing the singleton pattern which i attached to the frameList. So the selected frame keeps persistent through scene switches. Still thank @whathm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM