I have some images that are money in my game. I have a spawner that instantiates them at a random spawnpoint. I made the spawner a child of my canvas, but it still spawns outside of the canvas(in the hierarchy). This is my code for the spawner:
using UnityEngine;
public class Spawner : MonoBehaviour {
public Transform[] spawnPoints;
public GameObject[] randomPrefab;
public float spawnDelay = 2f;
public float spawnTimeDifference = 2f;
void Update()
{
if (Time.time >= spawnDelay)
{
spawnObjects();
spawnDelay = Time.time + spawnTimeDifference;
}
}
void spawnObjects()
{
int randomIndex = Random.Range(0, spawnPoints.Length);
int randomNumber = Random.Range(0, 5);
for (int i = 0; i < spawnPoints.Length; i++)
{
if (randomIndex == i)
{
Instantiate(randomPrefab[randomNumber], spawnPoints[i].position, Quaternion.identity);
}
}
}
}
I assume you want the spawned objects to be childs of the Spawner? If so, you never set their parent. Try this:
GameObject tmp = Instantiate(...); // basically your line 31
tmp.transform.parent = transform;
Also, your entire for-loop is unnecessary. With ‘randomIndex’ you literally already calculated the index you want to access. No need to iterate the whole array, check if i == randomIndex, and then use i. Instead just use [randomIndex] and strip the extra calculations.
One more thing, method names, just like class or property names, should start with a capital letter, ie “SpawnObjects”
Parent of RectTransform is being set with parent property. Consider using the SetParent method instead, with the worldPositionStays argument set to false. This will retain local orientation and scale rather than world orientation and scale, which can prevent common UI scaling issues.
UnityEngine.Transform:set_parent(Transform)
Spawner:spawnObjects() (at Assets/Scripts/Spawner.cs:32)
Spawner:Update() (at Assets/Scripts/Spawner.cs:16)
It gives me this warning, is that okay?
Yoreki’s post is the older direct use of the .parent property, which usually works okay, but from your warning message it seems like it is getting deprecated.
With UI, it’s always best if you just jam it directly into the hierarchy with a variant of the Instantiate() call that takes only two arguments and the second one is a transform, which sets its parent. This means you would then need to set the position after the Instantiate.
Another completely different way to set the parent is the .SetParent() call, which takes an optional second argument that controls preservation of the world position. For UI items, you would want it to look like this: