Vector2 2D arrays in XNA - c#

I am trying to create 2D vector2 arrays in XNA,C#.
I used the following statement:
Vector2[][] SpritePosition=new Vector2[4][];
Then I used the following for loop to initialize them:
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
}
}
However, when I used the for loop, as stated above, it gave me an error, actually two:
Int is a field and used as a type.
'for' is an invalid token in class, struct or interface member declaration.
Can anyone tell why am I facing such a problem?
EDIT: This is the code:
public class Game1 : Microsoft.Xna.Framework.Game
{
int i=new int();
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D texture;
//Vector2[,] SpritePosition = new Vector2[4,4];
Vector2[,] SpriteSpeed = new Vector2[4,4];
for(i=0;i<4;i++)
{
}
}

Seems you need to read up on some C# Tutorials
You are going to need a function for that as so,
void LoadArray()
{
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
SpritePosition[i,j] = new Vector2(i,j)
}
}
You can call it from your initialize method, using LoadArray()
}
Also, You dont need int i = new Int() for basic stuff like strings, ints, etc you dont need the new Whatever() part
Just do
for(int i=0;i<4;i++)
{
}

for #2, it means your for loop isn't inside of a function... so there's probably an extra } somewhere higher up in your code that you didn't mean to put there. there's a good chance that this is also the problem with #1 but you haven't really given us enough context (more code or where exactly the compiler says the error is) to say for sure

Related

error CS0106: The modifier 'private' is not valid for this item C# error in Unity

I keep getting this error ( CS0106: The modifier 'private' is not valid for this item) and could use some help. I'm trying to make a random object generator for my game but since I am still a newbie coder I cannot seem to figure out how to fix this. Any help would be nice
Here is the code im using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class deployAsteroids : MonoBehaviour
{
public GameObject asteroidPrefab;
public float respawnTime = 1.0f;
void Start()
{
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(screenBounds.x, screenBounds.y, Camera.main.transform.position.z));
StartCorountine(asteroidWave());
private void spawnEnemy()
{
GameObject a = Instantiate(asteroidPrefab) as GameObject;
a.transform.position = new Vector2(Random.Range(-screenBounds.x, screenBounds.x), screenBounds.y * -2);
}
IEnumerator astroidWave()
{
while (true)
{
yield return new WaitForSeconds(respawnTime);
spawnEnemy();
}
}
}
Anytime you get a compiler error the first thing you should consider is to lookup up the error code in a search engine. From CS0106 the rules are provided. The forth bullet point is clear on this.
Access modifiers are not allowed on a local function. Local functions are always private.
You have two options:
Move the method outside of the parent method (Start()). This is the typical scenario if it will be used in more than one place.
Remove the modifier private.
Try using the static modifier, and reading this. That could work, it worked for me when I got the same error in unity for a public void.
Also, consider moving your method out of Start(), like others have said.

Cannot reference a script on an array of gameobjects generated in another script

I want an array of game objects, each game object has a simple script to move it. I want a controlling script to be able to trigger the remote script by referencing the array coordinates / game object at that point.
I am missing something basic in referencing a "global" variable - so apologies in advance. I have spent several hours now reading and trying things out.
Example questions like here Accessing a variable from another script C#
or
https://answers.unity.com/questions/42843/referencing-non-static-variables-from-another-scri.html
I believe the array should be static as there is only one set of data, however I don't care if it isnt
CreateGrid.cs
public class CreateGrid : MonoBehaviour
{
public static GameObject[,] gridArray = new GameObject[5, 5];
public GameObject gridSpace;
// Start is called before the first frame update
void Start()
{
GenerateGrid();
}
void GenerateGrid()
{
for (int x = 0; x < 5; x++)
{
for (int z = 0; z < 5; z++)
{
gridArray[x, z] = Instantiate(gridSpace, new Vector3(x, 0, z), Quaternion.identity) as GameObject;
}
}
// test grid works
// gridArray[2, 2].transform.Translate(0.0f, 3.0f, 0.0f);
}
}
test code
public class Pulse : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
for (int x = 0; x < 5; x++)
{
CreateGrid.gridArray[x, 3].GetComponent<MoveObject>().StartBounce(5.0f);
}
}
}
The grid of objects works.
However the test code errors with Object reference not set to an instance of an object from the line
CreateGrid.gridArray[x, 3].GetComponent().StartBounce(5.0f);
specifically CreateGrid.gridArray
Given that I seem to be really struggling with a concept, please explain clearly.
Thanks
Unless you don't clearly define otherwise, you don't know when the Start method of two MonoBehaviours will run.
In your case, the Pulse's Start method is called before CreateGrid's.
To fix your problem, I advise you to call CreateGrid's Generate method inside the Awake method of the class.
I often use this method to initialize members of the class not relying on other classes instances and use the Start method to initialize members needing other instances to be self-initialized.

C# (Unity 4.3) Cannot implicitly convert type `ShotScript[]' to `ShotScript'

Thanks all! The issue was I was using GetComponents rather than GetComponent, thanks!
I am fairly new to programming and I am trying to make a 2D game in Unity. I have found a tutorial online which is really good, up until a point (Tut can be found here http://pixelnest.io/tutorials/2d-game-unity/shooting-1/). I've come across an error and can't figure out why. The error occurs when I try and use another script inside my current script (if that makes sense to anyone). The two scripts in question have the name ShotScript and HealthScript and they are below
ShotScript:
using UnityEngine;
using System.Collections;
public class ShotScript : MonoBehaviour {
public int damage = 1;
public bool isEnemyShot = false;
void Start () {
Destroy (gameObject, 20);
}
}
HealthScript:
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
public int hp = 2;
public bool isEnemy = true;
void OnTriggerEnter2D(Collider2D Collider) {
ShotScript shot = collider.gameObject.GetComponents<ShotScript>();
if (shot != null) {
if (shot.isEnemyShot != isEnemy) {
hp -= shot.damage;
Destroy (shot.gameObject);
if (hp <= 0) {
Destroy(gameObject);
}
}
}
}
}
The error I get is:
"Assets/Scripts/HealthScript.cs(13,36): error CS0029: Cannot implicitly convert type ShotScript[]' toShotScript'"
I'm rather stuck and so if anyone could point me in the right direction, that'll be great =)
P.S I'm new to this asking questions thing, so if you need any extra info, I'll do my best to provide it
Well this is the problem:
ShotScript shot = collider.gameObject.GetComponents<ShotScript>();
It sounds like GetComponents<ShotScript> is returning an array of ShotScript references, i.e. its return type is ShotScript.
Do you want to take the same action for each ShotScript? If so, you probably want to just use a foreach loop... although you probably only want to check for the hp going negative at the end. I would expect you to be able to remove the check for nullity, too, assuming that GetComponents will just return an empty array if there aren't any such components:
ShotScript[] shots = collider.gameObject.GetComponents<ShotScript>();
foreach (ShotScript shot in shots)
{
if (shot.isEnemyShot != isEnemy)
{
hp -= shot.damage;
Destroy(shot.gameObject);
}
}
if (hp <= 0)
{
Destroy(gameObject);
}
(I've reformatted that to be rather more conventional C#, but of course you can use whatever indentation you want.)
You're calling GetComponents (notice the plural) which returns an array (that is ShotScript[]) of all matching components of the type on that particular GameObject.
So this is attempting to assign a ShotScript[] array into a single ShotScript instance which is not possible.
If you wanted to retrieve only one ShotScript (because you intend to have only 1 on an object), use the GetComponent (notice the singular) method instead which will return only one instance or null if none are assigned.
So change the one line to this:
ShotScript shot = collider.gameObject.GetComponent<ShotScript>();
If your intent was to handle many ShotScript instances/components on the same GameObject, use the fix/code supplied in Jon Skeet's answer.
The error message says that line 13 is in error:
ShotScript shot = collider.gameObject.GetComponents<ShotScript>();
It looks like the GetComponents method is returning an array ShotScript[], but you're trying to implicity cast it to just a single ShotScript instance. Try:
ShotScript[] shots = collider.gameObject.GetComponents<ShotScript>();

Drawing different Textures with a single Basic Effect, XNA 4.0

I have a problem in the game I wrote with XNA. I recently added Textured polygons, and saw that every textured polygon shared the same texture although I changed it before calling. The code I am using:
if (countMeshes > 0)
{
for (int i = 0; i < countMeshes; i++)
{
TexturedMesh curMesh = listMeshes[i];
if (curMesh.tex == null)
{
drawEffect.Texture = WHITE_TEXTURE;
}
else
{
drawEffect.Texture = curMesh.tex;
}
drawEffect.Techniques[0].Passes[0].Apply();
graphics.DrawUserPrimitives(PrimitiveType.TriangleList, curMesh.verts, 0, curMesh.count);
}
}
Now, the first that came into my mind would be to create a BasicEffect for each Texture I need to draw. But I think that would be a bit of a overkill so my question is: How should I do it?
PS: I double checked everything, the UV Coords are fine, and it is 2D.
It seems to be the only way, the way I did it was to create a Dictionary with the texture as the key and a struct of a basic effect and a list of Vertexs as the value.
Something like this:
public struct MeshEffect
{
public TexturedMesh mesh;
public BasicEffect effect;
}
and the Dictionary:
private Dictionary<Texture2D, MeshEffect> texturedMeshes = new Dictionary<Texture2D, MeshEffect>();
But it all really depends on how you handle drawing, but one thing is sure, you can't use more than one texture on one BasicEffect.

Typedef-equivalent in C#?

I know this exact question has been asked, but the solution posted there doesn't seem to work for me. Here's the code I'm trying:
namespace ConsoleApplication5
{
class Program
{
enum Tile { Empty, White, Black };
using Board = Tile[8,8];
And the error I get:
Invalid token 'using' in class, struct, or interface member declaration
It seems the "using" clause must be moved outside the Program class, but my Tile enum doesn't exist there. So how am I supposed to do this?
It looks like you're trying to use a name to represent a specific way of instantiating a Tile[,] array.
Why not just declare a method that does this?
Tile[,] GetBoard()
{
return new Tile[8, 8];
}
Another option, though I'd consider this a little bit bizarre (not to mention hacky), would be to define a Board type with an implicit operator to convert to Tile[,], as follows:
public class Board
{
private Tile[,] tiles = new Tile[8, 8];
public static implicit operator Tile[,](Board board)
{
return board.tiles;
}
}
This would actually allow you to do this:
Tile[,] board = new Board();
You cannot use using like that.
You can only use for concrete types, not for 'constructors' as you have used.
Unfortunately, you cannot use using to declare a name for an array type. I don’t know why, but the C# specification doesn’t allow it.
However, you can get pretty close by simply declaring Board as a new type containing the array you want, for example:
public class Board
{
public Tile[,] Tiles = new Tile[8,8];
}
Now every time you say new Board(), you automatically get an 8x8 array of tiles.

Categories