Search Unity

Unity3D Button.OnCllick always calls the first script from 1 object.

Discussion in 'UGUI & TextMesh Pro' started by patrick-noten, Mar 17, 2017.

  1. patrick-noten

    patrick-noten

    Joined:
    Sep 7, 2013
    Posts:
    12
    So basically the issue here is that I have a button with 1 OnClick method linked to a script on TestButtonObject.

    TestButtonObject contains 2 scripts, both of the same type "TestButtonScript" for example.

    TestButtonScript contains 1 method "Get" that returns an integer supplied in the Inspector where both TestButtonScript scripts have a different nr.

    So in my button I have TestButtonScript.Get(), where it is linked to TestButtonObject. For some reason it always calls the first script, is there no way to have a button.OnClick or any other unityevent to differentiate between the script instances?

    It calls the first script even if I drag the 2e script into the button OnClick instead.

    Unity version used is 5.4.1f1.

    Here is an image of the setup:
     
    Last edited: Mar 17, 2017
  2. liortal

    liortal

    Joined:
    Oct 17, 2012
    Posts:
    3,562
    I don't think this is possible. The onClick event persists enough information it needs to later on run the code in the event handler. It probably saves the object's identity, component and method it needs to run.

    According to that info, there's no way to determine which of the 2 components you want to invoke the event on.

    The best thing to do is to work around the issue by placing the TestButtonScript on different gam objects, if possible.
     
  3. patrick-noten

    patrick-noten

    Joined:
    Sep 7, 2013
    Posts:
    12
    After some tinkering with it some more I think this is indeed the only way, thanks!
     
  4. cdarklock

    cdarklock

    Joined:
    Jan 3, 2016
    Posts:
    455
    I messed around with this a little, and I concur. Not sure whether we should consider this a bug or not.
     
  5. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    It doesn't sound like a bug, because it references an instance and when you link it's just taking the first instance of the matching type. Since the OP adjusted his design and is satisfied, I guess there's no need to dig further, but there were probably other ways of implementing the task, too :)