Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How a button works

Discussion in 'Scripting' started by Pekmii, Aug 1, 2021.

  1. Pekmii

    Pekmii

    Joined:
    Jul 31, 2021
    Posts:
    11
    Hi
    I'm just starting out and so ask these kind of ridiculous questions x)
    I am in a 3D game, and I am using a menu to move from level to level but I cannot get the buttons to work.
    Here is the code, I put it in the button and it's supposed to switch cameras and teleport (to tutoTarget) the player when clicked.
    I also saw that it was necessary to select a function in the On Click () of the button, but no new function is displayed

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. public class MenuAct : MonoBehaviour
    6. {
    7.     public Transform tutoTarget;
    8.     public GameObject Player;
    9.     public GameObject PlayerCamera;
    10.     public GameObject MenuCamera;
    11.     public GameObject TutorielStart;
    12.         void Start()
    13.         {
    14.             PlayerCamera.SetActive(false);
    15.             MenuCamera.SetActive(true);
    16.             Debug.Log("Started");
    17.         }
    18.         void OnClick()
    19.         {
    20.             Player.transform.position = tutoTarget.transform.position;
    21.             PlayerCamera.SetActive(true);
    22.             MenuCamera.SetActive(false);
    23.             Debug.Log("Click");
    24.         }
    25. }

    I think I forgot to specify other things, sorry x)
    thank you
     
  2. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,890
    There are a couple of ways.

    The easiest is to select the button in the inspector, look inside the Button component for the On Click at the bottom, then add the function you want to call, by click-dragging your GameObject that has MenuAct on it and selcting the function from the drop-down. It has to be "public void..." to show up in the list.

    The second way is to do it using code. In your MenuAct script add a
    public Button ButtonName;
    , then in the Start function add
    ButtonName.onClick.AddListener(OnClick);
    . Remember to assign the button in the inspector.
     
    Pekmii likes this.
  3. Pekmii

    Pekmii

    Joined:
    Jul 31, 2021
    Posts:
    11
    I wrote "void ..." instead of "public void ..."
    Now it works!
    thanks a lot