- Home /
How do I Instantiate a prefab on another game object's position (2D)
I need help as I am unable to spawn a prefab on my game objects position. Here is my code:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
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]).transform.position = _tableauTraps[i].transform.position;
// _listeTraps.RemoveAt(_aleatoireSorte);
}
}
}
And here are a couple of screenshots showing my unity editor:
This is what actually happens when I spawn my prefab:
Answer by Mitrovic_Z · Dec 13, 2021 at 05:26 PM
What I wish to do is to randomly select one of my two prefabs, one being a spike and the other being a mine. They each have their own scripts, colliders, etc. I wish for them to be randomly selected by my element in _tableauTraps which will contain a list of multiple elements that will be spread throught my maze. I want my elements to choose from one of two traps and for those traps to be set at their position. I seem to be able to do everything but set their position where they are supposed to be. I thank each and everyone of you, for your help! :)