- Home /
I solved it.
Please help! I am new to unity and coding. I am trying to set my level at axis x =10.75148 and axis z= 3 but when script runs x and z axis becomes negative
I am trying to set my level at axis x =10.75148 and axis z= 3 but when script runs x and z axis becomes negative. I am trying to make infinity levels on y axis. On Y axis it seems fine but x axis and z axis becomes negative once level parent object TileManager script runs. Tile manager position sets as axis x =10.75148 , axis Y = 0 and axis z= 3
Please kindly help someone.
Below is my Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TileManager : MonoBehaviour
{
// Start is called before the first frame update
public GameObject[] tilePrefabs;
private Transform playerTransform;
private float spawnY = 115.9884f;
private float tileLenght = 499.8616f;
private float spawnX = 10.75148f;
private float spawnZ = 3f;
private int AmtOfTiles = 3;
private List<GameObject> activeTiles;
private int LastPrefabIndex = 0;
private void Start()
{
activeTiles = new List<GameObject>();
playerTransform = GameObject.FindGameObjectWithTag("Player").transform;
for (int i = 0; i < AmtOfTiles; i++)
{
if (i < 2)
SpawnTile(0);
else
SpawnTile();
}
}
// Update is called once per frame
private void Update()
{
if (playerTransform.position.y > (spawnY - AmtOfTiles * tileLenght))
{
SpawnTile();
DeleteTile();
}
}
private void SpawnTile(int prefabIndex = -1)
{
GameObject levelgo;
if (prefabIndex == -1)
levelgo = Instantiate(tilePrefabs[RandomPrefabIndex()]) as GameObject;
else
levelgo = Instantiate(tilePrefabs[prefabIndex]) as GameObject;
levelgo.transform.SetParent(transform);
levelgo.transform.position = Vector3.up * spawnY;
spawnY += tileLenght;
activeTiles.Add(levelgo);
}
private void DeleteTile()
{
Destroy(activeTiles[0]);
activeTiles.RemoveAt(0);
}
private int RandomPrefabIndex()
{
if (tilePrefabs.Length <= 1)
return 0;
int randomIndex = LastPrefabIndex;
while (randomIndex == LastPrefabIndex)
{
randomIndex = Random.Range(0, tilePrefabs.Length);
}
LastPrefabIndex = randomIndex;
return randomIndex;
}
}
Answer by Llama_w_2Ls · Jul 30, 2020 at 08:50 AM
You can always use the Mathf.Abs()
function to always get an absolute value which means your numbers will never be negative. E.g: Mathf.Abs((spawnY - AmtOfTiles * tileLenght))
will always return a positive number, instead of a negative. Check your BODMAS too, maybe spawnY - (AmtOfTiles * tileLength) was negative.
I fixed it. Issue is not with the code. It was about the position of the objects.
Follow this Question
Related Questions
Changing water level 0 Answers
Define position as lower left corner? 0 Answers
Transforming 2D object with respect to UI 1 Answer
Transform.position not working ??? 0 Answers
How do I make and object's position and rotation independent again? 1 Answer