- Home /
Question by
unity_E790889B07041C2772A3 · Apr 01 at 05:20 AM ·
instantiatecoroutinedelay
Delay Collecting Object by Player
I have two player that are trying to collect a single gameobject. However, I'm having a problem with collecting the gameobject at the same time. I'm trying to create a delay for the enemy collecting the gameObject. But, the enemy just go through the gameobject and doesn't destroy it.
public class DeleteAndSpawn : MonoBehaviour
{
public GameObject Collectable;
// Vector2 randomCollectPosition;
//public float ScanRadius = 1;
//public LayerMask exclude;
public GameObject PlayerOne;
//public LayerMask whatIsPlayer;
public GameObject EnemyDestroy;
bool samePosition = true;
float timerOne;
void OnTriggerEnter2D(Collider2D collision)
{
samePosition = true;
if (collision.gameObject.tag == "Player")
{
Vector2 randomCollectPosition2 = new Vector2(Random.Range(-4, 4), Random.Range(-4, 4));
while (Vector2.Distance(randomCollectPosition2, PlayerOne.transform.position) <= 7)
{
randomCollectPosition2 = new Vector2(Random.Range(-10, 10), Random.Range(-10, 10));
}
Instantiate(Collectable, randomCollectPosition2, Quaternion.identity);
// Debug.Log(Vector2.Distance(randomCollectPosition2, PlayerOne.transform.position));
Destroy(gameObject);
}
StartCoroutine(turnSamePosition());
if (collision.tag == "Enemy" && samePosition == false)
//else
{
Vector2 randomCollectPosition2 = new Vector2(Random.Range(-4, 4), Random.Range(-4, 4));
while (Vector2.Distance(randomCollectPosition2, EnemyDestroy.transform.position) <= 7)
{
randomCollectPosition2 = new Vector2(Random.Range(-10, 10), Random.Range(-10, 10));
}
Instantiate(Collectable, randomCollectPosition2, Quaternion.identity);
//Debug.Log(Vector2.Distance(randomCollectPosition2, EnemyDestroy.transform.position));
Destroy(gameObject);
}
IEnumerator turnSamePosition()
{
yield return new WaitForSeconds(0.01f);
samePosition = false;
Debug.Log("Change");
}
}
}
Comment