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. Dismiss Notice

Question Is it possible to attach a script to a button using only code?

Discussion in 'Editor & General Support' started by IIBearWithII, Jun 18, 2023.

  1. IIBearWithII

    IIBearWithII

    Joined:
    Feb 15, 2023
    Posts:
    87
    For a UGUI button, instead of selecting the script and the method in the inspector, can I set those elements off the button using a script instead? And if so, how?
     
  2. Rin-Dev

    Rin-Dev

    Joined:
    Jun 24, 2014
    Posts:
    552
  3. IIBearWithII

    IIBearWithII

    Joined:
    Feb 15, 2023
    Posts:
    87
  4. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    1,834
    As @Rin-Dev says, you probably want to use the event approach. However, for completeness, yes, you can "attach a script to a button" (more accurately, attach a component implemented by a script) with
    AddComponent<MyComponentScriptName>()
    .
     
  5. IIBearWithII

    IIBearWithII

    Joined:
    Feb 15, 2023
    Posts:
    87
    Ok, thanks!