c# - Unity C# 脚本中未调用重写虚函数

标签 c# unity3d

我在 Unity 3D 中编写了以下 2 个脚本,PhysicsObjectPlayerPlatformerController(在 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/

相关文章:

C# 包含方法

c# - 拥有多个步骤文件会打开多个浏览器

c# - jQuery - 如何正确显示两个日期之间的所有记录?

c# - UnityEngine.Component 不包含定义...C#

面向经验丰富的函数式程序员的 C# Lambda 和 LINQ 教程

c# - 需要在场景切换触发碰撞前添加 3 秒延迟

android - 在手机上构建游戏。原生还是引擎?

unity3d - 如何在 RectTransform 中计算 sizeDelta?

unity3d - unity : VRDevice cardboard not supported in Editor Mode. 请在目标设备上运行

c# - 无法将类型为 'System.DBNull' 的对象转换为类型 'System.String`