- Home /
Stop Object from instantiating multiple times in Update using bool
This is the script. I want the object to instantiate only once every time the y position is a multiple of 4. But the object gets instantiated multiple times as long as the y position is stuck at 4. I want to it to instantiate only once. Here's the script.
public GameObject obj;
bool check = true;
private void Update()
{
if (Mathf.Round(transform.position.y) % 4 == 0 && check)
{
check = false;
Spawn();
}
}
public void Spawn()
{
Instantiate(obj, new Vector3(transform.position.x, transform.position.y), Quaternion.identity);
check = true;
}
Thank You!
Answer by Bale_txy · Jan 27, 2018 at 01:21 PM
you can simply achieve that by buffer your game object's last position and compare it with its current position. If they are the same, which means the game object is still, then do not trigger the function.
if(.............&&.........&&lastposition!=transform.position){
//your code herer
}
lastposition = transform.position;
Doesn't work. I'm doing this.
public GameObject obj;
bool check = true;
Vector3 lastposition;
private void Start()
{
lastposition = transform.position;
}
private void Update()
{
if ($$anonymous$$athf.Round(transform.position.y) % 4 == 0 && lastposition!=transform.position)
{
Spawn();
}
}
public void Spawn()
{
Instantiate(obj, new Vector3(transform.position.x, transform.position.y), Quaternion.identity);
lastposition = transform.position;
}
lastposition = transform.position;
this line has to be put in the update() functions since it's checking whether the player is moving or not, and you need your bool variable as well
Alright I did this, now the object spawns only once when the position gets to 4, then when it gets to 8, 12 and so on, it doesn't spawn! Help!
public GameObject obj;
bool check = true;
Vector3 lastposition;
private void Start()
{
lastposition = transform.position;
}
private void Update()
{
if ($$anonymous$$athf.Round(transform.position.y) % 4 == 0 && check && lastposition!=transform.position)
{
Spawn();
check = false;
}
lastposition = transform.position;
}
public void Spawn()
{
Instantiate(obj, new Vector3(transform.position.x, transform.position.y), Quaternion.identity);
check = true;
}
Your answer
Follow this Question
Related Questions
Instantiate in different position 2017.3.0f3 2 Answers
calling function once? 3 Answers
Lagspike when using instantiate in coorutine 0 Answers
Instantiating road pieces without any spacings between 2 Answers