I have a function that creates, in an isometric perspective, a ground made out of n*n blocks, n being the length of one side, just like in the example below. All the creating is made from scratch, by that I mean that, my scene was almost all empty.
The thing is that when I introduce a length of 1 digit(from 1 to 9) the script works well. But when I try adding another digit to that one, making the length > 9, it makes the last block look like that. I assume that it is layered 1 layer behind and I don't understand why.
That problem is only when I try changing my length while the game is running. When I change to a length>9 before running, it works well. I think it is a layering problem but I don't know. I am a beginner after all. :)
In any case here is my script:
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using UnityEngine;
public class CreateField : MonoBehaviour
{
[SerializeField] Camera _cam;
[SerializeField] GameObject _sprite;
[SerializeField] GameObject _groundContainer;
[SerializeField] int lungime;
int lastLungime;
float _height, _width;
private void Start()
{
if(lungime<1) lungime = 1;
lastLungime = lungime;
_width = lungime;
setCameraResolution();
createField(new Vector3(0, _height, 0));
}
void setCameraResolution()
{
_height = _width / _cam.aspect;
_cam.orthographicSize = _height;
}
void deleteField()
{
for(int i = 0; i < _groundContainer.transform.childCount; i++)
{
Destroy(_groundContainer.transform.GetChild(i).gameObject);
}
}
void createField(Vector3 offset)
{
for(int i=1; i<= lungime; i++)
{
for (int j = 1; j <= lungime; j++)
{
Vector3 pos = new Vector3((i-j), -(i + j) / 2f, 0) + offset;
GameObject newSprite = Instantiate(_sprite, pos, _sprite.transform.rotation);
newSprite.transform.parent = _groundContainer.transform;
newSprite.name = "ground("+i+","+j+")";
}
}
}
private void Update()
{
if (lastLungime != lungime)
{
deleteField();
_width = lungime;
setCameraResolution();
createField(new Vector3(0, _height, 0));
lastLungime = lungime;
}
}
}
With that said, the problem is most likely in the Update(), but I don't see it.
Some more pictures for reference:
I tried different things but it did not work.
That's when I taught to use the position.z.
I multiplied length*length
and then I summed it with the pos.z
of the camera, then, for every block, I did this:
newSprite.transform.position += new Vector3(0, 0, diff--);
This way, the first block placed will be of cam.pos.z-lungime*lungime
, and then we decrease till the last block placed will be cam.pos.z.