Reputation: 51
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.
Upvotes: 1
Views: 526
Reputation: 3925
Single bool
is not enough, because you want to instantiate one object multiple times. You want to check if it was already instantiate in this position.
public GameObject obj;
float lastInstPos = 0;
private void Update()
{
var currPos = Mathf.Round(transform.position.y);
if (currPos % 4 == 0 && currPos != lastInstPos)
{
lastInstPos = currPos;
Spawn();
}
}
public void Spawn()
{
Instantiate(obj, new Vector3(transform.position.x, transform.position.y), Quaternion.identity);
}
If you want to include 0
, then make the lastInstPos
something arbitrary, e.g. lastInstPos = float.MinValue
Update: This solution assumes that y
either increases or decreases, but doesn't do both.
Upvotes: 1
Reputation: 51683
Simply use the return value of Instantiate and put each Instance into a Dictionary that has its y position as key - before instatiating check if this y position is already a key in the dictionary:
public GameObject obj;
private Dictionary<int, GameObject> myInst = new Dicitionary<int, GameObject>();
private void Update()
{
int pos = (int)Mathf.Round(transform.position.y);
if (pos % 4 == 0 && !myInst.ContainsKey(pos)) // check if key exists
{
myInst[pos] = Spawn(); // add gameObject to dictionary
}
}
// return the gameObject you spawned
public GameObject Spawn()
{
return Instantiate(obj, new Vector3(transform.position.x, transform.position.y), Quaternion.identity);
}
That way you know the exact y coordinate of each instantiated object.
If you do not need the Instance-GameObject as well you could get away simply with a Hashset<int>
of y-positions that you instantiated. Dictionary as well as Hashsets have very fast O(1) Key Lookups, store a ref to your Instanciated object takes not much space and is easier to retrieve here then by searching (if you ever need them at all)
Upvotes: 0