- Home /
Script instantiation always same position
Hello guys,
i try to instantiate a Prefab at a certain position depending on how many instances already were instanciated. The project is in 2D.
public GameObject projectObj;
float y_pos = 0;
public void NewButton()
{
y_pos += 10;
GameObject inst = Instantiate(projectObj, new Vector3(100, y_pos, 0), Quaternion.identity);
}
Goal: Instanciate iteratively by button pressing at different y positions = n*10. Problem: Instantiation always at (0, 0) of parent object. I read many threads but did not find a similar problem. Thanks for your help in advance :)
PS: tried to change from Vector3 to Vector2 and played around with datatypes but never changed behaviour: even using Vector3(1000,1000,0) or Vector2(1000,1000) delivering the same result so i must have a misunderstanding here.
Regards Chris
Answer by Rachmanichou · Mar 24 at 08:59 AM
Since nothing seemed wrong I plugged in the code into a test scene, and it worked out very well. How are you calling the method? I called it in the Update method and it worked just fine.
Hello and thank you fow your reply! I am calling the method by "On Click()" of a button. Additional info: The script is attached to a canvas which is holding the button (which i use for the call) as a child. The instances are created but they all overlap at (0, 0) and do not get instanced at the desired position:
Hi,
The problem, imho, is that the onClick() method is a unity event, which are at the same time - to my understanding - events and the delegates that pass it to an event handler, which will produce the appropriate response. When using only, onClick(), you integrate the event but it is not properly handled. What I just said could be completely wrong, but that's the way I visualize it, until I'll some day find some solid information about Unity Events and Listeners. Anyways, what I suggest is simply adding a part in your that assigns a Listener to your unity event. Here's what I plugged into the code:
using UnityEngine.UI;
public class test : MonoBehaviour
{
public GameObject projectObj;
public Button button ;
float y_pos = 0;
void Start()
{
button.onClick.AddListener(DoOnClick) ;
}
public void NewButton()
{
y_pos += 10;
GameObject inst = Instantiate(projectObj, new Vector3(100, y_pos, 0), Quaternion.identity);
}
void DoOnClick()
{
NewButton() ;
}
}
I placed that code on the Canvas, but it can be placed anywhere I think. And it did it for me! Hope that helps