Jump to content
  • Advertisement
ethancodes

C# assigning a property from an object in a list to a variable

Recommended Posts

Posted (edited)

I've got a problem with a piece of code and I'm not sure if I just have the syntax wrong or if I am doing something fundamentally wrong. Here is the line of code:

currentPosition = gridPositions[randomIndex].Id;

basically what's happening here is currentPosition is an int, gridPositions is a list of a custom class called GridSquare. Each GridSquare object contains a Vector3, a bool, and an int. the Int is Id. I'm trying to assign the Id int to the int currentPosition. What I'm getting instead is the index of gridPositions that we are currently on. Any ideas on why that would be, and if so how I can assign Id to currentPosition?

Edited by ethancodes
spelling

Share this post


Link to post
Share on other sites
Advertisement
Posted (edited)
1 hour ago, ethancodes said:

Here is the line of code:

This piece here is fine, it must be something else. I will show a step by step guide:

First you need a class for your GridSquare.

public class GridSquare {

	public bool Visible;
	public int Id; //Variables must be public to get them
	public Vector3 Position;
    //Constructor optional
	public GridSquare(int InId,Vector3 InPosition){
		Visible = true;
		Id = InId;
		Position = InPosition;
	}
}

Next we need to use that grid

	//1) Lets make 2 instances of the grid Squares
	GridSquare GridA = new GridSquare(1,new Vector3(0f,0f,0f));
	GridSquare GridB = new GridSquare(2,new Vector3(2f,2f,2f)); //These are for filing the array

	//2) Make array for holding grids
	GridSquare[] GridPositions = new GridSquare[2];
	//I am assigning each manually to keep things clear.
	GridPositions [0] = GridA;
	GridPositions [1] = GridB;

	//3) Function to Get a random value
	int RandomInt(){
     	 //All this does is convert the random float value to a int
      	 //with 50% chance
		float temp = Random.Range (0, 1f);//Using a already made random library
		if (temp > 0.5f) {
			return 1;
		}else{
			return 0;
		}
	}

	//4) Use Function ro get random value, can actually skip this
	int randomIndex = RandomInt();

	//5) Use all this in the way you showed
	int currentPosition = GridPositions[randomIndex].Id; //This gives me 1 for blockA and 2 for blockB

	//If what you want is the position it has to be done like this:
	vector3 currentPosition = GridPositions[randomIndex].Position;
	//Also we can skip step 4 like this:
	int currentPosition = GridPositions[RandomInt()].Id;//Because the function is a int

 

1 hour ago, ethancodes said:

I'm trying to assign the Id int to the int currentPosition. What I'm getting instead is the index of gridPositions that we are currently on.

So these are the possible problems I can think of:

  • You forgot to make Id public.
  • Your Id is exactly the same as the Index of the array?? I used 1 and 2 but if it was 0 and 1 it would be the same as the array index.
  • Id is a index and what you really want is the vector. Not the int Id. The vector is the position (X,Y) for 2D or (X,Y,Z) for 3D
  • Your randomIndex isn't really random.

There are millions of things that could be wrong. For more detailed help share your random function and GridSquare class.

Also explain if it is the grid ID you want or it's position.

Edited by Scouting Ninja

Share this post


Link to post
Share on other sites
public class GridSquare {

	public Vector3 GridPosition { get; set; }
	public bool IsOccupied { get; set; }
	public int Id { get; set; }



	public GridSquare (Vector3 position, bool occupied, int id)
	{
		GridPosition = position;
		IsOccupied = occupied;
		Id = id;
	}
}
Vector3 RandomPosition ()
		{
			if (gridPositions.All(c => c.IsOccupied == false))
			{
				//Declare an integer randomIndex, set it's value to a random number between 0 and the count of items in our List gridPositions.
			    randomIndex = Random.Range (1, gridPositions.Count);

				//Declare a variable of type Vector3 called randomPosition, set it's value to the entry at randomIndex from our List gridPositions.
				randomPosition = gridPositions [randomIndex].GridPosition;

				//Remove the entry at randomIndex from the list so that it can't be re-used.
				gridPositions[randomIndex].IsOccupied = true;

				currentPosition = gridPositions[randomIndex].Id;

				//Return the randomly selected Vector3 position.
				return randomPosition;
			} 

				CheckBorders(currentPosition);

				//Declare an integer randomIndex, set it's value to a random number between 0 and the count of items in our List gridPositions.
				randomIndex = Random.Range (1, gridOptions.Count);

				//Declare a variable of type Vector3 called randomPosition, set it's value to the entry at randomIndex from our List gridPositions.
				randomPosition = gridOptions [randomIndex].GridPosition;

				//Remove the entry at randomIndex from the list so that it can't be re-used.
				gridOptions[randomIndex].IsOccupied = true;

				currentPosition = gridPositions[randomIndex].Id;

				//Return the randomly selected Vector3 position.
				return randomPosition;	
			

		}

		void CheckBorders (int currentPosition)
		{
			gridOptions.Clear();

			if (gridPositions [currentPosition].GridPosition.x != 1)
			{
				if (gridPositions [currentPosition - 1].IsOccupied == false) 
				{
					gridOptions.Add(gridPositions[currentPosition - 1]);
				}
			}

			if (gridPositions [currentPosition].GridPosition.x != 20)
			{
				if (gridPositions [currentPosition + 1].IsOccupied == false) 
				{
					gridOptions.Add(gridPositions[currentPosition + 1]);
				}
			}

			if (gridPositions [currentPosition].GridPosition.y != 18)
			{
				if (gridPositions [currentPosition - 20].IsOccupied == false) 
				{
					gridOptions.Add(gridPositions[currentPosition - 20]);
				}
			}

			if (gridPositions [currentPosition].GridPosition.y != 30)
			{
				if (gridPositions [currentPosition + 20].IsOccupied == false) 
				{
					gridOptions.Add(gridPositions[currentPosition + 20]);
				}
			}
		
		}

So here is my GridSquare class and also my RandomPosition and CheckBorders methods. I'm using Id as a navigational property to navigate between the lists. The reason I needed this is so that when I place a brick on a grid space, I need to check above, below, and to the sides (CheckBorders()) to see if the positions are open. Each open position gets added to a second list. We then select a random one of those 4 options and that is when we want to grab the id to pass it back to the complete list of grid spaces. And I don't think it matters much, but my bool is used to check whether a brick has already been set there, basically the opposite of what you have done.

Share this post


Link to post
Share on other sites
Posted (edited)

The best thing you can do is to learn how to debug your code. If you step through the logic of your program you will be able to see what is actually happening and what values are being assigned where. I believe that is going to be the best thing here. It's hard for me to understand some of the logic without seeing more. For instance, in your CheckBorders method I am not sure what those magic numbers are or represent. If I remember from your previous questions those are the edges of the grid (and hence the name), but others looking at the code would not know this. You need to make constants to represent what those actually mean (GRID_MIN_X, GRID_MAX_X, GRID_MIN_Y, GRID_MAX_Y, etc.). Anyway, start a debug and step through your code. You will instantly be able to spot the issue.

Edited by AtomicWinter

Share this post


Link to post
Share on other sites
44 minutes ago, AtomicWinter said:

The best thing you can do is to learn how to debug your code. If you step through the logic of your program you will be able to see what is actually happening and what values are being assigned where.

I have already done this. That is how I figured out that I am getting the index of the list assigned and not the Id of the object at that index. The problem is I just don't know why it's doing that. It seems obvious to me from the first line of code that I posted that I should be assigning the Id to currentPosition, but for whatever reason that isn't happening. I've walked through all of this code and more step by step and can't find anything that's causing this.

Share this post


Link to post
Share on other sites

The first line of code you posted does exactly what it should, so the problem is elsewhere. You don't show us where you're setting these GridSquare ID values so we can't see if they are wrong or misleading in some way. If they are wrong then it might appear that the first line of code is getting the array index, just because the values happen to be the same.

Or, if you add GridSquares and give them an incrementing ID each time, then obviously it could end up being exactly the same as the array index by definition.

 

Also, a lot of these comments in your code are wrong, for example, where you say this:

//Declare a variable of type Vector3 called randomPosition
randomPosition = gridPositions [randomIndex].GridPosition;

...you're not declaring that variable, you're just overwriting its value. It must have been declared elsewhere.

 

Share this post


Link to post
Share on other sites

Ah I'm sorry, some of the comments may be out of date. I probably forgot to change them when I changed some of the code. I didn't even think about that before posting it.

 

I had a very large paragraph here explaining everything more clearly, but when I was almost done I think I may have realized what I did wrong. I should probably slap myself if this is the problem, but I think what I did was get my lists mixed up. In my RandomPosition method I set currentPosition to the randomIndex of the gridPositions list. I believe what I actually want is the randomIndex of the gridOptions list and then grab the Id from that location. That would explain why it appears to be working to you guys and not to me. Because it is working as you see it. I just simply overlooked my own mistake. And that would make sense why the Index and Id are the same. I will test this when I get home tonight but I'm almost positive that is the issue.

Share this post


Link to post
Share on other sites
5 hours ago, ethancodes said:

So here is my GridSquare class and also my RandomPosition and CheckBorders methods.

Only two things that look weird here:

randomIndex = Random.Range (1, gridPositions.Count);

Most random libraries gives Random.Range as a float. Meaning that (1:5) could result in 2.2235 that will be converted to 2 when it is used as a int. The pain is that this doesn't have a fair chance of a number landing but if it's only for testing it is fine.

if (gridPositions.All(c => c.IsOccupied == false))

No idea what gridPositions.All is an array, bool? How does it work?

To me it reads: If [Object] is equal or larger than [Object]'s bool. It should have given the error: "Cannot convert lambda to bool" I mean you are comparing c to the bool inside of c.

 

The rest of your code is working as expected. A example:

GridSquare GridA = new GridSquare(new Vector3(7f,7f,7f),false, 9999);//Position, IsOccupied, ID

debug.Print( GridA.Id ); //Returns 9999
debug.Print( GridA.IsOccupied ); //Returns False
debug.Print( GridA.GridPosition ); //Returns (7,7,7)

//Test with array:
GridSquare[] Grids = {GridA};

debug.Print( Grids[0].Id ); //Returns 9999
debug.Print( Grids[0].IsOccupied ); //Returns False
debug.Print( Grids[0].GridPosition ); //Returns (7,7,7)

 

2 hours ago, ethancodes said:

I am getting the index of the list assigned

I am really starting to think this is just a coincidence.

If your first grid has a ID of 0 and you add it into the array first, it will also have a Index of 0. So when you ask it for it's Index or ID both will return 0 because both IS 0.

To see if this is the problem set the ID to a number that will stand out

Share this post


Link to post
Share on other sites
Posted (edited)
20 minutes ago, Scouting Ninja said:

No idea what gridPositions.All is an array, bool? How does it work?

To me it reads: If [Object] is equal or larger than [Object]'s bool. It should have given the error: "Cannot convert lambda to bool" I mean you are comparing c to the bool inside of c.

That's C#'s lambda syntax. The All function returns true if the given predicate returns true for every element in the list, so this expression means "if (all grid positions are unoccupied)".

20 minutes ago, Scouting Ninja said:

I am really starting to think this is just a coincidence.

If your first grid has a ID of 0 and you add it into the array first, it will also have a Index of 0. So when you ask it for it's Index or ID both will return 0 because both IS 0.

I am inclined to agree. I'm not sure why this is an issue.

Edited by Oberon_Command

Share this post


Link to post
Share on other sites
1 minute ago, Oberon_Command said:

That's C#'s lambda syntax. The All function returns true if the given predicate returns true for every element in the list, so this expression means "if (all grid positions are unoccupied)".

Thanks for explaining this. At first it looked like gridPositions had a All variable.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!