- Home /
After disabling then enabling this script it stops working anyone know why?
i used unity playmaker to disable and enable the script
using UnityEngine; using System.Collections;
public class Green : MonoBehaviour { public Transform Target; public float firingAngle = 45.0f; public float gravity = 9.8f;
public Transform Projectile;
private Transform myTransform;
void Awake()
{
myTransform = transform;
}
void Start()
{
StartCoroutine(SimulateProjectile());
}
IEnumerator SimulateProjectile()
{
// Short delay added before Projectile is thrown
yield return new WaitForSeconds(0.1f);
// Move projectile to the position of throwing object + add some offset if needed.
Projectile.position = myTransform.position + new Vector3(0, 0.0f, 0);
// Calculate distance to target
float target_Distance = Vector3.Distance(Projectile.position, Target.position);
// Calculate the velocity needed to throw the object to the target at specified angle.
float projectile_Velocity = target_Distance / (Mathf.Sin(2 * firingAngle * Mathf.Deg2Rad) / gravity);
// Extract the X Y componenent of the velocity
float Vx = Mathf.Sqrt(projectile_Velocity) * Mathf.Cos(firingAngle * Mathf.Deg2Rad);
float Vy = Mathf.Sqrt(projectile_Velocity) * Mathf.Sin(firingAngle * Mathf.Deg2Rad);
// Calculate flight time.
float flightDuration = target_Distance / Vx;
// Rotate projectile to face the target.
Projectile.rotation = Quaternion.LookRotation(Target.position - Projectile.position);
float elapse_time = 0;
while (elapse_time < flightDuration)
{
Projectile.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime);
elapse_time += Time.deltaTime;
yield return null;
}
}
}
Answer by MUG806 · Feb 20, 2021 at 03:42 PM
Not 100% sure but I'd try moving "StartCoroutine(SimulateProjectile());" from Start() to OnEnable(). That way your coroutine should start when you enable the script, not just when it is first created. You may also need to add OnDisable() with "StopCoroutine(SimulateProjectile());", if you want the coroutine to cancel when the object is disabled.
The start method on all monobehaviour scripts run when the scene is first loaded. It isn't ever called again. Even if you disable then enable the script. OnEnable is specific to the script, so it should work as intended.
Which is exactly why I suggested not using start...
Your answer
