Unity always stop working when running simple script, Help please ?
I attach a script to a simple cube which bounded by four other cube. But when I play, unity stops responding. Is anything wrong in my script, or any other suggestion please ?
using UnityEngine; using System.Collections;
public class gunf : MonoBehaviour {
public int sec;
public float value;
public float ras;
public bool isDown;
public Rigidbody rb;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update () {
}
void FixedUpdate () {
while(Input.GetMouseButtonDown (0) && isDown == false){
isDown = true;
ras = Random.Range (10f, 40f);
rb.AddForce (transform.up * ras);
Debug.Log (ras);
isDown = false;
}
}
}
Sorry for bad english.
Answer by ZefanS · Dec 01, 2015 at 06:57 AM
From what I can understand it seems as though you just want to check when the user clicks the mouse, so you could try this instead:
void FixedUpdate ()
{
if (Input.GetMouseButtonDown (0))
{
ras = Random.Range (10f, 40f);
rb.AddForce (transform.up * ras);
Debug.Log (ras);
}
}
I would think it's probably unnecessary to use FixedUpdate(). Update() is probably fine. Hope this helps.
Actually I want the loop of AddForce till i pressed mouse button. Is any suggestion ? And why unity crashes ?
The reason Unity crashes is likely because you are stuck in an infinite loop. If you want it to add the force when the mouse button isn't being pressed, try this:
void FixedUpdate ()
{
if (!Input.Get$$anonymous$$ouseButton (0))
{
ras = Random.Range (10f, 40f);
rb.AddForce (transform.up * ras);
Debug.Log (ras);
}
}
If you want to keep looping until you click and then stop, try this:
using UnityEngine;
using System.Collections;
public class gunf : $$anonymous$$onoBehaviour
{
public int sec;
public float value;
public float ras;
public bool clicked = false;
public Rigidbody rb;
// Use this for initialization
void Start ()
{
rb = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void Update ()
{
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
clicked = true;
}
if (clicked == false)
{
ras = Random.Range (10f, 40f);
rb.AddForce (transform.up * ras);
Debug.Log (ras);
}
}
}