- Home /
Question by
SuperCrow2 · Jan 17, 2021 at 02:05 AM ·
c#gameobjectcolliderunity 2dcharacter
Getting a chest is not enabling my collider
The collider on my character starts off disabled, which is working as intended, and it is supposed to be enabled when I get a chest, when it is enabled running into an enemy destroys it which also works. After seconds, its supposed to be disabled, but that doesnt work.
The following does not work, no matter which function I put the code in, it does not work properly:
When I put the code in Update, FixedUpdate, or OnTriggerEnter, the collider is always enabled, even when I didn't get the chest, it overrode my start function for some reason.
When I put the code in OnCollisionEnter the collider is not being enabled.
I included both methods (CollisionEnter and FixedUpdate) for this question, I only used one in my actual script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//THIS COLLIDER IS ON OUR CHARACTER
public GameObject other;
public GameObject ChestObject1;
public GameObject ChestObject2;
//START COLLIDER DISABLED
void Start()
{
other.GetComponent<Collider2D>().enabled = false;
}
private void OnCollisionEnter2D(Collision2D col)
{
if (ChestObject2.tag.Equals("chest"))
{
other.GetComponent<Collider2D>().enabled = true;
StartCoroutine("DisableCollider");
}
//AFTER GETTING THE CHEST, ENABLE THE COLLIDER
void FixedUpdate()
{
if (ChestObject1.tag.Equals("chest"))
{
//ENABLE COLLIDER AFTER GETTING THE CHEST SO WE CAN DESTROY THE ENEMY WHEN WE RUN INTO IT
other.GetComponent<Collider2D>().enabled = true;
//START CO-ROUTINE TO DISABLE THE COLLDER AFTER 5 SECONDS AFTER IT'S BEEN ENABLED SO WE CAN NO LONGER DESTROY THE ENEMY
StartCoroutine("DisableCollider");
}
}
//DISABLE THE COLLIDER AFTER 5 SECONDS
private IEnumerator DisableCollider()
{
yield return new WaitForSeconds(5f);
yield return new WaitForSeconds(0.5f); // wait 1/10th of a second 0.1f
other.GetComponent<Collider2D>().enabled = false;
}
}
Comment