• Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By BigJiggly
      Hello! So, I've been the leader of BJP for a while now. I'm a bit bored of taking the role I always take, leader. I was hoping someone out there is looking to forge a team maybe and needs a programmer. 
      I have experience mainly in the Unity engine(C# intermediate) and I have a very small amount of knowledge on Shaders, as well as experience on developing games(usually end up stuck in dev hell) and leading experience from my last team which at one point reached 11 people. I personally love the Unity engine and prefer to use it as it's the development environment I'm comfortable with. 
      I have used Unity for over a year and a few months, I'd consider myself an intermediate at the Engine, but to this day Unity still surprises me. 
      I live in the United Kingdom, I find it a bit strange to work with other programmers as the ones I've worked with tend to leave their code heavily unoptimised and I'm a on the go optimise kind of guy, I also like to get things done quickly.
       
      If you're a new team and need a programmer that has high levels of ambition and strives to maintain the motivation throughout the team, then I'm your guy. I don't care if you're just beginning because I'm all for helping people learn!
       
      To finish this off: I like to get things done and I like to get them done right the first time, if I fail I will do it again and again, etc, until I loose all motivation. So if you're a modeller or an artist, please don't leave me to do all the modelling/art as well as the programming and sound. I do have experience in all those areas but my main power is in programming and I'd prefer to keep it that way.
       
      [If this was posted in the wrong forum, sorry, I don't really know the layout of this website yet]
    • By Kristiyan21
      Hello guys,i am writing this topic to get to the opinion of more people.I have just released my first game for android(worked on it for about 5-6 months in my spare time) i used Unity framework and i am planning to make it a big project but i had to release 1.0 version so i am 100% sure i wouldn't quit the project at some time.What i am asking any of you guys is to give me your opinion about the game. What do you like,what you don't , is the ad too irritating?is the GUI okay?any information you might consider usefull for me would be helpful,thanks in advance!
      the game on google play:
      https://play.google.com/store/apps/details?id=com.KindieGames.PlaneDash
    • By ethancodes
      I've got a custom Brick class. I need at least one other type of Brick subclass, maybe more. These classes should do most of what the Brick class does, but have a bit of modified or added behavior. Normally I would assume inheriting from the Brick class would be the best choice for this, but when I tried to do it I was having some issues because of having to make additional instances of variables referencing manager objects. I'm not sure if I was just doing it wrong, or if maybe inheritance isn't the right solution here. Here is the Brick class:
      using System.Collections; using System.Collections.Generic; using UnityEngine; public class Brick : MonoBehaviour { public AudioClip crack; public Sprite[] hitSprites; public static int breakableCount = 0; public GameObject smoke; private LevelManager levelManager; private int timesHit; private bool isBreakable; private float delay = 1.5f; //Delay till bricks move down 1 row. private float timer = 0; // update ever frame and compare to delay. // Use this for initialization void Start () { isBreakable = (this.tag == "Breakable"); //keep track of breakable bricks if (isBreakable){ breakableCount++; } timesHit = 0; levelManager = GameObject.FindObjectOfType<LevelManager>(); } // Update is called once per frame void Update () { timer += Time.deltaTime; if (timer >= delay) { transform.Translate(0.0f, -1.0f,0.0f); timer = 0; } } void OnCollisionEnter2D (Collision2D collision) { if (collision.gameObject.tag == "EndScreen") { levelManager = GameObject.FindObjectOfType<LevelManager>(); levelManager.LoadLevel("Lose"); } AudioSource.PlayClipAtPoint (crack,transform.position); if (isBreakable) { HandleHits (); } } void HandleHits () { timesHit++; int maxHits = hitSprites.Length + 1; if (timesHit >= maxHits) { breakableCount--; levelManager.BrickDestroyed(); PuffSmoke(); Destroy (gameObject); } else { LoadSprites(); } } void LoadSprites () { int spriteIndex = timesHit - 1; if (hitSprites [spriteIndex] != null) { //if statement keeps it from loading nothing if level designer forgets to assign a sprite this.GetComponent<SpriteRenderer> ().sprite = hitSprites [spriteIndex]; } else { Debug.LogError("Brick sprite missing"); } } void PuffSmoke () { var smokePuff = Instantiate(smoke, transform.position, Quaternion.identity); var effect = smokePuff.GetComponent<ParticleSystem>().main; effect.startColor = GetComponent<SpriteRenderer>().color; } } What I need is for a different kind of brick to destroy all other adjacent bricks when the ball hits it. I considered just adding this functionality in to the brick class, and have it activate based on tags, but that didn't seem like the best solution. I'm open to any ideas. Thanks!
    • By Epicghost 505
      Hello,
      We are looking for people to be apart of a team, to help create a horror game we are looking for 3d modelers, coders, artist, animators, fx artist, level designers, and audio design, there will be a payment plan once release of game                                                                                                                                                                                                                                                                                              if your interested come join our discord                                                                                                                                                                                                                                                                         We hope to see you there
      https://discord.gg/6rcc6xr
      -Epicghost505
    • By ethancodes
      I'm having a weird issue with detecting a collision. I've tried everything I could find online but nothing seems to work. I have a brick object. It has a 2D Collider attached and I have also attached a 2D Rigidbody on it. I also have an EndScreen 2D Collider. The EndScreen 2D collider is tagged with "EndScreen". I am trying to detect when a brick collides with the end screen collider and simply print "game over" in the console. 
      This is my current code for this part of the program, it is attached to the bricks:
      void OnCollisionEnter (Collision2D collision) { if (collision.gameObject.tag == "EndScreen") { Debug.Log("Game over"); } } Several things have happened depending on the set up. If I have the rigidbody 2D set as static, my ball object can still collide with the bricks, but I get no Log message. If I set it to Kinematic or Dynamic, I get absolutely no interaction between the ball and the bricks, and nothing when the bricks pass through the collider. I have tried to set the collider to a trigger and use OnTriggerEnter2D, no change. I have tried to put the rigidbody on the EndScreen object and tried to set it's body type to all 3 settings, no change. The only thing I can think of that I have not done is put the script on the EndScreen object and switch the tag to the bricks. The reason I have not done this is because I will have several types of bricks, some of which will have different tags. 
       
      Please tell me somebody can see what I'm doing wrong here, because I'm losing my mind over something I feel should be ridiculously simple. Thanks.
  • Advertisement
  • Advertisement

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