0

I have this code first file

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controller : MonoBehaviour
{
    public Machines machines;
    void Start()
    {
        machines = new Machines();
        machines.ClickSpeedUpgrade();//here I get the error
    }
}

second file

using System.Collections;
using System.Collections.Generic;
using BreakInfinity;
public class Machines
{
    public void ClickSpeedUpgrade()
    {
        //some code
    }
}

NullReferenceException: Object reference not set to an instance of an object

Why do I get this error and how can I fix it?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
  • 2
    We would need to see what is in `ClickSpeedUpgrade` because nothing in `Start` would cause that error – Jamiec Aug 26 '21 at 10:42
  • the call stack error should help you finding where is the problem. Use then breakpoints and debug – Cid Aug 26 '21 at 10:43
  • It is [not allowed](https://stackoverflow.com/questions/40640553/why-in-unity-im-getting-the-warning-you-are-trying-to-create-a-monobehaviour-u) to use `new` in order to create instances of `MonoBehaviour`! Components always need to be attached to an existing `GameObject` -> The only valid options for creating instances is using `someGameObject.AddComponent`, `Instantiate(prefabWithMachinesComponent)` or `new GameObject("name", typeof(Machines))` .... does your class need to be a `MonoBehaviour` (=> attached to a certain GameObject and receive Unity messages) at all? – derHugo Aug 26 '21 at 11:12
  • @derHugo, he is not creating instance of `MonoBehaviour` he is creating an instance of Machines which is not even inherit `MonoBehaviour`, Alexandru, your issue is not in the class and new, it is in the `\\some code` part of it. if you have line numbers, check which line is causing error. – AaA Sep 07 '21 at 08:08

0 Answers0