反应性属性未设置为对象的实例

时间:2021-06-28 07:41:32

标签: c# unity3d unirx

我尝试学习 UniRX。我编写了用于控制播放器的简单脚本:

'''

using UnityEngine;
using UniRx;
using UniRx.Triggers;

namespace playerV1
{
    public class Inputs : MonoBehaviour
    {
        public static Inputs Instance { get; private set; }
        public ReadOnlyReactiveProperty<Vector2> ImpulseForce { get; private set; }
        private void Awake()
        {
            Instance = this;
            ImpulseForce = this.FixedUpdateAsObservable()
                .Select
                (
                _ =>
                {
                    float x = Input.GetAxis("HorizontalX");
                    float z = Input.GetAxis("HorizontalZ");
                    return new Vector2(x, z).normalized;
                }
                )
                .ToReadOnlyReactiveProperty();
        }
    }
    
    public class PlayerController : MonoBehaviour
    {
        public float coefficient;
        private Rigidbody _rg;

        private void Awake()
        {
            _rg = GetComponent<Rigidbody>();
        }
        private void Start()
        {
            Inputs inputs = Inputs.Instance;
            //Debug.Log(inputs.ImpulseForce); I get the mistake here
            inputs.ImpulseForce
                .Where(force => force != Vector2.zero)
                .Subscribe
                (
                force =>
                {
                    _rg.AddForce(coefficient * new Vector3(force.x, 0, force.y), ForceMode.Impulse);
                }
                );
        }
    }
}

'''

但是我弄错了: “NullReferenceException:未将对象引用设置为对象的实例 playerV1.PlayerController.Start()(在 Assets/Scripts/PlayerController.cs:43)” 我不明白这里有什么问题。 这里可能有什么问题?

1 个答案:

答案 0 :(得分:0)

我发现了错误。它不在代码中。我将两种单一行为放在一个文件中。当我创建两个具有相同 monobehaviours 名称的文件时,它开始正常工作。 祝福 Unity 意大利面!