我有一个技工在我的新项目,敌人被编程追逐球员,但只有当他们有他们的“火炬”启用。正如您将在脚本中看到的那样,我使用null检查来完成此操作。
以下是代码:
public class chasePlayer : MonoBehaviour
{
public Transform target;
public float speed;
public Light playerLight;
void followLight()
{
if (playerLight != null)
{
speed = 1;
float walkspeed = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, walkspeed);
}
}
void stopFollowing()
{
if (playerLight = null)
{
speed = 0;
}
}
void Update()
{
followLight();
stopFollowing();
}
}问题是,我认为我所有的代码都是正确的,理论上它应该做我想做的事情,但它没有。它根本不移动,即使当我开始游戏,它应该。
我可能做错了什么。第一次做原始脚本的时候,可能很多地方出错了
发布于 2018-09-03 08:27:53
这里的老兵!*笑*
在开始之前,我只想提到您正在使用C#,所以尝试使用CamelCase来命名方法和类。
您的代码无法工作,因为您正在检查Light组件的null。只有在没有任何东西被分配,或者被分配的对象被销毁之后,null才会成为现实。如果要检查组件的状态,最好使用playerLight.enabled。在整个代码中添加一些小的改进,现在看起来如下:
public class ChasePlayer : MonoBehaviour
{
public Light playerLight;
public float speed;
public Transform target;
private void FollowLight()
{
// Does checking for given statement but is only executed in Debug mode.
// Fairly good for fail-proofing private methods
// Or clarifying, what values should be before invoking the method.
Debug.Assert(playerLight != null);
float walkspeed = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, walkspeed);
}
private void Update()
{
if(playerLight != null && playerLight.enabled)
FollowLight();
}
}注意:不要忘记将类文件重命名为ChasePlayer,因为类名是CamelCased (为了能够在编辑器中为GameObjects分配组件),需要匹配该文件和类名。
发布于 2018-09-03 07:51:13
根据您最后的评论,尝试如下:
public class chasePlayer : MonoBehaviour
{
public Transform target;
public float speed;
public Light playerLight;
void followLight()
{
if (playerLight != null)
{
speed = 1;
}
float walkspeed = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, walkspeed);
}
void stopFollowing()
{
if (playerLight == null)
{
speed = 0;
}
}
void Update()
{
followLight();
stopFollowing();
}
}https://stackoverflow.com/questions/52143837
复制相似问题