-1

I try to study UniRX. And I write the simple script for controlling player:

'''

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);
                }
                );
        }
    }
}

'''

But I get mistake: "NullReferenceException: Object reference not set to an instance of an object playerV1.PlayerController.Start () (at Assets/Scripts/PlayerController.cs:43)" I don't understand what is wrong here. What is problem might be here?

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Azag_Tot
  • 11
  • 2
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – IndieGameDev Jun 28 '21 at 08:42

1 Answers1

0

I had found the mistake. It was not in code. I put both monobehaviours in one file. When I created two files with the same monobehaviours names it started to work fine. Bless Unity spaghetti!

Azag_Tot
  • 11
  • 2