【发布时间】:2017-10-10 07:10:41
【问题描述】:
我在 Unity 3D 中编写了以下 2 个脚本,PhysicsObject 和 PlayerPlatformerController(接下来是 tutorial)。 PlayerPlatformerController 脚本附加到游戏对象。
PhysicsObject.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PhysicsObject : MonoBehaviour {
void Update () {
ComputeVelocity ();
}
protected virtual void ComputeVelocity() {
}
}
PlayerPlatformerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerPlatformerController : PhysicsObject {
void Update () {
}
protected override void ComputeVelocity() {
}
}
代码看起来很简单,但是PlayerPlatformerController 中的ComputeVelocity() 没有被调用(通过添加Debug.Log() 来证明)。为什么?
如果我更改为以下代码,该功能可以完美运行:
PhysicsObject.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PhysicsObject : MonoBehaviour {
void Update () {
//ComputeVelocity ();
}
/*protected virtual void ComputeVelocity() {
}*/
}
PlayerPlatformerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerPlatformerController : PhysicsObject {
void Update() {
ComputeVelocity();
}
void ComputeVelocity() {
}
}
我错过了什么?
【问题讨论】:
-
ComputeVelocity方法是否在PhysicsObject中被调用? -
嗨,史蒂夫,是的,
ComputeVelocity()可以在PhysicsObject内调用(也由Debug.Log()证明) -
尝试将
PhysicsObject中的ComputeVelocity更改为抽象方法,看看它是否在PlayerPlatformerController中被调用。我来自 .Net 视图,但除非 Mono 有不同的行为,否则它应该可以按您的预期工作。 -
谢谢。通过将
virtual更改为abstract,它要求PhysicsObject类也必须是abstract类。因为我在PhysicsObject类中有其他代码,所以我不能这样做。我开始认为这是 Unity 的一个小故障,因为无论从 .NET 还是 Mono 框架的角度来看,我的代码看起来都很好。 -
如果您不直接使用“PhysicsObject”,您应该可以将其抽象化。我只是建议它无论如何都要进行测试,看看是否调用了基本实现。