今天我们来通过写的代码来添加RigidBody组件
首先在Hierarchy 添加Sphere
然后书写脚本Rigid
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rigid : MonoBehaviour
{
private Rigidbody m_Rigidbody;
// Start is called before the first frame update
void Start()
{
//用代码添加组件
gameObject.AddComponent<Rigidbody>();
//用代码获取组件
m_Rigidbody = GetComponent<Rigidbody>();
//如果组件不为空
if (m_Rigidbody != null)
{
m_Rigidbody.useGravity = true;
m_Rigidbody.isKinematic = true;
}
//如果组件为空
else
Debug.Log("can not find component");
}
// Update is called once per frame
void Update()
{
}
}
最后在将脚本添加到创建的物体身上
我们就会发现 球体的Inspector
在运行的时候会有Rigid组件