Is there a way to choose which script/component will be exactly used as parameter of script?

Is there a way to choose which script/component will be exactly used as parameter of script?

For example I have a class ExampleBehaviour which is used twice on the same game object. Next I have class ExampleBehaviour2 which looks something like:

public class ExampleBehaviour2 : MonoBehaviour {
public ExampleBehaviour exampleBehaviour;

// …
}

…and I want exact instance of ExampleBehaviour to be used as parameter exampleBehaviour. I would like to achieve this in inspector, not having dependency in some script.

It looks Unity don’t have this opportunity, just takes first instance of class (component), or something like that.

Hi Elvis.,
Although GetComponent will pick the first component it finds, you can also use GetComponents

If you are trying to hook the reference up via the inspector, you can also drag the component itself into the slot from the inspector.

This can be difficult if the multiple ExampleBehaviour components live on a separate game object than ExampleBehaviour2. In order to do that hookup, you can use the lock functionality in the inspector. In the upper right corner of the inspector, you can click the lock button to lock that inspector window to the current selection. Then, open up another Inspector window, select the other game object, and now you have two inspector windows open with two different selections and you can do the drag from there.

Hope that helps,

  • Beck

Not possible easily I think, no, (Edit: so this is easily possible, based on Beck’s answer) if you really want to achieve this, something like this might work (more from a fun theoretical point of view), a combination of:

So:

  1. Create a custom attribute, such as “SelectiveComponentAttribute” (naming can be improved :wink: )
  2. If you have a GameObject where you want a specific component from, give it the attribute in your code, which would be:
public class ExampleBehaviour2 : MonoBehaviour {
[SelectiveComponentAttribute]
public ExampleBehaviour exampleBehaviour;
}
  1. In the custom inspector, you draw the stuff, and create a PropertyField, next to it, create an IntField. Then in the code, you can call “GetComponents”, and get the component at the index of the intfield value!

Not sure if this would work, but I guess it might?

Edit: Beck’s answer is way easier, mine might be fun just for the sake of it!