Disable a script for a few seconds
can somebody show me how to disable this script for a few seconds once it collides with an object tag "bouncy object" here's the script:
using UnityEngine;
using System.Collections;
public class playermovement : MonoBehaviour {
public float speed = 15f;
private Vector3 target;
void Start () {
target = transform.position;
}
void Update () {
if (Input.GetMouseButtonDown (0)) {
target = Camera.main.ScreenToWorldPoint (Input.mousePosition);
target.z = transform.position.z;
}
transform.position = Vector3.MoveTowards (transform.position, target, speed * Time.deltaTime);
}
}
Thank you!!
Answer by Cepheid · Nov 09, 2015 at 12:29 AM
Try having a look at Coroutines and the WaitForSeconds method provided by Unity.
You could use this to call a method on another script which contains an instance of the playermovement script so that it disables it, waits for a specified amount of time and then re-activates the script through the enabled variable. For example have a look below:
public playermovement playerMovementRef;
void Start ()
{
StartCoroutine("DisableScript");
}
IEnumerator DisableScript ()
{
playerMovementRef.enabled = false;
yield return new WaitForSeconds(3f);
playerMovementRef.enabled = true;
}
Thank you, I've tried the script out and it kinda works, the only problem is that when my player collides with an object that bounces it, the player shakes a lot, also when the player moves left it's movement is all weird, until it collides with another box collider. How would I stop this from occurring? Once again thanks in advances. @Cepheid
Answer by Statement · Nov 09, 2015 at 08:25 PM
void OnCollisionEnter(Collision collision)
{
float fewSeconds = 3;
if (collision.gameObject.tag == "bouncy object")
Disable(fewSeconds);
}
void Disable(float time)
{
enabled = false;
// If we were called multiple times, reset timer.
CancelInvoke("Enable");
// Note: Even if we have disabled the script, Invoke will still run.
Invoke("Enable", time);
}
void Enable()
{
enabled = true;
}
Your answer
Follow this Question
Related Questions
How to enable and disable a script on an game object by pressing a keyboard button? 1 Answer
How to disable my buttons when i press and enable the other ones? 0 Answers
How do I disable enemy ai the script after enemy ai dies 1 Answer
Identical Lines of Code Will Either Disable, or Wont Disable a Script. Need Help. 0 Answers
What is wrong with my script? 1 Answer