how to go from one scene to another scene by gazing an object in unity?

1.5k Views Asked by At

I am developing an application using Unity where I have created two Scene's.if the user gazes at an object in Scene 1 it should go to Scene 2. I have the code below, but I get errors.

SOURCE CODE:-

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class time : MonoBehaviour {

    public float gazeTime = 2f;

    private float timer;

    private bool gazedAt;


    // Use this for initialization
    void Start () {

    }
    void update(){
        if (gazedAt)
        {
            timer += Time.deltaTime;

            if (timer >= gazeTime)
            {

                Application.LoadLevel (scenetochangeto);

                timer = 0f;
            }

        }

    }
    public void ss(string scenetochangeto)
    {
        gameObject.SetActive (true);
    }

    public void pointerenter()
    {



        //Debug.Log("pointer enter");
        gazedAt = true;
    }

    public void pointerexit()
    {
        //Debug.Log("pointer exit");
        gazedAt = false;
    }
    public void pointerdown()
    {
        Debug.Log("pointer down");
    }
}
2

There are 2 best solutions below

6
Mukesh Saini On BEST ANSWER

You should initialize your variables with proper values and use scene manager to load new scene as follows -

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.EventSystems;

public class time : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {

    public float gazeTime = 2f;
    private float timer = 0f;
    private bool gazedAt = false;

    // Use this for initialization
    void Start () {

    }
    void Update(){
        if (gazedAt)
        {
            timer += Time.deltaTime;
            if (timer >= gazeTime)
            {
                SceneManager.LoadScene("OtherSceneName");
                timer = 0f;
            }
        }
    }
    public void ss(string scenetochangeto)
    {
        gameObject.SetActive (true);
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        //Debug.Log("pointer enter");
        gazedAt = true;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        //Debug.Log("pointer exit");
        gazedAt = false;
    }
}

Change the "OtherSceneName" with name of the scene you need to load (scenetochangeto).

0
Andrea On

You didn't specified the errors you got, but pay attention: Update() is a "special" function of the Unity engine, and needs the capital U. It will never work as it is now.