从另一个脚本访问字符马达

本文关键字:字符 马达 访问 脚本 另一个 | 更新日期: 2023-09-27 18:35:37

正在尝试创建运行脚本。访问玩家的CharacterMotor并提高移动速度,但编译器说这些对象不存在。使用常用的 First Person Character Controller

错误 CS1061:键入 UnityEngine.Component' does not contain a definition for 字符电机",找不到CharacterMotor' of type UnityEngine.Component' 的扩展方法(是否缺少 using 指令或程序集引用?

public class PlayerRun : MonoBehaviour {
public GameObject _player;
private float _runSpeed = 10;
private float _defaultSpeed;
// Use this for initialization
void Start () 
{
    _defaultSpeed = _player.GetComponent("CharacterMotor").CharacterMotor.maxForwardSpeed;
}
// Update is called once per frame
void Update () 
{
    if (Input.GetKeyDown(KeyCode.LeftShift))
    {
        _player.GetComponent("CharacterMotor").CharacterMotor.maxForwardSpeed = _runSpeed;
        _player.GetComponent("CharacterMotor").CharacterMotor.maxSidewaysSpeed = _runSpeed;
        _player.GetComponent("CharacterMotor").CharacterMotor.maxBackwardsSpeed = _runSpeed;
    }
    else
    {
        if (_player.GetComponent("CharacterMotor").CharacterMotor.maxForwardSpeed == _runSpeed)
        {
            _player.GetComponent("CharacterMotor").CharacterMotor.maxForwardSpeed = _defaultSpeed;
        _player.GetComponent("CharacterMotor").CharacterMotor.maxSidewaysSpeed = _defaultSpeed;
        _player.GetComponent("CharacterMotor").CharacterMotor.maxBackwardsSpeed = _defaultSpeed;
        }
    }
}

}

从另一个脚本访问字符马达

看起来你刚刚从 UnityScript 迁移到 C#?

您可能应该使用 GetComponent 的通用形式:

_defaultSpeed = _player.GetComponent<CharacterMotor>().maxForwardSpeed;

如果调用 GetComponent(typeof(T)) ,您将获得类型 Component 的引用。您可以将结果投射到T,但为什么要打扰呢?您可以同样轻松地调用GetComponent<T>()来获取该类型的引用。