'Unity C# - Trying to call a method of an instance of a class defined in a script [duplicate]
I am trying to call a function assigned to a canvas object but I can't figure out what method I should use:
ScoringSystem send;
send.AddPoints();
This method does not work and I get the following error:
NullReferenceException: Object reference not set to an instance of an object
ObHost.Update () (at Assets/Scripts/ObHost.cs:39)
The name of the script I am calling the function from is ObHost.
The function is in a script called ScoringSystem.
The function is called AddPoints().
I really don't know what to do here because I have tried other methods but they involve a game object, whereas my function is in a canvas.
Solution 1:[1]
You did not initialize the instance send of the class ScoringSystem, so a NullReferenceException is raised.
And since send is a null reference, any call to a member or a method will fail with a NullReferenceException.
Declaring an variable for an instance, and initializing it are two different things, that are usually done in a single statement, with a call to a constructor (new) or to a static factory method.
All you have to do is initialize the variable send:
// Put any required or optional parameter in the constructor call
ScoringSystem send = new ScoringSystem();
There are some examples here with condition to the object variables: https://www.geeksforgeeks.org/object-and-collection-initializer-in-c-sharp/#:~:text=In%20object%20initializer%2C%20you%20can,the%20variable%20in%20the%20assignment.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kall2sollies |
