简体   繁体   English

如何在 unity3d & C# 中移动立方体?

[英]How to move cube in unity3d & C#?

First of all I apologize that this texts looks so weird.首先,我很抱歉,这些文字看起来很奇怪。 It's my first time to use stackoverflow这是我第一次使用stackoverflow

I start to learn about Unity and C#.我开始了解 Unity 和 C#。

And today I learn about move cube in unity, gonna review the script and I think i failed.今天我学习了统一移动立方体,要查看脚本,我认为我失败了。

I put script in cube1 at Hierarchy, click the solution build at C# and run at unity.我将脚本放在 Hierarchy 的 cube1 中,单击 C# 的解决方案构建并统一运行。 And didn't work.并没有奏效。

public class TRAIN : MonoBehaviour
{
    // return cube1 to cube. cube1 is name of cube object in unity
    GameObject cube = GameObject.Find("cube1");   

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //move cube1 to z-axis at speed 1
        cube.transform.position += new Vector3(0, 0, 1);  
    }
}

How can I move cube1?如何移动 cube1?

You can't call GameObject.Find() directly there, you should be getting an error in the console.你不能直接在那里调用GameObject.Find() ,你应该在控制台中得到一个错误。

UnityException: Find is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead UnityException:不允许从 MonoBehaviour 构造函数(或实例字段初始值设定项)调用 Find,而是在 Awake 或 Start 中调用它

Do it in the Awake() or Start() instead.改为在Awake()Start()中执行此操作。

public class TRAIN : MonoBehaviour
{
    GameObject cube; 

    void Start()
    {
        cube = GameObject.Find("cube1");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM