I am working on a very small Unity 5.4 project, I have several "pellets" which in the game world have a Rigid Body 2D and 2D polygon collider attached. I then also have a ball which has a Rigid Body 2D, Polygon Colider and also a Physics Material which allows the ball to bounce into other objects.
The following code is attached to a script on the ball would do something... anything when it hits the green pellets but nothing happens. I don't actually want it to quit the application this was just for example purposes.
The following are the properties of both objects:
public class BallBounce : MonoBehaviour {
// Use this for initialization
void Start () {
//activate camera because I am lazy
var cam = GameObject.Find ("camera");
var ball = GameObject.Find ("ball");
Rigidbody2D rb = GetComponent<Rigidbody2D>();
cam.SetActive (true);
}
// Update is called once per frame
void Update () {
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Bricks") {
Application.Quit ();
}
}
}
Application.Quit();
does not work in the Editor. It is used for Standalone Build. Replace that with UnityEditor.EditorApplication.isPlaying = false;
Now, if you want it to work in both Editor and Standalone Build:
void Start ()
{
//activate camera because I am lazy
var cam = GameObject.Find ("camera");
var ball = GameObject.Find ("ball");
Rigidbody2D rb = GetComponent<Rigidbody2D>();
cam.SetActive (true);
Debug.Log("Start Called!");
}
void Update ()
{
}
void OnCollisionEnter2D(Collision2D col)
{
Debug.Log("Collision detected: "+col.gameObject.name);
if (col.gameObject.tag == "Bricks") {
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
Next time when testing if something is true or false, simply use Debug.Log("It works");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.