unity3D 使用rigidbody.AddForce()

旧的代码写法

void OnMouseDown () {
		rigidbody.AddForce (transform.forward * 500f);
		rigidbody.useGravity = true;
	}

unity 2017 新的代码写法

void OnMouseDown () {
		GetComponent<Rigidbody> ().AddForce (transform.forward * 500f);
		GetComponent<Rigidbody> ().useGravity = true;
	}

可以在代码顶部
[RequireComponent (typeof (Rigidbody))] 将组件预装在物件上变成物件主要的属性,也可以避免代码呼叫错误

[RequireComponent (typeof (Rigidbody))]
public class OnMouseClick : MonoBehaviour {

	void OnMouseDown () {
		GetComponent<Rigidbody> ().AddForce (transform.forward * 500f);
		GetComponent<Rigidbody> ().useGravity = true;
	}
}

你可能感兴趣的:(Unity)