Why are my for loops not working in Unity2D? [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 24 days ago.
Improve this question
I am trying to make a chess variation, and to make the squares for the board, I am trying to loop through the files and ranks, and adding the square to an array, as well as logging that a colored square was made. I get the same two errors for each loop.
The errors are:
"Assets\Scripts\BoardManager.cs(17,28): error CS0029: Cannot implicitly convert type 'int' to 'bool'
Assets\Scripts\BoardManager.cs(17,36): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
Here is the code:
` using System;
using UnityEngine;
public class BoardManager : MonoBehaviour
{
public Color whiteSquare = new Color(1f, 1f, 1f);
public Color blackSquare = new Color(0f, 0f, 0f);
// Start is called before the first frame update
void Start()
{
Square[] squares = new Square[36];
int squareNumTemp = 1;
Color squareColorTemp;
for (int rank = 1; rank++; rank <= 6)
{
for (int file = 1; (int)file++; file <= 6)
{
if ((file + rank) % 2 != 0)
{
squareColorTemp = blackSquare;
Debug.Log("Black square made");
} else
{
squareColorTemp = blackSquare;
Debug.Log("White square made");
}
squares[squareNumTemp] = new Square(squareNumTemp, squareColorTemp);
}
}
}
// Update is called once per frame
void Update()
{
}
}
class Square
{
public int squareNum;
public Color squareColor;
public Square (int numIn, Color colorIn)
{
this.squareNum = numIn;
this.squareColor = colorIn;
}
}`
I tried to make the file and rank variables integers using (int) but that did not work. I also cannot decipher what the second error means.

Your for loop is formed wrong.
It is expecting a condition and not int (you're returning integer with rank++)
for (int rank = 1; rank <= 6; rank++)
{
for (int file = 1; file <= 6; file++)
{
"Assets\Scripts\BoardManager.cs(17,28): error CS0029: Cannot implicitly convert type 'int' to 'bool'
Error CS0029 is type conversion error
Error CS0201 is invalid statement
for loops in C#
You can see from the W3 website, statement 2 defines the condition (bool) and statement 3 is the one executed every loop (rank++)
So just turning those two around fixes your issue

Related

How to program the Sudoku game logic in Unity3D [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am trying to make a Sudoku game in Unity3D but I'm currently stuck on the logic behind the game. (checking if all the numbers in the same subgrid, row and column are different)
I have been able to get a script that generates the whole grid running, both for a 2x2, 2x3 and a 3x3 level. The part that I am stuck on is making the 2D Array to hold the selected values for all subgrids. I can also provide the full GenerateGrid script if it's needed, but any help apart from that would be of help.
(Note: I have tried my best to research as much as I can about this, but none of the stuff I found online was about a Unity3D version of the game, only 2D ones)
Thanks!
Something like this? The board is a 9x9 grid. Skip the multidimensional syntax as it just complicates things (in my opinion).
(Pseudocode - I haven't tried compiling this.)
int[] board = new int[9*9];
/// note that coordinates are zero-based. So, rows, columns. etc. go from 0..8, not 1..9
int getCell(int x, int y)
{
return board[y * 9 + x];
}
bool colIsValid(int x)
{
var digitsFound = new bool[9];
for(int y=0; y < 9; ++y)
{
var cellValue = getCell(x,y);
if (cellValue > 0)
{
if (digitsFound[cellValue])
return false;
digits[cellValue] = true;
}
}
return true;
}
bool rowIsValid(int y)
{
var digitsFound = new bool[9];
for(int x=0; x < 9; ++x)
{
var cellValue = getCell(x,y);
if (cellValue > 0)
{
if (digitsFound[cellValue])
return false;
digits[cellValue] = true;
}
}
return true;
}
// determine if the 3x3 subgrid containing cell (x,y) is valid.
bool subGridIsValid(int cellX, int cellY)
{
var minX = (cellX / 3) * 3;
var maxX = minX + 3;
var minY = (cellY / 3) * 3;
var maxY = minY + 3;
var digitsFound = new bool[9];
for(var j=minY; j < maxY; ++j)
{
for(var i = minX; i < maxX; ++i)
{
var cellValue = getCell(i,j);
if (cellValue > 0)
{
if (digitsFound[cellValue])
return false;
digitsFound[cellValue] = true;
}
}
}
return true;
}
You can represent yourself a Sudoku as a grid (with rows and columns). Each grid cell is itself a subgrid (with sub-rows and sub-columns)
To check if the user solved the Sudoku you have 3 conditions
there is no duplicate number in a subgrid itself
there is no duplicate number in a same sub-row for every cell on the same row
there is no duplicate number in a same sub-column for every cell on the same column
From there we can begin to work. I would recommend to use two sets of bidimensionnal arrays. One for the main grid and a second for each sub-grids
So basically...your grid declaration may looks like this int[,][,] sudoku and sudoku[1,2][3,4] will access the row 1, column 2, sub-row 3, sub-column 4 if that makes sense
So to check game conditions:
test every sub-cells of sudoku[1,2][i,j] to make sure there is no duplicated numbers in the grid cell [1,2]
test every sub-cells for sudoku[1,i][2,j] to make sure there is no duplicated number in the sub-column 2 of the column 1
test every sub-cells for sudoku[i,1][j,2] to make sure there is no duplicated number in the sub-row 2 of the row 1
You should find a better optimisation to check the grid rather than brute force it sub-cell by sub-cell but I leave it up to you.
Hope that helped ;)

Why I'm getting null or index out of bound? [duplicate]

This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
In this case animators contains 3 items.
But let' say I don't know how many items there is. Could be 3 or 30.
I can get the "medea_m_arrebola" index fine but how do I get the rest indexs ?
I tried on this line also 2 and now 1 : But getting exception IndexOutOfRangeException: Index was outside the bounds of the array.
soldiers_indexs = new int[1];
And if not using this line I'm getting null on the line :
soldiers_indexs[i] = i;
How can I get the rest items indexs ?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OpenningScene : MonoBehaviour
{
[Header("Animators")]
public Animator[] animators;
[Space(5)]
[Header("Movement Settings")]
public Transform target;
public float movingSpeed = 1f;
public bool slowDown = false;
[Space(5)]
[Header("Rotation Settings")]
public float rotationSpeed;
public DepthOfField dephOfField;
public float waitingAnimation;
public float startConversation;
private Vector3 targetCenter;
private bool startWaitingAnim = true;
private bool endRot = false;
private int medea_m_arrebola_index;
private int[] soldiers_indexs;
// Use this for initialization
void Start()
{
targetCenter = target.GetComponent<Renderer>().bounds.center;
soldiers_indexs = new int[1];
for (int i = 0; i < animators.Length; i++)
{
animators[i].SetFloat("Walking Speed", movingSpeed);
if(animators[i].name == "medea_m_arrebola")
{
medea_m_arrebola_index = i;
}
else
{
soldiers_indexs[i] = i;
}
}
}
Because C# is not Javascript.
Your code with soldiers_indexs[i] = i; would work perfectly in Javascript, even if the end result is hard to understand. However, an array in C-type languages is a defined data structure with lower and upper bounds. C# does not allow you to do things that appear to make no sense.
As it's not clear from your code what you are attempting to do, I can't advise a forward path. However, it is clear that using the index variable i to refer to a place on an array that you are not iterating is a mistake.
Generally, in C#, we use more general-purpose data structures such as a List<T>. In addition, I do not recommend for loops. A foreach loop nearly always makes more sense, and is always easier to read.

It says I need to add "," in C#, Where do I put it? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I tried to make a FizzBuzz code in C# but the error code it gives me is that I'm missing a " , " somewhere but I can't find where to place it
Also I know there are other underlying programs in the code I just need this fixed so I can compile and fix them
using System;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
float i = 0;
if (i != 101)
{
i = i + 1;
float i3 = i / 3;
float i5 = i / 5;
float i15 = i / 15;
string Print = Convert.ToString(i)
else ; if ((i3 %1) > 0)
{
string Hold = ("Fizz");
Print = Hold;
}
else if ((i3 % 1) > 0)
{
string Hold = ("Buzz");
Print = Hold;
}
else if ((i15 % 1) > 0)
{
string Hold = ("FizzBuzz");
Print = Hold;
}
Console.WriteLine(Print)
; Console.WriteLine("Done");
Console.ReadLine();
}
}
}
}
Fizz-Buzz was originally a game designed to teach children division, it worked like this:
The player designated to go first says the number "1", and each player counts one number in turn. However, any number divisible by three is replaced by the word fizz and any divisible by five by the word buzz. Numbers divisible by both become fizz buzz.
So your program has a number of errors, first one is that you use an if where you should be looping. Your first if statement:
if (i != 101)
{ ... }
Really doesn't do anything. You set i=0 in the previous statement, so i will never equal 101. What you need to do instead is a while loop:
float i = 0.0f;
while (i < 101.0f)
{
//Run the program
}
The next problem you have is that it is OK to use i for an iterator, or even x or y if iterating dimensions, but that is really where the single letter variables should stop. Use meaningful names, it makes things much easier:
So, again we need to check if i is divisible by 3, 5, or both. We can do that with simple boolean variables, no need to make things more complicated.
bool divisibleBy3 = i % 3.0f == 0.0f;
bool divisibleBy5 = i % 5.0f == 0.0f;
The next thing you have wrong is that you have ; in strange places, namely you seem to mix them in on separate lines. Try not to do this. There are very few reasons that a ; should not be on the end of every code line, and there should really only be one per line. So this:
string Print = Convert.ToString(i)
else ; if ((i3 %1) > 0)
Is an error because it treats it all as one line until it hits the ;, so your code really becomes:
string Print = Convert.ToString(i) else;
if (...)
And it should be obvious what the problem with that is.
The last problem I'll touch on really isn't a code issue, but a form one. You have a lot of "holding" variables that don't do anything but temporarily put things in places then put them somewhere else, like this:
if ((i3 %1) > 0)
{
string Hold = ("Fizz");
Print = Hold;
}
What is the purpose of Hold? You could just write:
Print = "Fizz";
The ( and ) are also unnecessary. So lets take all these lessons and put them into the Fizz-Buzz program:
int i = 0; //No reason to use float here, int is just fine
while (i <= 100)
{
bool divisibleBy3 = i % 3 == 0;
bool divisibleBy5 = i % 5 == 0;
if (divisibleBy3 && divisibleBy5)
Console.WriteLine("FizzBuzz");
else if (divisibleBy3)
Console.WriteLine("Fizz");
else if (divisibleBy5)
Console.WriteLine("Buzz");
else
Console.WriteLine(i.ToString());
i += 1;
}
Console.WriteLine("Done");
Console.ReadKey(true);
Or, it can be written with a for loop:
for (int i = 0; i <= 100; i++)
{
bool divisibleBy3 = i % 3 == 0;
bool divisibleBy5 = i % 5 == 0;
if (divisibleBy3 && divisibleBy5)
Console.WriteLine("FizzBuzz");
else if (divisibleBy3)
Console.WriteLine("Fizz");
else if (divisibleBy5)
Console.WriteLine("Buzz");
else
Console.WriteLine(i.ToString());
}
Console.WriteLine("Done");
Console.ReadKey(true);
So you can see how giving variables meaningful names, paying attention to indenting/formatting, and understanding of the ; can help you make debugging easier. Clean, well formatted code is easy to read and debug, and giving variables meaningful names means you can tell what the purpose is without having to read through the entire use of the variable.
Note: Some programmers will argue that Fizz-Buzz can be condensed down to 1-3 lines of code. While it is possible, I would argue that it doesn't demonstrate good programming practices. There is a big difference between readable code that can be maintained, and just making something short for the sake of it being short.

2D Array IndexOutOfRange Issue in Unity C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have 35 Tile objects and I'm trying to put them into a 2D array (and list) but I keep getting an IndexOutofRange error when populating the array. The code I'm using is:
private Tile[,] AllTiles = new Tile[5,7];
private List<Tile> EmptyTiles = new List<Tile>();
// Use this for initialization
void Start () {
Tile[] AllTilesOneDim = GameObject.FindObjectsOfType<Tile> ();
foreach (Tile t in AllTilesOneDim) {
// Fill 2D Array AllTiles
AllTiles [t.indRow, t.indCol] = t;
// Fill List with all tiles
EmptyTiles.Add (t);
}
}
I should note that each Tile object contains an int for indRow between 0-4 and an int for indCol between 0-6.
Try adding some defensive code to check the range before adding the tile to the 2D array. Like:
int rows = AllTiles.GetLength(0);
int cols = AllTiles.GetLength(1);
int indRow = 0;
int indCol = 0;
foreach (Tile t in AllTilesOneDim) {
indRow = t.indRow;
indCol = t.indCol;
if (indRow >= 0 && indRow < rows
&& indCol >= 0 && indCol < cols)
{
// Fill 2D Array AllTiles
AllTiles[indRow, indCol] = t;
}
}
Use the debugger to step into this path and see what you find. The indRow and indCol values must sometimes be outside of your specified ranges of 5 (0 to 4) and 7 (0 to 6). Remember indexes are zero based and the Length returns the total number of items so we must subtract one to find the correct index (or use "index less than rows or cols" like I did in the if statement).
GetLength() Method:
https://msdn.microsoft.com/en-us/library/system.array.getlength.aspx
https://stackoverflow.com/a/4260228/8094831

C# - only assignment call increment decrement await and new object expressions can be used as a statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I got the the following error when I use a code:
only assignment call increment decrement await and new object expressions can be used as a statement
I get this when I use this code:
for (int i = enemies.Count - 1; i >= 0; i-)
{
enemies[i].Update(gameTime);
if (enemies[i].Active == false)
{
enemies.RemoveAt(i);
}
}
PS: I get the error on I- first line : I >= 0; I-
Use i-- to decrement. Use two minuses.
This is the equivalent of i -= 1; or i = i - 1; It is the expression that progresses the iteration
It could be a class level issue, but more likely it is that you are not decrementing i properly.
It should read:
for (int i = enemies.Count -1; i >= 0; i--) { // etc... }
You are just using i- which is incorrect.
Your error located in this row:
for (int i = enemies.Count - 1; i >= 0; i-)
You need to use this code:
for (int i = enemies.Count - 1; i >= 0; i--)
You probably meant i--
for (int i = enemies.Count - 1; i >= 0; i--)
The error message indicates that some piece of code is not a complete statement. For this line, there are 3 "statements":
int i = enemies.COunt -1;
i >= 0;
i-;
If you imagine writing these lines outside of the for loop declaration, you immediately see that i- is not a complete line of code.
only assignment call increment decrement await and new object expressions can be used as a statement
Translated into easy wording:
Only assignemnt (variable = value), call ( DoSomething() ), increment (i++), decrement, (i--), await (await DoSomethingAsync() ), and new object (new List<Object>() ) expression can be used as a statement
Your problem is with your for statement, you only have i- not i--.
Since i- is not an operation it is viewed as a statement.

Categories

Resources