So, I’ve got this going on
and after spending the day fighting with Unity to try and have it select a random asset from the resources folder without having to hardcode them in, my brain is too burnt to see what’s going wrong with my script. Could someone please take a look and point me towards the error?
My Script
using UnityEngine;
public class PlatformGenerator : MonoBehaviour
{
[SerializeField] Transform myCamera;
[SerializeField] float verticalShift;
[SerializeField] float horizontalShift;
[SerializeField] float generationPosition;
int elementCount = 0;
BlockPicker blockPicker;
Vector3 endPosition;
string[] platformTypes = new string[] { "Multi", "Single" };
void Start()
{
blockPicker = GetComponent<BlockPicker>();
GameObject startPlatform = GameObject.Find("Start Position Group");
if (!startPlatform) CreateStartPosition();
else
{
CountElements();
endPosition = CalculateEndPosition(startPlatform);
}
}
// Update is called once per frame
void Update()
{
// if endPosition is within 3 units of camera view then generate next platform.
if (endPosition.y - myCamera.transform.position.y < generationPosition) GeneratePlatform();
}
void GeneratePlatform()
{
string platformType = SelectPlatformType();
GameObject selectedBlock = blockPicker.GetDefaultBlock();
if (platformType == "Single") selectedBlock = blockPicker.SelectSingleBlockElement();
else if (platformType == "Multi") selectedBlock = blockPicker.SelectMultiBlockElement();
Vector3 targetPosition = CalculateNewPosition(endPosition);
var newBlock = Instantiate(selectedBlock, targetPosition, Quaternion.identity) as GameObject;
SetUpNewBlock(newBlock);
}
string SelectPlatformType()
{
return platformTypes[Mathf.RoundToInt(Random.Range(0f, platformTypes.Length-1))];
}
Vector3 CalculateNewPosition(Vector3 currentEndPosition)
{
float newXPos = currentEndPosition.x + (Random.value * horizontalShift);
float newYPos = currentEndPosition.y + (Random.value * (verticalShift * 2)) - verticalShift;
return new Vector3(newXPos, newYPos, 0f);
}
Vector3 CalculateEndPosition(GameObject block)
{
Vector3 lastEndPoint = new Vector3();
for(int i =1; i <= block.transform.childCount; i++)
{
Transform child = block.transform.GetChild(i-1).transform;
if(child.name == "End Pont")
{
if (child.transform.position.y > lastEndPoint.y) lastEndPoint = child.transform.position;
}
}
return lastEndPoint;
}
private void SetUpNewBlock(GameObject block)
{
endPosition = CalculateEndPosition(block);
block.transform.parent = this.transform;
elementCount++;
}
void CreateStartPosition()
{
var newBlock = Instantiate(blockPicker.GetStartElement(), new Vector3(), Quaternion.identity) as GameObject;
newBlock.name = "Start Position Group";
SetUpNewBlock(newBlock);
}
void CountElements() { for (int i = 1; i <= this.transform.childCount; i++) elementCount++; }
}