Search Unity

onClick disappears at runtime

Discussion in 'Scripting' started by UnityMatt, Mar 28, 2015.

  1. UnityMatt

    UnityMatt

    Joined:
    Mar 7, 2015
    Posts:
    13
    When I instantiate a button not using the inspector the onClick that I assigned disappears.

    I have looked at prior posts but cannot figure this out.

    Code (CSharp):
    1. GameObject go = (GameObject)Instantiate(prefab)
    makes my buttons through iteration.

    So how can I add an onClick creating them via script?

    Thanks
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    You can add a listener to the onClick event through script by calling button.onClick.AddListener().

    However, I'm pretty sure that if you have any listeners set in the inspector, they should carry over when you clone the object with the Instantiate method. Are you absolutely sure you have configured the onClick of the same object you're instantiating?
     
  3. UnityMatt

    UnityMatt

    Joined:
    Mar 7, 2015
    Posts:
    13
    I just checked again. Whenever I make the object a prefab the onclick disappears and it won't let me add it to the prefab.
     
  4. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    Prefabs can include references to other parts of the same prefab, but not to objects in your scene, because they're not associated with a specific scene.

    You can solve this problem by cloning an object in your scene (possibly a disabled one, so it won't show up or affect anything) instead of a prefab...or you can set up your listeners from code after instantiation.
     
  5. UnityMatt

    UnityMatt

    Joined:
    Mar 7, 2015
    Posts:
    13
    Thanks,

    I made another prefab and it doesn't show up in window. Just a box outline with some red lines in it.
    And the box isn't even the size of he prefab.
    Any ideas?