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?
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.
– ncrOften 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.
– Owen-Reynolds