So basically I have obstacles spawn and when “Player” hits them their speed gets reduced and when the “Enemy” hits them I want him to stop moving for (waitTime); after waitTime the obstacle is destroyed.
For now it works all like a charm only when “Enemy” and “Player” hit the same obstacle, only playerSpeed is restored and on enemy.IsKinematic stays true.
Here is my code:
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player" && gameManager.isGameActive == true)
{
SlowDownPlayer();
}
else if (other.tag == "Enemy" && gameManager.isGameActive == true)
{
SlowDownEnemy();
}
}
public void SlowDownPlayer()
{
Debug.Log("Splash");
StartCoroutine(SlowDownInPuddle());
}
public IEnumerator SlowDownInPuddle()
{
player.gameObject.GetComponent<PlayerController>().playerSpeed = player.gameObject.GetComponent<PlayerController>().playerSpeed / 2;
yield return new WaitForSecondsRealtime (waitTime);
Destroy(gameObject);
if (gameObject != null)
{
Debug.Log("player-speed restore");
player.gameObject.GetComponent<PlayerController>().playerSpeed = player.gameObject.GetComponent<PlayerController>().playerSpeedInit;
}
}
public void SlowDownEnemy()
{
Debug.Log("Slurp");
StartCoroutine(SlowDownInPuddleEnemy());
}
public IEnumerator SlowDownInPuddleEnemy()
{
enemy.gameObject.GetComponent<Rigidbody>().isKinematic = true;
yield return new WaitForSeconds(waitTime);
Destroy(gameObject);
if (gameObject != null)
{
Debug.Log("enemy-kinematic = false");
enemy.gameObject.GetComponent<Rigidbody>().isKinematic = false;
}
}
Something looks wrong with your code. How do you set the value of player and enemy? I believe they are not the references you get from OnTriggerEnter. And destroying the gameObject before the end of the coroutine may abort the coroutine (the destroy happens after the yield so maybe not).
Hey, thanks for your answer! I checked your code and I still have the same error; when player hits the Puddle and Enemy does so too, playerSpeed is restored but enemy.IsKinematic == true. And Vice versa if enemy hits first and player second.
To give you a little bit more context: I have a prefab spawning with the script applied. If either player or enemy hits the obstacle the code worked just fine, just when both are hitting the same object, the first value changed (playerSpeed or IsKinematic) and the second one is not. I feel like it has to do something with the gameObject being destroyed too soon, so I figured I could call if (gameObject != null) and then “isKinematic = false” and “playerSpeed = playerSpeedInit;” which should apply the if statement, when the object is destroyed. I might be mistaken on that one so maybe that’s where the problem is.
Let me post more of my code: