- Home /
How do I make an object spawn on another object's coordinates
Hi! I solved my other question from a couple minutes ago, my objects now spawn! New problem though, I wish to make them spawn on where they are supposed to go. For example here is my code atm:
public class Puzzle : MonoBehaviour { private List _listeTraps;
[SerializeField] private GameObject[] _tableauTraps;
[SerializeField] private GameObject[] _Spikes;
[SerializeField] private GameObject[] _Mines;
[SerializeField] private GameObject[] _Nothing;
// Start is called before the first frame update
void Start()
{
_listeTraps = new List<GameObject[]>();
_listeTraps.Add(_Spikes);
_listeTraps.Add(_Mines);
_listeTraps.Add(_Nothing);
Init();
}
private void Init(){
for(int i = 0; i < _tableauTraps.Length; i++)
{
int _aleatoireSorte = Random.Range(0, _listeTraps.Count); //pige un chiffre random
GameObject[] n = _listeTraps[_aleatoireSorte]; //n = au chiffre piger
int _aleatoireTrap = Random.Range(0, n.Length);
_tableauTraps[i] = n[_aleatoireTrap];
Instantiate(n[_aleatoireTrap], _tableauTraps[i].transform.position, Quaternion.Euler(0,0,0));
// _listeTraps.RemoveAt(_aleatoireSorte);
}
}
}
As of now, my object spawns kind of randomly, I want it to spawn on one of the elements in my _tableauTraps list. How do I do so?
Here's an image of my editor:
Hi! Forgot to mention, that I plan on having multiple traps generated and not just one!
What do you mean by my object spawns kind of randomly
? The code looks correct, you're providing the position of the spawn point as second argument of the Instantiate
method, so unless the objects you instantiate have children which are not centered, I think your code works.
Whenever it spawns, it doesn't go to the right position, I want it to go on my element trap's position on my editor.
for example, the grey spot is where I want my trap to spawn, the black spot is where my trap is spawning
Are you sure your trap
object referenced in the _tableauTraps
has a local position of (0, 0, 0)? (i.e is placed at the Traps
's position?
You could try changing your code for:
Instantiate(n[_aleatoireTrap]).transform.position = _tableauTraps[i].transform.position;
but I believe you'll get the same outcome.
P.S: Piece of advice: pick either english or french for your code, not a mix of both