Search Unity

Question Help with level loader script

Discussion in 'Scripting' started by wohoyefe, Sep 10, 2021.

  1. wohoyefe

    wohoyefe

    Joined:
    Apr 25, 2020
    Posts:
    16
    Hi everyone, I've been trying to build a script that shows a loading screen and bar whilst loading a level. I followed a few different tutorials on Youtube but none of them worked except for the one posted below. This script works when adding it to an empty gameobject and then adding an on-click-event to a button in my UI where I link the gameobject and define the number of the level to be loaded under LoadingScreenControl.LoadScreenExample (see picture). This works like a charm where as none of the other scripts I found did (even the one in Brackey's video).

    I now would like to make this same script work when my player touches a hitbox to load the next level instead of having it attached to a UI button that needs to be pressed. I know that there has to be an ontriggerenter somewhere in there to make this happen, but I don't know how to make it work, because I can't add a trigger event on the hitbox the way I can add an on-click-event to a button.

    If anyone could help me scripting an ontriggerevent into this script I would really appreciate. If it's possible, it would also be nice if the level to be loaded wouldn't have to be defined manually, but that Unity instead would just load the next one in the SceneManager. But this is the smaller issue.

    Thank you so very much

    Code (CSharp):
    1. using System.Collections;
    2. using UnityEngine;
    3.  
    4. using UnityEngine.UI;
    5. using UnityEngine.SceneManagement;
    6.  
    7. public class LoadingScreenControl : MonoBehaviour{
    8.    
    9.     public GameObject loadingScreenObj;
    10.     public Slider slider;
    11.    
    12.     AsyncOperation async;
    13.    
    14.     public void LoadScreenExample(int LVL)
    15.         {
    16.             StartCoroutine(LoadingScreen(LVL));
    17.         }
    18.  
    19.     IEnumerator LoadingScreen(int lvl)
    20.     {
    21.         loadingScreenObj.SetActive(true);
    22.         async = SceneManager.LoadSceneAsync(lvl);
    23.         async.allowSceneActivation = false;
    24.        
    25.         while (async.isDone == false)
    26.         {
    27.             slider.value = async.progress;
    28.             if (async.progress == 0.9f)
    29.         {
    30.             slider.value = 1f;
    31.             async.allowSceneActivation = true;
    32.         }
    33.         yield return null;
    34.     }
    35.  
    36. }
    37. }
     

    Attached Files:

  2. Pixelith

    Pixelith

    Joined:
    Jun 24, 2014
    Posts:
    580
    On another script make it reference the loader, use On Trigger Enter, and call the scene loader.