- Home /
The Script keeps executing..instead executing onec
The following script is to reset the ball after every kick in the football game.. the scripts works well but what happens is the after the collision(kick) the function should be called once but after first collision the ball gets reset after five seconds...but the ball keeps resetting after every five second even if not kicked(collided) again.. can any one help to find the mistake in the script..?
using UnityEngine;
using System.Collections;
public class BallSpawnTest : MonoBehaviour
{
private Vector3 initialPos; // Hold the ball's initial position, and reset it's position to this after every kick
private Quaternion originalRotation;
private float hitballTimer = 0.0f; // Timer to make sure we only use the first collision detected
private const float COLLISION_TIMER = 1.0f; // Time after kick to ignore collisions
private const float KICK_SEQUENCE_TIME = 5.0f; // Time from kick start until the game is reset
void Start()
{
initialPos = transform.position;
originalRotation = transform.rotation;
}
void Update ()
{
Debug.Log("update function called");
// When the timer is active, update it
if(hitballTimer > 0.0f)
{
hitballTimer -= Time.deltaTime;
}
}
void OnCollisionEnter(Collider collide) {
if(hitballTimer <= 0 && (collide.gameObject.name == "ball"))
{
print("hit Ball with: " + collide.gameObject.name);
Debug.Log("Ball hit");
KickBall(true);
}
}
private void KickBall(bool leftFoot)
{
// Start timer to prevent collision detection until the ball is at a distance from the legs
hitballTimer = COLLISION_TIMER;
StartCoroutine(RestartBall());
}
private IEnumerator RestartBall()
{
Debug.Log("in restart bal function");
yield return new WaitForSeconds(KICK_SEQUENCE_TIME);
Debug.Log("in restart bal function2");
transform.position = initialPos;
rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;
transform.rotation = originalRotation;
}
}
Comment