XNA: Object reference not set to an instance of an object [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I'm currently working on a xna project, a 2D game. My problem is that when I want the bullet(poop) to appear after I pressed the Up key, i receive the error in the line which is giving the initial position to the Vector2 of my bullet(poop).
// for each bullet in the list, update it
foreach (Poop p in poopList)
{
p.Update(gameTime);
}
In the Poop class, in the update method, i have a case, depending on the direction in which the bullet should go:
Top (1)
Right (2)
Down (3)
Left (4)
case 1:
position = new Vector2(monitoPosition.X + monitoTexture.Width / 2 - poopTexture.Width / 2, monitoPosition.Y + monitoTexture.Height / 2);
position.Y = position.Y - speed;
if (position.Y <= 0 || position.Y >=500)
isVisible = false;
if (position.X <= 0 || position.X >= 800)
isVisible = false;
break;
So in the line, in which I assign a new position to the bullet(poop), it throws the error.
Please Help

A variable in your code is null, meaning you will get an Object reference not set an instance of an Object error, because it is basically nothing. See this StackOverflow question for more info.
Double check that all your variables are assigned to.
Assuming you are talking about this line:
position = new Vector2(monitoPosition.X + monitoTexture.Width / 2 - poopTexture.Width / 2, monitoPosition.Y + monitoTexture.Height / 2);
Make sure that monitoPosition and poopTexture are set. You can set a breakpoint on this line to pause the code, and hover over the variables to see if they are null.

Related

How can I fix Array index out of range Unity [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 3 years ago.
Array index is out of range in Unity, need some help!
void OnCollisionEnter2D(Collision2D col) {
rigidbody2D.velocity = new Vector2(0, 0);
transform.rotation = Quaternion.Euler (0, 0, headDownAngle);
if(!isDied) {
audios[1].Play();
animator.SetTrigger("dead");
iTween.ShakePosition(Camera.main.gameObject, new Vector3(0.3f, 0.3f, 0), 0.5f);
}
isDied = true;
isPlaying = false;
I don't see any other arrays being used (Unless one of your other functions use arrays) so it seems this line is causing the error:
audios[1].Play();
Remember Arrays are zero based so the first position in an array is actually 0, so if you are trying to get the first element do:
audios[0].Play().
If you are trying to get the second element, make sure audios has 2 elements.
Array index is out of range is an error caused when you try to use a part of an array that doesn't exist
example
float numOfTests = 2;
AudioSource[numOfTests] tests;
void Start()
{
tests[3].play();
}
since there are only 2 audio sources in the array we can access a third one because it doesn't exist.
I hope this is helpful. I used to code in unity put I moved over to c++ and writing custom engines so if my answer doesn't help that might because I haven't used unity in a year.

Host Data Object set to Null Reference Unity3D?

I am writing a multi player game. And doing a check OnGUI() that if there is any hostData do something.
if (hostData)
{
for (int i = 0; i < hostData.Length; i++)
{
GUI.Button (new Rect (btnX * 2f + btnW, btnY * 1.2f + (btnH * i), btnW * 3f, btnH * 0.5f), hostData [i].gameName);
}
}
But I have filled host Data on a button click, while on the other hand OnGUI is always looking for if(hostData) that is why it gives Null reference.
How i check this if statement other then this. Help me out.
if (hostData) only works if hostData is a game object, or component. This is because Unity implemented the implicit operator.
In other words, if (gameObject) works as a shortcut to if (gameObject != null).
This doesn't work when you are using something else then game objects or components, such as arrays or lists. In that case you have to use != null.

IndexOutOfRangeException only on Mac OS X Standalone

I'm getting an IndexOutOfRange exception in my game, but only in a standalone build on Mac OS X. It works fine in the Unity editor on both Windows and OSX, and works fine as a standalone on Windows and Android. On OSX however, I get the following exception:
IndexOutOfRangeException: Array index is out of range.
at WorldController.InstantiateChunk (Vector2i pos, .MeshBuildInfo[] meshes) [0x00072] in /Users/sargunster/Code/Unity Projects/block-game/Assets/Scripts/World/Objects/WorldController.cs:226
at WorldController.FixedUpdate () [0x00060] in /Users/sargunster/Code/Unity Projects/block-game/Assets/Scripts/World/Objects/WorldController.cs:79
Here's the relevant function:
void InstantiateChunk(Vector2i pos, MeshBuildInfo[] meshes)
{
float worldX = pos.x * World.CHUNK_SIZE - .5f;
float worldZ = pos.z * World.CHUNK_SIZE - .5f;
// for each chunk in the column
for (int y = 0; y < World.WORLD_HEIGHT; y++)
{
float worldY = y * World.CHUNK_SIZE - .5f;
// instantiate the chunk
Vector3 position = new Vector3(worldX, worldY, worldZ);
string name = System.String.Format(" Chunk at ({0}, {1}, {2})", pos.x, y, pos.z);
// THIS IS WHERE IT HAPPENED
ChunkRenderer opaque = MakeChunk(position, "Opaque" + name, meshes[y].opaque, opaqueMaterial);
ChunkRenderer transparent = MakeChunk(position, "Transparent" + name, meshes[y].transparent, transparentMaterial);
Vector3i chunkPos = new Vector3i(pos.x, y, pos.z);
opaqueInstances.Add(chunkPos, opaque);
transparentInstances.Add(chunkPos, transparent);
}
}
I followed the references to find where meshes was instantiated, and it should have a length of WORLD_HEIGHT.
MeshBuildInfo[] meshes = new MeshBuildInfo[World.WORLD_HEIGHT];
So, I went in to the debugger to see the exact value of the variable when the exception happened. Debugger output:
> meshes
Evaluation failed.
> 2+2
4
> meshes.Length
Evaluation failed.
> y
0
> position
{(-7168.5, -0.5, 4079.5)}
The index is 0, I can evaluation expressions just fine... except for the array that's not working. I can't get the length of it or its value.
I don't know how to solve this issue. What does "Evaluation Failed" mean? How can the index be out of bounds? Why is this only happening on OSX? How do I fix it?
World.WORLD_HEIGHT is a constant with a value of 16.
After days of being frustrated by this issue, I've finally solved it (sort of). It only occurs when the game is built as x86_64 or Universal. Changing the architecture setting to x86 solved it. Must be a Unity bug.

get center polygon C# [duplicate]

This question already has answers here:
What is the fastest way to find the "visual" center of an irregularly shaped polygon?
(15 answers)
Closed 9 years ago.
what algorithm that i can use to get the center of polygon (red point)
case 1 : i try with maxX, maxY, minX, minY and i got the wrong point (black point)
case 2 : i try to get the second max and min coordinate X and Y, but i got problem with the polygon which have point less than 5
case 3 : i add if point count < 5 then use case 1 else use case 2 but i got some error for some polygon
can you tell me the right algorithm for me??
note :
explaination for 4th picture
//ma mean max, mi mean min, X1 mean first, X2 mean second
maX1 = maX2 = maY1 = maY2 = 0;
miX1 = miX2 = miY1 = miY2 = 2000;
//aCoor is array of coordinate, format = {x1,y1,x2,y2,x3,y3,x4,y4,...}
for(int i=0; i<aCoor.count(); i+=2)
{
//point is list of point
point.Add(aCoor[i],aCoor[i + 1]);
//this to get second max X
if(maX2 < aCoor[i])
{
maX2 = aCoor[i];
//this to get first max x
if(maX1 < maX2) {maX1 += maX2; maX2 = maX1 - maX2; maX1 -= maX2;}
}
//this to get second min X
if(miX2 > aCoor[i])
{
miX2 = aCoor[i];
//this to get first min x
if(miX1 > miX2) {miX1 += miX2; miX2 = miX1 - miX2; miX1 -= miX2;}
}
//this to get second max Y
if(maY2 < aCoor[i + 1])
{
maY2 = aCoor[i + 1];
//this to get first max x
if(maY1 < maY2) {maY1 += maY2; maY2 = maY1 - maY2; maY1 -= maY2;}
}
//this to get second min Y
if(miY2 > aCoor[i + 1])
{
miY2 = aCoor[i + 1];
//this to get first min x
if(miY1 > miY2) {miY1 += miY2; miY2 = miY1 - miY2; miY1 -= miY2;}
}
}
if(point.Count < 5)
{
Xcenter = (maX1 + miX1) / 2;
Ycenter = (maY1 + miY1) / 2;
}
else
{
Xcenter = (maX2 + miX2) / 2;
Ycenter = (maY2 + miY2) / 2;
}
this how far i do
What you are looking for is not the geometric center (or centroid) of the polygon, but the center of the portion of the polygon's axis of symmetry which lies inside the polygon. Let me edit one of your examples to demonstrate:
Edited example
Do you see what I mean?
I picked this example because it demonstrates another flaw in your thinking; this is two polygons, and each of them produce a point that fits the qualifications you're looking for. In your example you just arbitrarily chose one of them as the point you want. (I have seen your edited fourth example; it still has two interiors and does not change my point.)
In any case, what you're looking for is actually the solution to two problems: first, how to find an axis of symmetry for a polygon; second, finding a line segment on that axis of symmetry which also lies in the interior of the polygon. After that, finding the center of that segment is trivial.
I can't post any more links, but there's a paper by P. Highnam out of Carnegie Mellon University entitled Optimal Algorithms for Finding the Symmetries of a Planar Point Set which could help with the first problem, it's a bit involved so I won't explain it here. The second problem just boils down to testing each line segment to see if it contains a point of intersection with a line along the axis of symmetry running through the figure's centroid. Assuming your polygon only has one interior (read: is not like your fourth example), you should get two points. Average them and you have your center.

Implement bouncing balls collision detection

I have a bouncing ball application and I have to extend it to prevent overlapping of the balls.
When ball overlaps another, they should move away as in real life.
I have to extend the given MoveBall method:
private void MoveBall()
{
prevX = x;
prevY = y;
x += xVelocity;
y += yVelocity;
// Is there too closed ball?
foreach (Ball ball in parentForm.balls)
{
distance = Math.Sqrt(Math.Pow((double)(ball.prevX - prevX), 2) +
Math.Pow((double)(ball.prevY- prevY), 2));
overlap = ((radius + ball.radius) - distance);// +ball.radius;
if (ball.id != this.id &&
ball.id != lastID &&
overlap > 0)
{
lastID = this.id;
if (xVelocity > 0) // roading right
{
xVelocity = -xVelocity;
x -= xVelocity - ball.xVelocity;
}
else if (xVelocity <= 0) // roading left
{
xVelocity = -xVelocity;
x += xVelocity + ball.xVelocity;
}
if (yVelocity > 0)
{ // going up
yVelocity = -yVelocity;
y -= yVelocity - ball.yVelocity;
}
else if (yVelocity <= 0) // down
{
yVelocity = -yVelocity;
y += yVelocity + ball.yVelocity;
}
}
}
// ***********************************************
// ***************** END MY CODE *****************
if (x > parentForm.Width - 10 - (radius) || x < 0)
{
if (x < 0) x = 0;
if (x > parentForm.Width - 10) x = parentForm.Width - 10 - radius;
xVelocity = -xVelocity;
}
if (y > parentForm.Height - 40 - (radius) || y < 0)
{
if (y < 0) y = 0;
if (y > parentForm.Height - 40) y = parentForm.Height - 40 - (radius);
yVelocity = -yVelocity;
}
}
x,y, xVelocity, yVelocity, radius, prevX, prevY declared as int.
overlap, distance as double.
When 2 overlap, they are getting stuck. Why?
Unfortunately, I can't upload all source code because there are lot of modules.
I'm using Visual C# Express 2010.
As no Question is asked explicitly, I will assume the question "Why are the balls sticking together?"
You have only shown one loop in source code, that's not enough ;-) To check all possible collisions, you need to check n*(n-1)/2 possible collisions. That is normally done with two loops. You have to put in careful measures to avoid handling the same collision twice.
The reason that your balls get stuck is that you handle the same collision multiple times. For example two balls colliding exactly horizontal: The left one has velocity 5 and x-position of 100. The other one shall have a position of 110 and velocity of -6. When the collision happens:
x is set to 105.
Collision detected: x is set to 104 and velocity to -5.
The other Ball handles the same collision:
He moves according to his velocity to position 104.
Collision handling: His velocity becomes 6 and position becomes 105.
The balls were at 100 and 110 resp. and have been moved to 104 and 105. While the velocities are now pointing away from each other, the collision handling in the following step will invert them again. So the positions are close together and the velocities are changing sign every frame. The balls seem "stuck to each other".
I hope the answer helps you to understand your problem. For a better implementation of an elastic collision (that handles each collision exactly once) look here: Ball to Ball Collision - Detection and Handling
Having stumbled upon similar issues when I made my first attempts at collision detection algorithms, I'll try to describe what I think is the problem here.
Maybe the balls move fast enough so that, before collision is even detected by your code, they are already partially "inside" each other. When collision detection comes and notices that, it does what it's supposed to do: change the planned trajectories of the objects according to the details of the collision that just happened. The problem is that, because these objects got sort-of "merged" before collision detection caught them, they can't get unstuck because collision detection is fired again, trapping them with each other.
If this is the source of the problem, then maybe the above code would work with a small enough velocity vector. Of course, that's not a real solution, but if it does work for very small velocities, it probably confirms my hypothesis and you have some idea regarding how to proceed.

Categories