我在 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() {
}
}
我错过了什么?
最佳答案
碰巧我有两个脚本: 健康.cs HealthModified.cs -> 这是 Health.cs 的重写函数
在我的 GameObject 中,我正在测试 HealthModified(已启用)并且我在游戏对象中也有 Health.cs 但已禁用。
当代码被禁用时,代码也在使用 Halth.cs 组件,我不得不从游戏对象中删除该组件以获得 HealthModified 行为。
关于c# - Unity C# 脚本中未调用重写虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46660594/