An unhandled exception of type 'System.NullReferenceException' for XNA Game - xna

I keep getting this message:
An unhandled exception of type 'System.NullReferenceException' on the code below:
if (position.X >= p.position.X && position.X != p.position.X)
position.X -= Yspeed;
if (position.X >= p.position.X && position.X != p.position.X)
position.X += Yspeed;
position.Y = position.Y + Yspeed;
Specifically refers to the first line. What i'm trying to do is move the enemy towards the player.

You are accessing a field or method of a null reference:
MyType instance = null;
// Throws a NullReferenceException because instance is
// not an actual object but null.
instance.Name = "foo";
So I suppose position or, rather p is unset. If you are using an IDE like Visual Studio use a breakpoint and inspect your variables and check if they actually contain something.

Related

Instancing Nested Object (Dart)

On trying to assign values to Nested Object Properties,Dart treats the Nested Object(class OperandRange) as null.
Default values have been assigned to the Nested Object Properties but the issue exists.
In the case below Nested Object Class OperandRange should be assigned minimum and maximum values but dart considers it to the Null.
How to resolve this?
Code
import 'dart:io';
//Nested Object Class
class OperandRange{
double _minValue = 0;
double _maxValue = 10;
OperandRange(this._minValue , this._maxValue);
double get minValue => _minValue;
double get maxValue => _maxValue;
set minValue(double _val){
_minValue = (_val) ;
}
set maxValue(double _val){
_maxValue = (_val) ;
}
}
class OperationData{
List<OperandRange> operandList = [];//Nested Object
List<String> operatorList = [] ;
OperationData({this.operandList, this.operatorList});
}
void main(){
int _operationCount = 2;
OperationData _operation = OperationData();
for(int _index = 0 ; _index < _operationCount ; _index++) {
stdout.write(" Operation $_index - Name(string): ");
_operation.operatorList[_index] = stdin.readLineSync();
//Null Object
stdout.write(" Operand $_index - Minimum Value (double) : ");
_operation.operandList[_index]._minValue =
double.parse(stdin.readLineSync());
stdout.write(" Operand $_index - Maximum Value (double): ");
_operation.operandList[_index]._maxValue =
double.parse(stdin.readLineSync());
}
}
Error
Operation 0 - Name(string): Add
Unhandled exception:
NoSuchMethodError: The method '[]=' was called on null.
Receiver: null
Tried calling: []=(0, "Add")
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 main (1.dart:41:28)
#2 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
#3 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
Process finished with exit code 255
Here is what's happening.
You initialize operandList with a nested list. But this never has any effect because you also initialize it in OperationData constructor. Once you mention it in constructor arguments, it will either be set to a value you pass to constructor, or set to null if you do not pass this argument to constructor.
For your purpose you may remove constructor altogether as you never pass anything to it. Then your [] defaults will stand.
Otherwise, if in some cases you need to initialize it with a custom list, you may do it like this:
class OperationData{
List<OperandRange> operandList;
List<String> operatorList;
OperationData({
List<OperandRange> operandList,
List<String>operatorList,
}) :
this.operandList = operandList ?? <OperandList>[],
this.operatorList = operatorList ?? <String>[]
;
}
The same goes for your OperandRange class. 0 and 10 defaults will never be used as the constructor requires explicit values. By the way, I do not see OperandRange creation at all. The list stays empty. You will catch a next error when trying to access an index out of bounds when you fix the first error.
Also you should upgrade to Dart 2.12 if possible. It introduced null-safety that would show you this error at compile time.

WoW Lua error; attempt to call a global(a nil value)

I'm new to Lua and was following the tutorial on https://wowwiki.fandom.com/wiki/AddOn_tutorial but i just cant get it to work; i have copied the code but i get the error message "attempt to call a global 'functionname' (a nil value)" on both the SetMapToCurrentZone() and the GetPlayerMapPosition("player") functions.
This is the entire Lua file;
local zone = nil
local TimeSinceLastUpdate = 0
local function UpdateCoordinates(self, elapsed)
if zone ~= GetRealZoneText() then
zone = GetRealZoneText()
SetMapToCurrentZone()
end
TimeSinceLastUpdate = TimeSinceLastUpdate + elapsed
if TimeSinceLastUpdate > .5 then
TimeSinceLastUpdate = 0
local posX, posY = GetPlayerMapPosition("player");
local x = math.floor(posX * 10000)/100
local y = math.floor(posY*10000)/100
eCoordinatesFontString:SetText("|c98FB98ff("..x..", "..y..")")
end
end
function eCoordinates_OnLoad(self, event,...)
self:RegisterEvent("ADDON_LOADED")
end
function eCoordinates_OnEvent(self, event, ...)
if event == "ADDON_LOADED" and ... == "eCoordinates" then
self:UnregisterEvent("ADDON_LOADED")
eCoordinates:SetSize(100, 50)
eCoordinates:SetPoint("TOP", "Minimap", "BOTTOM", 5, -5)
eCoordinates:SetScript("OnUpdate", UpdateCoordinates)
local coordsFont = eCoordinates:CreateFontString("eCoordinatesFontString", "ARTWORK", "GameFontNormal")
coordsFont:SetPoint("CENTER", "eCoordinates", "CENTER", 0, 0)
coordsFont:Show()
eCoordinates:Show()
end
end
How do i fix it?
These functions have been renamed and moved to a wrapper object in 8.0, to C_Map.GetBestMapForUnit (requiring "player" as parameter to yield the same result) and C_Map.GetPlayerMapPosition respectively.
You can probably expect more functions that are called later to throw the same error, their lines just couldn't be reached before. I can check the whole code example when I'm at a desktop again, but you may simply look up these functions on Wowpedia, especially other map-related functions.
I suggest using Wowpedia over Wowwiki, it's a personal preference/impression, the former seems to receive more constant updates.
(The two seem to be merging again now, after splitting 10 years ago)

Service Fabric reliable state and F# default GetHashCode issue

I having an issue when trying to update a SF stateful service after updating a child object of the service state. The upgrade fails to pass the 1st upgrade domain with a 'package activation' error. Digging around in the event viewer on the offending node gives the below exception:
Errormsg=TStore.OnApplyAddAsync: Unexpected exception System.NullReferenceException: Object reference not set to an instance of an object.
at xxx.DataChildObject.GetHashCode(IEqualityComparer comp)
at xxx.Data.GetHashCode(IEqualityComparer comp)
at xxx.Data.GetHashCode() in C:\Users\xxx\Source\Repos\xxx\xxx\xxx.Core\Domain.fs:line 17
at System.Fabric.Store.TStore`5.OnApplyAdd(TransactionBase txn, MetadataOperationData metadataOperationData, RedoUndoOperationData operationRedoUndo, Boolean isIdempotent, String applyType) Assert=System.Exception: at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
The change to the 'DataChildObject' was to add a new field that is a tuple of 2 doubles.
I understand that F# is automatically generating equality methods and these must be triggered during SF state and that due to datacontact serialisation these are null during the GetHashCode check.
I don't understand exactly when this check is being performed or why though?
As a test i tried overriding the GetHasCode method on my DataChildObject, but this didn't change the error i get when trying to upgrade my service.
[<DataContract>]
type DataChildObject =
class
[<DataMember(IsRequired=false,Name="Value1")>] val mutable Value1 : float * float
[<DataMember(IsRequired=false,Name="Value2")>] val mutable Value2 : float * float
[<DataMember(IsRequired=false,Name="NewValue")>] val mutable NewValue : float * float
new (v1,v2) = {Value1=v1;Value2=v2;NewValue=1.0,1.0}
override this.GetHashCode() =
let value1 = if (box this.Value1 = null) then 1 else this.Value1.GetHashCode()
let value2 = if (box this.Value2 = null) then 1 else this.Value2.GetHashCode()
let newValue = if (box this.NewValue = null) then 1 else (this.NewValue).GetHashCode()
value1+value2+newValue
end
I expect these domain objects to change more in the near future so any help in understanding exact how to get past or avoid this issue is helpful.
Thanks

Function which creates objects that have global name

I had this code which simply displays a picture I need in my game.
DeckOfPlayingCards = display.newImageRect("Graphics/ImproveMenu/Wealth/Luxury/Buy/DeckOfPlayingCards.png", 96*6, 96)
DeckOfPlayingCards.x = centerX
DeckOfPlayingCards.y = -90
DeckOfPlayingCards.name = "DeckOfPlayingCards"
Now, since I have a lot of these pictures planned to be in my game menu, I don't want to copy-paste that code all over. I wanted to make a simple function that would do it for me. This is what I tried, but failed and don't know why.
function DisplayObject(object, x, y, name)
object = display.newImageRect("Graphics/ImproveMenu/Wealth/Luxury/Buy/" ..name..".png", 96*6, 96)
object.x = x
object.y = y
object.name = name
scrollView:insert(object)
end
DisplayObject(DeckOfPlayingCards, centerX, -90, "DeckOfPlayingCards")
This function can successfully show the picture, but whenever I try to do something with it (make it a button), it says the value is nil. After doing the function, I tried to do print the name like so:
function DisplayObject(object, x, y, name)
object = display.newImageRect("Graphics/ImproveMenu/Wealth/Luxury/Buy/" ..name..".png", 96*6, 96)
object.x = x
object.y = y
object.name = name
scrollView:insert(object)
end
DisplayObject(DeckOfPlayingCards, centerX, -90, "DeckOfPlayingCards")
print(DeckOfPlayingCards.name)
It crashes and says that the value is nil.
Now, how can I exactly make my object with function that will be as I tried to write it like the first code? I hope someone can help me out.
DisplayObject(DeckOfPlayingCards, centerX, -90, "DeckOfPlayingCards")
I think you expect this to act as passing the name DeckOfPlayingCards to DisplayObject, but it's just passing nil because it's an undefined variable.
One option is to simply create the object in DisplayObject, return it, then assign it to DeckOfPlayingCards:
function DisplayObject(x, y, name)
local object = display.newImageRect(
"Graphics/ImproveMenu/Wealth/Luxury/Buy/" ..name..".png",
96*6, 96)
object.x = x
object.y = y
object.name = name
scrollView:insert(object)
return object
end
DeckOfPlayingCards = DisplayObject(centerX, -90, "DeckOfPlayingCards")
print(DeckOfPlayingCards.name)
The error message tells you what is wrong. You cannot index a nil value.
Therefor DeckOfPlayingCards must be nil.
Where do you initialize DeckOfPlayingCards? I understand that the first block of code is not part of your current script as you moved it into the new function DisplayObject.
Assuming that DeckOfPlayingCards is nil when you call DisplayObject(object, x, y, name) object is also nil within your function.
As lua only creates a local copy of the function parameters you set the local variable object to the return value of display.newImageRect...
This does not change the value of DeckOfPlayingCards!!! It is still nil.
What you do is the same as:
function DisplayObject(x, y, name)
local object = display.newImageRect("Graphics/ImproveMenu/Wealth/Luxury/Buy/" ..name..".png", 96*6, 96)
object.x = x
object.y = y
object.name = name
scrollView:insert(object)
end
Return object and store it in DeckOfPlayingCards to solve your problem.

Weird result comparing property values using reflection

Can someone explain why this is occurring? The code below was executed in the immediate window in vs2008. The prop is an Int32 property (id column) on an object created by the entity framework.
The objects entity and defaultEntity were created using Activator.CreateInstance();
Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType)
0
Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType)
0
Convert.ChangeType(prop.GetValue(entity, null), prop.PropertyType) == Convert.ChangeType(prop.GetValue(defaultEntity, null), prop.PropertyType)
false
I assume you're wondering why the third line prints false. If you want to know why the first two lines are printing 0, you'll have to post more code and tell us what you actually expected.
Convert.ChangeType returns object. Therefore when the property type is actually Int32 it will return a boxed integer.
Your final line is comparing the references of two boxed values. Effectively you're doing:
object x = 0;
object y = 0;
Console.WriteLine (x == y); // Prints False
You can use Equals instead - and the static object.Equals method handily copes with null references, should that be an issue:
object x = 0;
object y = 0;
Console.WriteLine (object.Equals(x, y)); // Prints True

Resources