'How would you instantiate something relative to the position of the previously instantiated object?
So basically, for the past couple hours I have been trying to figure this out. Currently, what I have is some code that instantiates an object within a certain x and z range, 5-10 metres higher each time.
private GameObject platScript;
public GameObject[] platforms;
public float xRange = 50.0f;
public float yRange = 5f;
public float objectRange;
public float yMinRange = 5f;
public float yMaxRange = 10f;
public float zRange = 50.0f;
public float rotRange = 360.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.K))
{
PlacePlatform();
}
}
void PlacePlatform()
{
int platformsToSpawn = Random.Range(0, platforms.Length);
yRange += Random.Range(yMinRange, yMaxRange);
platforms[platformsToSpawn].transform.rotation = Quaternion.Euler(Random.Range(-rotRange, rotRange), rotRange, Random.Range(rotRange, rotRange));
Vector3 RandomSpawnPos = new Vector3(Random.Range(-xRange, xRange), yRange, Random.Range(-zRange, zRange));
GameObject platStan = Instantiate(platforms[platformsToSpawn], RandomSpawnPos, platforms[platformsToSpawn].transform.rotation);
platScript = platStan.GetComponent<GameObject>();
Vector3 platPos = new Vector3(platStan.transform.position.x + Random.Range(-10, 10), 0, platStan.transform.position.z + Random.Range(-10, 10));
Instantiate(platforms[platformsToSpawn], platPos, platforms[platformsToSpawn].transform.rotation);
}
What this code is supposed to do is get the current x and z range of the instantiated object, add between -10 and 10 to it, and then spawn it within a radius of -10 to 10 relative to the last instantiated object, rather than anywhere in a -50 to 50 radius on the x and y axis.
I tried running this, but it doesn't seem to have any effect on whether the platforms spawn relative to the last instantiated object or not. They just spawn anywhere between -50 to 50 on the horizontal axis, going 5-10 metres higher each time.
I'm quite new to c#, having only picked it up about 2 weeks ago, so my code is probably quite a mess, and I apologise for that. Any advice on cleaning my code or how to get this to work would be Greatly appreciated. Many thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
