I want to access game objects (sprites) in my code in an Array but I have no idea how to do that, I am new to C#.
This is my testing code, but I am not getting any values:
void Start()
{
Sprite[] countries = Resources.LoadAll<Sprite>("MAPS");
sr = GetComponent<SpriteRenderer>();
names = new string[countries.Length];
for (int i = 0; i < names.Length; i++)
{
names[i] = countries[i].name;
//0 = red
//1 = green
if (UnityEngine.Random.Range(0, 2) == 0)
{
this.GetComponent<SpriteRenderer>().color = Color.red;
}
else
{
this.GetComponent<SpriteRenderer>().color = Color.green;
}
}
}
Instead of using this keyword:
if (UnityEngine.Random.Range(0, 2) == 0)
{
this.GetComponent<SpriteRenderer>().color = Color.red;
}
else
{
this.GetComponent<SpriteRenderer>().color = Color.green;
}
try to use countries[i]:
if (UnityEngine.Random.Range(0, 2) == 0)
{
countries[i].GetComponent<SpriteRenderer>().color = Color.red;
}
else
{
countries[i].GetComponent<SpriteRenderer>().color = Color.green;
}
Related
I'm setting up a windowsform that pings all my IP's at work and changes the button.BackColor accordingly.
Ping pingClassxx = new Ping();
PingReply pingxx = pingClassxx.Send("192.168.xx.xx");
if (pingxx.Status == IPStatus.Success)
{
button1.BackColor = Color.Green;
button1.Text = "SQL Server | Online";
}
else
{
button1.BackColor = Color.Red;
button1.Text = "SQL Server | Offline";
}
Now I'm trying to do this to multiple machines so I went like this:
private void timer0_Tick(object sender, EventArgs e)
{
timer1.Stop();
int iCount0 = 0;
string[] arr = new string[8];
arr[0] = "192.168.x.xx"; //button0
arr[1] = "192.168.x.yy"; //button1
arr[2] = "192.168.x.zz"; //button2
arr[3] = "192.168.x.xy"; //button3
arr[4] = "192.168.x.xz"; //button4
arr[5] = "192.168.x.yx"; //button5
arr[6] = "192.168.yy.yz"; //button6
arr[7] = "192.168.x.ww"; //button7
for (int I = 0; I < arr.Length ; I++)
{
// Ping
string s = arr[I];
Console.WriteLine(s);
Ping pingClassx = new Ping();
PingReply pingx = pingClassx.Send(arr[I]);
if (pingx.Status == IPStatus.Success)
{
[What do I do here?].BackColor = Color.Green;
}
else
{
[What do I do here?]BackColor = Color.Red;
}
// Loading Bar
iCount2 += 1;
progressBar0.Value = iCount2 * 100 / 8;
label0.Text = iCount2 + "/8";
}
timer1.Start();
}
How can I loop this?
I could just repeat the code but I am sure there is a fancier way to do it.
If you want to Change the Color only Of Your Form Buttons then try This :
foreach(Button c in Form.Controls){
if (pingx.Status == IPStatus.Success)
{
c.BackColor = Color.Green;
}
else
{
c.BackColor = Color.Red;
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PrefabReplace : EditorWindow
{
[SerializeField] private GameObject prefab;
private bool selectionChanged;
private string objectsToSearch = "";
private List<GameObject> foundObjects = new List<GameObject>();
private List<GameObject> duplicatedObjects = new List<GameObject>();
private bool searched = false;
private int count = 0;
private int countChilds = 0;
private bool countChildren = false;
[MenuItem("Tools/Prefab Replace")]
static void CreateReplaceWithPrefab()
{
int width = 340;
int height = 300;
int x = (Screen.currentResolution.width - width) / 2;
int y = (Screen.currentResolution.height - height) / 2;
GetWindow<PrefabReplace>().position = new Rect(x, y, width, height);
}
private void OnGUI()
{
Searching();
GUILayout.Space(50);
Replacing();
}
private void Searching()
{
GUI.Label(new Rect(10, 20, 150, 20), "Search by name");
objectsToSearch = GUI.TextField(new Rect(90, 60, 150, 20), objectsToSearch, 25);
if (objectsToSearch != "")
{
GUI.enabled = true;
}
else
{
GUI.enabled = false;
}
GUILayout.Space(40);
if (GUILayout.Button("Search"))
{
foundObjects = new List<GameObject>();
duplicatedObjects = new List<GameObject>();
countChildren = true;
countChilds = 0;
count = 0;
foreach (GameObject gameObj in GameObject.FindObjectsOfType<GameObject>())
{
if (gameObj.name == objectsToSearch)
{
count += 1;
foundObjects.Add(gameObj);
}
}
if (foundObjects.Count > 0)
{
searched = true;
}
else
{
searched = false;
}
}
GUI.enabled = true;
if (count > 0)
GUI.TextField(new Rect(90, 85, 60, 15), count.ToString(), 25);
if (foundObjects.Count > 0 && countChildren == true)
{
for (int i = 0; i < foundObjects.Count; i++)
{
if (foundObjects[i].transform.childCount > 0)
{
countChilds += foundObjects[i].transform.childCount;
//GameObject duplicate = Instantiate(foundObjects[i]);
//duplicate.name = foundObjects[i].name;
//duplicatedObjects.Add(duplicate);
}
}
countChildren = false;
}
GUI.enabled = true;
if (countChilds > 0)
GUI.TextField(new Rect(90, 105, 60, 15), countChilds.ToString(), 25);
GUILayout.Space(100);
if (foundObjects.Count > 0)
EditorGUILayout.LabelField("Test");
}
private void Replacing()
{
GUILayout.Space(20);
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label("Replacing");
GUILayout.Space(20);
prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", prefab, typeof(GameObject), false);
var selection = Selection.objects.OfType<GameObject>().ToList();
if (selectionChanged)
{
if (selection.Count == 0)
GUI.enabled = false;
for (var i = selection.Count - 1; i >= 0; --i)
{
var selectedObject = selection[i];
if (prefab != null && selection.Count > 0 &&
selectedObject.scene.name != null
&& prefab != PrefabUtility
.GetCorrespondingObjectFromSource(selectedObject))
{
GUI.enabled = true;
}
else
{
GUI.enabled = false;
}
}
}
else
{
GUI.enabled = false;
}
if (GUILayout.Button("Replace"))
{
InstantiatePrefab(selection);
selectionChanged = false;
}
GUILayout.Space(10);
GUI.enabled = true;
EditorGUILayout.LabelField("Selection count: " + Selection.objects.OfType<GameObject>().Count());
GUILayout.EndVertical();
}
private void OnInspectorUpdate()
{
Repaint();
}
private void OnSelectionChange()
{
selectionChanged = true;
}
private void InstantiatePrefab(List<GameObject> selection)
{
if (prefab != null && selection.Count > 0)
{
for (var i = selection.Count - 1; i >= 0; --i)
{
var selected = selection[i];
SceneManager.SetActiveScene(SceneManager.GetSceneByName(selected.scene.name));
var prefabType = PrefabUtility.GetPrefabType(prefab);
GameObject newObject;
if (prefabType == PrefabType.Prefab)
{
newObject = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
}
else
{
newObject = Instantiate(prefab);
newObject.name = prefab.name;
}
if (newObject == null)
{
Debug.LogError("Error instantiating prefab");
break;
}
Undo.RegisterCreatedObjectUndo(newObject, "Replace With Prefabs");
newObject.transform.parent = selected.transform.parent;
newObject.transform.localPosition = selected.transform.localPosition;
newObject.transform.localRotation = selected.transform.localRotation;
newObject.transform.localScale = selected.transform.localScale;
newObject.transform.SetSiblingIndex(selected.transform.GetSiblingIndex());
Undo.DestroyObjectImmediate(selected);
}
}
}
}
The searching part find object/s in the hierarchy and if there are any childs it's counting them too.
The replacing part replace a prefab with selection of objects. If for example I selected 20 Cubes and clicked the Replace button it will replace the selected Cubes with the prefab with the same position,rotation,scaling the cubes was.
But it's not replacing childs if there are any.
I need somehow when searching to add to a List/s the parent and childs and keep the hierarchy of each parent and his childs and then when clicking the replace button to replace it will the searching results objects and not with the selection like now and including the childs.
Example if my Hierarchy looks like this:
Cube1
Cube1
Cube1
Cube1
Cube1
Cube1
If I'm searching for Cube1 I shold find 6 Cubes and two of them childs.
And if for example I will replace them with Sphere prefab the Hierarchy should looks like:
Sphere
Sphere
Sphere
Sphere
Sphere
Sphere
What I need to do is to combine the searching part with the replacing part and make that the replacing will include also childs.
You could try something like this:
void ChangeObjectRecursively(Transform t)
{
for (int i = 0; i < t.childCount; i++)
{
ChangeObjectRecursively(t.getChild(i));
}
ChangeObject(t.gameObject);
}
I'm using c# windows form in Visual studio 2017 version
I've made a high low game for practice and it works perfect but what I'm trying to accomplish is once someone hits 10 guesses it starts the application over again.
This was my last resort coming here and asking but i have no one else to turn to. I've tried all kinds of things to make it work when hitting 10 guesses to restart the app but nothing works and i get errors.
here's the start button and the guess button
variables I'm using
static int intRandomNumber;
static int intNumGuesses;
static int intBestLowScore;
static int intGuessedNum;
static int difference = 0;
Start Button
{
//Random Numbers//
Random rnRandomNumber = new Random();
intRandomNumber = rnRandomNumber.Next(0, 1000);
lblRandomNumber.Text = intRandomNumber.ToString();
txtGuess.Enabled = true;
btnGuess.Enabled = true;
btnStart.Enabled = false;
lblAnswer.Text = "".ToString();
intBestLowScore = intNumGuesses;
intNumGuesses = 0;
lblNumGuesses.Text = "0";
lblBestScore.Text = intBestLowScore.ToString();
lblAnswer.BackColor = Color.White;
txtGuess.Focus();
SoundPlayer audio = new SoundPlayer(High_Low_Game.Properties.Resources.Cheering);
audio.Stop();
}
Guess Button
{
intNumGuesses++;
lblNumGuesses.Text = intNumGuesses.ToString();
try
{
intGuessedNum = Convert.ToInt32(txtGuess.Text);
if (intRandomNumber - intGuessedNum < difference)
{
lblAnswer.Text = "To High";
lblAnswer.ForeColor = Color.Red;
lblAnswer.BackColor = Color.White;
txtGuess.Text = "";
txtGuess.Focus();
}
else if (intRandomNumber - intGuessedNum > difference)
{
lblAnswer.Text = "To Low";
lblAnswer.ForeColor = Color.Blue;
lblAnswer.BackColor = Color.White;
txtGuess.Text = "";
txtGuess.Focus();
}
else
{
lblAnswer.Text = "You Guessed it.";
lblAnswer.ForeColor = Color.Black;
lblAnswer.BackColor = Color.Green;
btnGuess.Enabled = false;
txtGuess.Enabled = false;
txtGuess.Text = "";
btnStart.Enabled = true;
SoundPlayer audio = new SoundPlayer(High_Low_Game.Properties.Resources.Cheering);
audio.Play();
}
}
catch
{
MessageBox.Show("Input your Guess again and Integers Only. Retry.");
txtGuess.Focus();
}
}
You're missing an if statement
Guess Button:
private void btnGuess_Click(object sender, EventArgs e)
{
intNumGuesses++;
lblNumGuesses.Text = intNumGuesses.ToString();
//This is what you're looking for-v
if(intNumGuesses==10)
{
btnGuess.Enabled = false;
txtGuess.Enabled = false;
txtGuess.Text = "";
btnStart.Enabled = true;
intNumGuesses=0;
}
//This is what you're looking for-^
try
{
intGuessedNum = Convert.ToInt32(txtGuess.Text);
if (intRandomNumber - intGuessedNum < difference)
{
lblAnswer.Text = "To High";
lblAnswer.ForeColor = Color.Red;
lblAnswer.BackColor = Color.White;
txtGuess.Text = "";
txtGuess.Focus();
}
else if (intRandomNumber - intGuessedNum > difference)
{
lblAnswer.Text = "To Low";
lblAnswer.ForeColor = Color.Blue;
lblAnswer.BackColor = Color.White;
txtGuess.Text = "";
txtGuess.Focus();
}
else
{
lblAnswer.Text = "You Guessed it.";
lblAnswer.ForeColor = Color.Black;
lblAnswer.BackColor = Color.Green;
btnGuess.Enabled = false;
txtGuess.Enabled = false;
txtGuess.Text = "";
btnStart.Enabled = true;
}
}
catch
{
MessageBox.Show("Input your Guess again and Integers Only. Retry.");
txtGuess.Focus();
}
}
In your 'guess-button' handler do the following:
{
intNumGuesses++;
lblNumGuesses.Text = intNumGuesses.ToString();
bool guessed = false;
try
{
intGuessedNum = Convert.ToInt32(txtGuess.Text);
if (intRandomNumber - intGuessedNum < difference)
{
...
}
else if (intRandomNumber - intGuessedNum > difference)
{
...
}
else
{
...
guessed = true;
}
if ((intNumGuesses == 10}&&(!guessed))
{
// Show Message "max. nr. of guesses reached'
// call method to clear values from textBoxes & enable Start-button
}
catch
{
MessageBox.Show("Input your Guess again and Integers Only. Retry.");
txtGuess.Focus();
}
}
What about this?
{
intNumGuesses++;
if(intNumGuesses >= 10)
{
StartButton(); // pseudo call, replace with whatever the name and parameters of your method really are
return;
}
lblNumGuesses.Text = intNumGuesses.ToString();
// ...
}
I would recommend to write an Init()method, that you call either from your StartButton() method or from your GuessButton() method when necessary
So Im making tetris and I dont know how to draw the blocks( L,I,Z etc) I have one block as Texture2D and every class for the blocks look like this:
namespace Tetris
{
public class ZBlock
{
Color Color;
const int x = 4;
const int y = 4;
bool[,] vorm;
public bool[,] zblock()
{
vorm = new bool[x, y];
for(int i=0; i< x; i++)
for (int j=0; j<y; j++)
{
vorm[i, j] = false;
vorm[0, 0] = true;
vorm[1, 0] = true;
vorm[1, 1] = true;
vorm[2, 1] = true;
}
Color = Color.Purple;
return vorm;
}
}
and this is the block class:
namespace Tetris
{
public class Block
{
Texture2D block;
Vector2 BlockPosition = new Vector2(30, 30);
float FallTimer;
Random Random = new Random();
ZBlock zBlock = new ZBlock();
TBlock tBlock = new TBlock();
SBlock sBlock = new SBlock();
OBlock oBlock = new OBlock();
JBlock jBlock = new JBlock();
LBlock lBlock = new LBlock();
IBlock iblock = new IBlock();
public bool[,] blockvorm()
{
bool[,] vorm;
vorm = new bool[4, 4];
vorm[3, 3] = false;
int r = Random.Next(7);
if (r == 0)
{
ZBlock.zblock();
}
else if (r == 1)
{
TBlock.tblock();
}
else if (r == 2)
{
SBlock.sblock();
}
else if (r == 3)
{
OBlock.oblock();
}
else if (r == 4)
{
JBlock.jblock();
}
else if (r == 5)
{
LBlock.lblock();
}
else if (r == 6)
{
IBlock.iblock();
}
return vorm;
}
public TBlock TBlock
{
get { return tBlock; }
}
public ZBlock ZBlock
{
get { return zBlock; }
}
public SBlock SBlock
{
get { return sBlock; }
}
public OBlock OBlock
{
get { return oBlock; }
}
public JBlock JBlock
{
get { return jBlock; }
}
public LBlock LBlock
{
get { return lBlock; }
}
public IBlock IBlock
{
get { return iblock; }
}
public void Draw(GameTime gameTime, SpriteBatch spriteBatch, ContentManager Content)
{
block = Content.Load<Texture2D>("Block");
int[,] Grid = Tetris.GameWorld.TetrisGrid;
spriteBatch.Begin();
spriteBatch.Draw(?????????????);
spriteBatch.End();
}
So the problem is: I dont know how to draw those blocks (I know how to draw one block but I want the complete ones). I thought maybe ZBlock.vorm or ZBLock.zblock but both give errors.
Does anyone know how to draw the blocks?
Ok so here is a partial answer. What you want to do is basically just draw each block with a certain offset from the next block equal to: blockWidth / 2 in pixels. This means that the blocks will be correctly orientated without overlap.
Here is what you should put in the draw statement:
public void Draw(int theXPosition, int theYPosition, Color theColor, SpriteBatch theSpriteBatch, Texture2D theBlockTexture)
{
int aTextureStartX = Color * Convert.ToInt32(mBlockSize);
for (int aBlock = 0; aBlock < mNumberOfBlocks; aBlock++)
{
int aXPosition = (int)(theXPosition + (CurrentShape[Rotation, aBlock, 0] * mBlockSize));
int aYPosition = (int)(theYPosition + (CurrentShape[Rotation, aBlock, 1] * mBlockSize));
theSpriteBatch.Draw(theBlockTexture, new Rectangle(aXPosition, aYPosition, mBlockSize, mBlockSize), new Rectangle(aTextureStartX, 0, mBlockSize, mBlockSize),
}
}
This is from a blog: http://www.xnadevelopment.com/tutorials/fallingblocksyoumovetomakelines/fallingblocksyoumovetomakelines.shtml
The source code is at the top of the page.
enter code here i have two cell in grid i want to chage one cell color and value by zero when i entered in other cell greater then zero value
private void grdDetail_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if (this.IsLoadComplete)
{
UpdateValueofQtyCell(e.ColumnIndex);
}
}
private void UpdateValueofQtyCell(int index)
{
int cur_row = grdDetail.CurrentRow.Index;
if (index == 1)
{
grdDetail[1, cur_row].Style.BackColor = Color.White;
grdDetail[2, cur_row].Style.BackColor = Color.FromArgb(224, 224, 224);
grdDetail[2, cur_row].Value = 0;
}
else if (index == 1)
{
grdDetail[2, cur_row].Style.BackColor = Color.White;
grdDetail[1 cur_row].Style.BackColor = Color.FromArgb(224, 224, 224);
grdDetail[1, cur_row].Value = 0;
}
}
you can use this code:
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value.ToString() != "0")
{
dataGridView1.Rows[i].Cells[0].Style.BackColor = Color.Yellow;
}
}
create below variable at class level.
bool IsAnyGreaterThanZero = false;
then call first below function which tell if any cell value is greater than zero.
private void CheckForGreaterThanZero()
{
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
if ((int)dataGridView1.Rows[i].Cells[0].Value > 0)
{
IsAnyGreaterThanZero = true;
}
}
}
then call below function to change color of those cells which has value equal to zero.
private void ChangeOtherCellColor()
{
if(IsAnyGreaterThanZero)
{
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
if ((int)intdataGridView1.Rows[i].Cells[0].Value == 0)
{
DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
CellStyle.BackColor = Color.Red;
dataGridView1.Rows[i].Cells[0].Style = CellStyle;
}
}
}
}