[英]Unity - Moving Platform from Point A to Point B
I am trying to make a game in Unity and I am stuck in a part where I am trying to move a platform from Point A to Point B.我正在尝试在 Unity 中制作游戏,但我被困在试图将平台从 A 点移动到 B 点的部分。
The error I get is:我得到的错误是:
NullReferenceException: Object reference not set to an instance of an object MovingPlatform.Update () (at Assets/Scripts/MovingPlatform.cs:30) NullReferenceException:Object 引用未设置为 object MovingPlatform.Update () 的实例(位于 Assets/Scripts/MovingPlatform.cs:30)
The Source Code is:源代码是:
public class MovingPlatform: MonoBehaviour公共 class 移动平台:MonoBehaviour
{ {
[SerializeField]
private Transform pointA, pointB;
private float speed = 1.0f;
private Transform target;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (transform.position == pointA.position)
{
target = pointB;
}
else if (transform.position == pointB.position)
{
target = pointA;
}
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
} }
What should I do?我应该怎么办?
Because the platform is not moving at all.因为平台根本不动。
The error tells you whats wrong.该错误告诉您出了什么问题。 In line 30 of your script you have a reference somewhere which is
null
(hence NullReferenceException
) and you try to do something with this (eg accessing attributes).在脚本的第 30 行中,您在某处有一个引用
null
(因此是NullReferenceException
),您尝试对此做一些事情(例如访问属性)。 I guess its target.position
from我猜它的
target.position
来自
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
when your if
-statements dont trigger.当您的
if
语句不触发时。 You should add target = pointB;
你应该添加
target = pointB;
in Start()
to have target
properly initialized (i assume you want start out moving to pointB
).在
Start()
中正确初始化target
(我假设你想开始移动到pointB
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.