- Home /
Flipping bool on one instance of prefab in scene
I'm detecting if a player is by a door, by flipping a bool in OnTriggerEnter.
What I have works for animating the correct door opening, but when I try to parent the player with the door, I noticed the bool rapidly flips from true to false. So, the player is constantly being added and removed from the parent, with the end result of the door passing through him. How may I go about only flipping the bool to true for the door the player is near?
My Code
void Update()
{
if(!this.flagDoor)
{
player.transform.parent = null;
}
}
void OnTriggerEnter(Collider other)
{
if(other.gameObject.name == "Player")
{
this.flagDoor = true;
}
}
void OnTriggerStay(Collider other)
{
if(this.flagDoor)
{
player.transform.parent = gameObject.transform.root;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.name == "Player")
{
this.flagDoor = false;
//parentToObject = false;
}
}
Answer by Starwalker · Nov 10, 2013 at 09:42 AM
The problem is more design related here, adding the player to the door seems un-needed, why?, you need to explain for a full accurate answer.
The reason the door passes through him is because, when you parent an object to another, the child loses its own position and in-herits its parents position.
You'll need to keep the door and the player separate, you already have a trigger setup, you can do whatever you want in the OnTriggerEnter and OnTriggerExit , because these are events which fire /frame, when the trigger is touched. So you are parenting the player every frame, not just once, which is un-needed and inefficient.
If your purpose for all this is just to detect if the player is nearby the door, just increase the size of the collider, the collider can be made bigger without scaling the object itself.
If you can do the above, it would solve your problem, if not, redesign your code structure.
You can interect with other scripts using GetComponent or GameObject.Find, parenting is not required.
I tried using rigid bodies at first, so the door would collide with the player; (he has a character controller) but, the door still pass through him. Even after playing around with is kinematic the door animation kept passing through the character. I ended up setting up a trigger box on each side of the door that are responsible for calling the appropriate door animations, and parenting the player to the door, If he's in the way of the animation. They also detach the player, if he leaves the trigger or the current animation wouldn't collide with him.
Doesn't your character have a collider on him? What type of collider is this? Usually when to collider's intersect, the 1st one will push the other out.
Doesnt the door itself has a box or mesh collider on it?