C# Unity,如何找到我的游戏对象并移动它
我是Unity和C#的新手,我尝试做一个3D游戏 我想当我按下“Qkey”时,立方体的高度会下降 这是我的密码C# Unity,如何找到我的游戏对象并移动它,c#,unity3d,C#,Unity3d,我是Unity和C#的新手,我尝试做一个3D游戏 我想当我按下“Qkey”时,立方体的高度会下降 这是我的密码 using System.Collections; using System.Collections.Generic; using UnityEngine; public class ripcube : MonoBehaviour { // Start is called before the first frame update bool isTeleport
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ripcube : MonoBehaviour
{
// Start is called before the first frame update
bool isTeleported = false;
// Update is called once per frame
void Update()
{
if (Input.GetKey("a") && !isTeleported)
{
ripcube.transform.position = (-2, -2, -2) ;
}
}
}
这给了我一个错误:
(19,13): error CS0120: An object reference is required for the non-static field, method, or property 'Component.transform'
我知道ripcube是我的职业,但我的游戏对象是什么?我在图形界面上创建了多维数据集
谢谢你的帮助,兄弟,你可以用
transform.position = new Vector3(-2, -2, -2);
而不是
transform.position = (-2, -2, -2) ;
改变
Input.GetKey("a")
到
你应该在youtube上观看一些关于unity gameobjects如何工作的基本视频,但现在: 您可以从代码中引用游戏对象,或按如下方式查找它们:
public class ripcube: MonoBehaviour
{
GameObject myCubeObject;
float speed = 2f;
void Start()
{
myCubeObject = GameObject.Find("YourCubeNameInUnity");
}
void Update()
{
if(Input.GetKey(KeyCode.Q))
{
myCubeObject.transform.Translate(speed * Vector3.down * Time.deltaTime);
}
}
}
你应该注意的是:
myCubeObject.transform.position+=speed*Vector3.down*Time.deltaTime
浮点速度
变量,即立方体在所需方向上的速度(我使用2作为值,但它可以是任何实际值)Vector3.down
)指定。你可以随意改变卸下ripcube。。。。然后使用
transform.position=newvector3(-2,-2,-2)代码>或transform.position=Vector3.one*-2代码>。。因此,基本上使用this.transform
谢谢您的评论,仅此而已,如果您愿意,您可以添加以下答案:)
public class ripcube: MonoBehaviour
{
GameObject myCubeObject;
float speed = 2f;
void Start()
{
myCubeObject = GameObject.Find("YourCubeNameInUnity");
}
void Update()
{
if(Input.GetKey(KeyCode.Q))
{
myCubeObject.transform.Translate(speed * Vector3.down * Time.deltaTime);
}
}
}