Spawn power ups after random amount of time
So at the moment I have a power up that speeds the player up by 2x, in IEnumetor WaitTime ()
This is called when the Player gameobject hits the speed power up gameobject. I was wondering once it is hit, how to make it destroy and instantiate after a random amount of time?
Many thanks
Code:
public float speed;
private Rigidbody2D rb2d;
public GameObject Player;
public static int livess = 3;
public Vector2 movement;
void Start ()
{
rb2d = GetComponent<Rigidbody2D> ();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal"); //Gets keys that unity refers to being able to move horizontal (Set by default)
float moveVertical = Input.GetAxis ("Vertical"); //Gets keys that unity refers to being able to move vertical (Set by default) Use forces to act with RigidBody2D
Vector2 movement = new Vector2 (moveHorizontal, moveVertical);
rb2d.AddForce (movement * speed);
if(moveHorizontal < 0)
GetComponent<SpriteRenderer>().flipX = true;
else if(moveHorizontal > 0)
GetComponent<SpriteRenderer>().flipX = false;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag ("shuriken"))
{
if (livess <= 1)
{
Destroy (Player);
livess = livess - 1;
Debug.LogError (livess);
}
else
{
livess = livess - 1;
Debug.LogError (livess);
return;
}
}
else if (other.gameObject.CompareTag ("speedPowerUp"))
StartCoroutine (WaitTime());
}
IEnumerator WaitTime ()
{
speed = speed * 2;
yield return new WaitForSeconds (5);
speed = speed / 2;
}
}
Forgot to mention, this is attatched to the GameObject "Player". I think I will need the instantiation script in the speedPowerUp GameObject
Answer by Jordi-Bonastre · Mar 21, 2016 at 05:04 PM
MonoBehaviour.Invoke?
http://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html
This is called when the Player gameobject hits the speed power up gameobject. I was wondering once it is hit, how to make it destroy and instantiate after a random amount of time?
When it's hit, call to Invoke(_numberOfSeconds) and Destroy.
You can do this inside of a OnTriggerEnter2D function?