- Home /
For loop and instantiate question
Howdy,
I have written myself a script that allows me to instantiate a potato plant object on an available tile (as in no other plant is on that tile) and when I right click that plant and it is "mature" potatos will be instantiated and the plant will be destroyed. Once the plant is on longer on the tile it allows me to plant another one there again.
This all seems to be working as intended but now rather than 1-2 potatos spawing I'm getting 6-10. I know the issue it the for loop its self but I need it in order to loop through the different ground tiles.
Here is the method that allows me to destroy a mature plant and spawn the potatos
private void DeystroyMaturePlant() { Vector3 mousePOS = Input.mousePosition;
if (maturePotato == true)
{
mousePOS = Camera.main.ScreenToWorldPoint(mousePOS);
if (((gameObject.transform.position.y < mousePOS.y) && (gameObject.transform.position.y > mousePOS.y - 0.8)) && ((gameObject.transform.position.x < mousePOS.x + 0.3) && (gameObject.transform.position.x > mousePOS.x - 0.3)))
{
int range = UnityEngine.Random.RandomRange(1, 3);
for (int j = 0; j < range; j++)
{
GameObject newPotato = new GameObject();
newPotato.transform.position = gameObject.transform.position;
newPotato.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f);
newPotato.AddComponent<SpriteRenderer>().sprite = itemDataBase.FindItem("Potato").sprite;
newPotato.AddComponent<Rigidbody2D>();
newPotato.AddComponent<PolygonCollider2D>();
newPotato.GetComponent<Rigidbody2D>().isKinematic = true;
newPotato.AddComponent<Magnetism>();
newPotato.GetComponent<Magnetism>().strength = 2;
newPotato.GetComponent<Magnetism>().range = 11.1f;
newPotato.layer = 10;
newPotato.name = itemDataBase.FindItem("Potato").name;
}
Object.Destroy(this.gameObject);
}
}
}
I also have a for loop on that one that randomizes how many will drop. Getting rid of that does reduce the amount that are dropped but not by much. But it also doesn't randomize the number of drops which I would like.
Here is the method with the for loop
private void Update()
{
GameObject[] ground = GameObject.FindGameObjectsWithTag("Ground");
till = new Till[ground.Length];
for (int i = 0; i < ground.Length; i++)
{
till[i] = ground[i].GetComponent<Till>();
if (Input.GetMouseButtonDown(1))
{
DeystroyMaturePlant();
till[i].isPlantable = true;
}
}
}