ItsDamu
ItsDamu

Reputation: 11

How to Call On an OnClick Button in Another Script?

so I'm trying to call on my "play" button from my main menu so that when i hit my play button it then plays my loading screen transition into the next scene. So far this is what my script looks like using the mousebuttondown instead of calling on my OnClick button as I'm not sure what to write in order to call on it so im using this for now.

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

public class Transition : MonoBehaviour
{

    public Animator transition;

    public float transitionTime = 4f;

    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            LoadNextLevel();
        }
    }

    public void LoadNextLevel()
    {
        StartCoroutine(LoadLevel(SceneManager.GetActiveScene().buildIndex + 1));
    }

    IEnumerator LoadLevel(int levelIndex)
    {
        transition.SetTrigger("Start");

        yield return new WaitForSeconds(transitionTime);

        SceneManager.LoadScene(levelIndex);
    }
}

And heres the script im trying to reference from

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

public class MainMenu : MonoBehaviour
{
    public void PlayGame ()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
    }  

    public void QuitGame ()
    {
        Debug.Log("QUIT");
        Application.Quit();
    }
      
}

Thanks in advance!!

Upvotes: 0

Views: 673

Answers (1)

uchar
uchar

Reputation: 2590

Pass LoadNextLevel function to your button from here :

enter image description here

You can also do it from script with something like this :

private void Start(){
  yourButtonGameObject.GetComponent<Button>().onClick.AddListener(() =>
  {
     // Load your next scene
  });
}

Upvotes: 0

Related Questions