- Home /
Yield/OnTriggerEnter Help C#
Hey guys, at the moment my rocks are falling due to having a rigidbody and being placed in the sky with gravity bringing them down. When they hit the player it sends the player to the beginning of the level using Application.LoadLevel(2). I am fairly new and have attempted yield wait for seconds and coroutines but have not got the code correct. I would like it so when the rock hits the player their is a 2 second delay then the player restarts the level. Also I want these rocks to be triggers so when the player hits the box collider the rock will begin to fall. Thank you for any help, greatly appreciated. :)
using UnityEngine;
using System.Collections;
public class fallingrock: MonoBehaviour {
public float Minspeed;
public float Maxspeed;
private float currentSpeed;
public GameObject explosion;
// Use this for initialization
void Start()
{
currentSpeed = Random.Range(Minspeed, Maxspeed);
float amtToMove = currentSpeed * Time.deltaTime;
transform.Translate(Vector3.down * amtToMove) ;
}
// Update is called once per frame
void Update ()
{
transform.Rotate(Vector3.forward * Time.deltaTime * 100);
}
void OnCollisionEnter(Collision mColl)
{
//Detects when asteroid hits terrain
if(gameObject.tag == "Asteroid" && mColl.gameObject.tag == "Terrain")
{
Destroy (gameObject);
GameObject explosCLONE;
explosCLONE = Instantiate(explosion, transform.position, transform.rotation) as GameObject;
}
//detects when asteroid hits player
if(gameObject.tag == "Asteroid" && mColl.gameObject.tag == "Player")
{
Destroy (gameObject);
GameObject explosCLONE;
explosCLONE = Instantiate(explosion,transform.position,transform.rotation) as GameObject;
Application.LoadLevel(2);
}
}
}
Formatted your code. Please do it properly next time by using the "101010" button.
No problem. When you get enough karma (15 I think), you will be able to edit your own post.
Answer by fafase · Aug 06, 2012 at 11:02 AM
On the guy:
function OnCollisionEnter(other:Collision){
if(other.gameObject.tag=="Stone") Restart();}
function Restart(){
yield WaitForSeconds(2);
transform.position= new Vector3(0,0,0);
}
I guess that would work but I don't have Unity to try.
Im using C#, would it just be a matter of changing function to void?
In C#, coroutine must return an IEnumerator
object.
OnCollisionEnter can already be a coroutine (if I'm not mistaken). So changing @fafase code into C#, it gives:
IEnumeratorOnCollisionEnter(Collision other)
{
if(other.gameObject.tag=="Stone")
{
yield return new WaitForSeconds(2);
transform.position = new Vector3(0,0,0); // to reset the position
// or Application.LoadLevel(Application.loadedLevel); // to restart the level
}
}
Your answer
Follow this Question
Related Questions
Mysteries of yield 1 Answer
Trouble Resuming after Yielding while Inside Coroutine 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# yield waitforseconds 3 Answers