Unity实现围绕另一物体旋转

对于Unity操作0基础.看过百度的教程

public class RotateTest : MonoBehaviour
{
    public Transform cube;

    private void Update()
    {
        this.transform.RotateAround(cube.position, cube.up, 20 * Time.deltaTime);
    }
}

写完后进入Unity无法直接运行,还需要在Inspector面板中设置,否则会报错The variable cube of RotateTest has not been assigned.
在这里插入图片描述
此时年幼的我打算这样写,心想,在这里设置完cube后就不用再去Inspector设置了

public class RotateTest : MonoBehaviour
{
    public Transform cube = GameObject.FindGameObjectWithTag("Cube").transform;
    private void Update()
    {
        this.transform.RotateAround(cube.position, cube.up, 20 * Time.deltaTime);
    }
}

但依然会报上述的错。正如atgczcl所言,这种错误很低级

不需要设置Inspector的代码:

public class RotateTest : MonoBehaviour
{
    public GameObject cubeobj;
    public Transform cube;

    private void Start()
    {
        cubeobj = GameObject.Find("Cube");
        cube = cubeobj.transform;
    }
    private void Update()
    {
        this.transform.RotateAround(cube.position, cube.up, 20 * Time.deltaTime);
    }
}

此时运行,则球体可成功围绕Cube的周旋转

你可能感兴趣的:(Unity,unity)