How to delegate events from one GameObject to another?

I have a CharacterController and a script that implements OnTriggerStay. When I attach the script to the CharacterController everything works as expected.

However I would like to keep the script somewhere else and still be able to react on events from CharacterController. In my particular example, I have an Inventory prefab which has the script attached and I would like just to drag the inventory prefab and add it to my player object and have everything wired automatically. Currently I do as follows:

private var target : GameObject;
target = transform.root.gameObject.FindWithTag("Player").GetComponentInChildren(CharacterController).gameObject;

// Avoid The Infinite Loop
if (!target.GetComponent.<InventoryController>()) {
  target.AddComponent(InventoryController);
}

and the structure of GameObjects is like this:

Player
  First Person Controller
  Inventory

Is there a better way to do this? Or maybe I shouldn’t do it and just attach the InventoryController to the CharacterController?

1 Answer

1

It looks a little like your asking if you can have a gameObject with a charController and 2 scripts (inventory, movement.) Sure you can. Or, answer#2:

The object with the component is always going to be the one to detect it. So, you can’t put OnTriggerStay anywhere except in a script on the gameObject with the charController component (well, in the thing you’re touching, but not somewhere else listening to you.)

But, you can no problem have On** call out to anywhere (the cool kids way, where you make a link 1st):

InventoryController IC; // link to main inventory script
// establish link to inventory on some empty:
Start() { IC = GO.Find("InventoryGO").GetComponent<InventoryController>(); };

OnTrigger*(...) {  IC.doSomeCheck(transform, thingIHit); }

After a few days more with Unity, I realized that I don't need to delegate events at all. I simply should add a collider to the Inventory game object so it emits events directly to my script. I think this is the correct way of adding functionality to game objects: attach a child game object and add some scripts to it. This way I can also make a prefab from the Inventory along with scripts to use later on other game objects.

Often the inventory script would reuse previously setup player colliders. I believe 2 OnCollisions (on two scripts) will trigger (but I think colliders may not count coming "down" from a parent.) But let's say you don't pick up objects if you're hurled through them. So you might want the player to handle all collisions/clicks and call "Inven.AddItem("fish");" as needed. It still might make sense to add the Inventory script/object to the player -- since it belongs to you.