Open and Close using colliders

Hello. I implemented my own code to open and close objects that are animatable. But a problem arose when it wouldnt work. The logic is as follows:

GameObject:Locker has the script, and the locker model has the animations. A box collider is attached to GameObject:Locker. When the player enters OnColliderEnter() is called and if the player presses “E” the locker should open. Only it doesnot, nor does it close. I think the problem is OnColliderEnter() method.

public class OpenClose : MonoBehaviour 
{
	Animation lockerBehavior;

	public AudioClip open;
	public AudioClip close;

	bool isOpen;
	bool isClosed = true;

	void Start()
	{
		lockerBehavior = GetComponentInChildren<Animation>();
	}


	void Update () 
	{

	}

	void OnColliderEnter(Collider enter)
	{
		if(enter.gameObject.tag == "Player")
		{
			if(isClosed == true)
			{
				if(Input.GetKey(KeyCode.E))
				{
					isOpen = true;
					audio.PlayOneShot(open);
					lockerBehavior["Open"].wrapMode = WrapMode.Once;
					lockerBehavior.Play("Open");
					
					if(isOpen == true)
					{
						if(Input.GetKey(KeyCode.E))
						{
							isClosed = true;
							audio.PlayOneShot(open);
							lockerBehavior["Close"].wrapMode = WrapMode.Once;
							lockerBehavior.Play("Close");
						}
					}	
				}
				
			}
		}
	}
}

Hi Irin,

I would suggest trying to make a bool that determines if your character is in range. I think the problem lies with your nested if statements. The following code will give you an idea of how you might approach this.

bool inRange;

void Start()
{
  inRange = false;
}

void OnCollisionEnter(Collider other)
{
  if (other.gameObject.tag == "Player")
    inRange = true;
}

void OnCollisionExit(Collider other)
{
  if (other.gameObject.tag == "Player)
    {inRange = false;}
}

void Update()
{
  if (inRange && Input.GetButtonDown("Interact") && isOpen == false)
 {
  OpenLocker(); 
 }
}

I suggest you mark your colliders as “Is Trigger”, and then replace OnCollisionEnter/Exit with OnTriggerEnter/Exit.
Also make sure your player has a collider and rigidbody attached.