如何在unity脚本中移动单独的对象
本文关键字:移动 单独 对象 脚本 unity | 更新日期: 2023-09-27 18:03:06
我正在尝试在Unity中编写一个c#脚本,该脚本将移动游戏中的其他对象。我尝试了下面的代码,但它不起作用。错误是说REDpos、RRDpos、RADpos和RCDpos在当前上下文中不存在。请帮我想办法解决这个问题!我是初学者,很抱歉,如果这很明显。
下面是我的代码:using UnityEngine;
using System.Collections;
public class TeamSelect : MonoBehaviour {
public GameObject RCD;
public GameObject RAD;
public GameObject RED;
public GameObject RRD;
// Use this for initialization
void Start () {
RCD = GameObject.Find("RCD");
RAD = GameObject.Find("RAD");
RED = GameObject.Find("RED");
RRD = GameObject.Find("RRD");
}
// Update is called once per frame
void Update () {
RCDpos = RCD.transform.position.x;
RADpos = RAD.transform.position.x;
REDpos = RED.transform.position.x;
RRDpos = RRD.transform.position.x;
if (Input.GetKey("right")) {
RCDpos = RCDpos - 0.1;
RADpos = RADpos - 0.1;
REDpos = REDpos - 0.1;
RRDpos = RRDpos - 0.1;
}
if (Input.GetKey("left")) {
RCDpos = RCDpos + 0.1;
RADpos = RADpos + 0.1;
REDpos = REDpos + 0.1;
RRDpos = RRDpos + 0.1;
}
}
}
当然他们不存在…你没有定义它们:'
RCDpos = RCD.transform.position.x;
RADpos = RAD.transform.position.x;
REDpos = RED.transform.position.x;
RRDpos = RRD.transform.position.x;
在给RCDpos分配一些东西之前,你必须定义它们,你只定义RCD RAD RED RRD GameObject
尝试在你定义你的GameObjects后添加这个:
Vector3 RCDpos;
Vector3 RADpos;
Vector3 REDpos;
Vector3 RRDpos;
用这种方式修改你的Update:
RCDpos = new Vector3(RCD.transform.position.x,0,0);
RADpos = new Vector3(RAD.transform.position.x,0,0);
REDpos = new Vector3(RED.transform.position.x,0,0);
RRDpos = new Vector3(RRD.transform.position.x,0,0);
我想应该是工作
试试这个:
class Obj : MonoBehaviour
{
//public so other classes can get it
public Vector3 pos = transform.position;
void Update ()
{
//keeps pos updated
pos = transform.position;
}
public void move (Vector3 vect)
{
//moves player
transform.position += vect;
}
}
class team
{
public Obj obj;
void Start ()
{
obj.move(new Vector3(0f,0f,0f));
}
}
将对象从team类中移出。