[Partially Solved] Check from which object the script is being called from.

Updated on June 7, 2017 in [A] Other Answers
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
8 on June 7, 2017

Let’s say I have a button with an onClick event. The onClick event is calling a method from another script and it has one parameter. Is there a way to find which object is calling the method?

  • Liked by
Reply
6 on June 7, 2017

No. (There might be a hacky way using the stacktrace, but that’s just bad design)
Are you already using that parameter?
If not, you can ask the gameobject as a caller.

Wise
on June 7, 2017

That’s the thing, I am using the only parameter already. Maybe create a helper class like TwoParameters which hold parameter one and parameter two. Then in the onClick event I can pass the helper class TwoParameters.

Guru
on June 7, 2017

You won’t be able to pass a class in the inspector unless it’s a component.

What I do is to create a method for every button I have. Then that method calls all the things I want.

 

Wise
on June 7, 2017

That would literally be copy pasting, and I will probably change the parameters.

 

Wise
on June 7, 2017

And it would be a helper class but still a monobehaviour I would put on that object.

 

Guru
on June 7, 2017

That should work

 

Wise
on June 7, 2017

And I can use the Object type and an array so I can use it in different scenarios if that happens. I can put multiple number of elements and different data types.

 

Show more replies
  • Liked by
Reply
Cancel
0 on June 7, 2017

I know this isn’t a solution to this problem but it’s a solution to my use case:

In the end I just needed to accept to parameters in the onClick event which I did by using a helper class which is a MonoBehaviour and can be attached to gameObjects as a component.

MultipleParameters:

using UnityEngine;
public class MultipleParameters : MonoBehaviour
{
    public Object [] parameters;
}

You can specify the number of parameters and the type it accepts can be any Unity type. (You can of course switch it to maybe accept only primitive types such as int, float, string…)

 

In the method I actually use it from:

public void OpenMenu (MultipleParameters menus)
{
    // Hide the current menu
    GameObject menuFrom = (GameObject) menus.parameters [0];
    menuFrom.SetActive (false);
    // Show the next menu
    GameObject menuTo = (GameObject) menus.parameters [1];
    menuTo.SetActive (true);
}

And how it looks in the inspector:

  • Liked by
Reply
Cancel