- Home /
Add force to each object individually from a list immediately after it has been instantiated. ,Applying force to a listed object after it has been instantiated
So I am trying to add a force to a listed object and only that object immediately after it has been instantiated from a list. In this code, as you might see, applies a force to all objects each time an object in the list is added and instantiated. I don't really know how to explain this further, but if you ask questions I will answer. I will work on this myself in the meantime. Thank you for answering.
while (count >= 0f && OVRInput.Get(OVRInput.Touch.SecondaryThumbstick) && OVRInput.Get(OVRInput.Button.SecondaryIndexTrigger) && OVRInput.Get(OVRInput.Button.SecondaryHandTrigger))
{
count -= .1f;
transPY = Random.Range(-90f, 90f);
transPX = Random.Range(-90f, 90f);
cone1 = new Vector3(transPos.transform.position.x + .1f, transPos.transform.position.y, transPos.transform.position.z);
sphereClones.Add(Instantiate(sphere, cone1, transPos.transform.rotation));
foreach (GameObject clone in sphereClones)
{
clone.transform.GetComponent<Rigidbody>().AddRelativeForce(transPos.transform.forward.x * transPX, transform.position.y * transPY, transform.forward.z * 100f);
}
print("X: " + transform.forward.x * transPX);
print("Y: " + transform.position.y * transPY);
print("Z: " + transform.forward.z * 100f);
//print("Works");
astra = "";
IEnumerator WaitDestroy()
{
var emberOut = 0;
foreach (GameObject clone in sphereClones)
{
yield return new WaitForSeconds(.05f);
Destroy(sphereClones[emberOut]);
emberOut += 1;
//print("COUNT: " + sphereClones);
//print("EMBER: " + emberOut);
}
}
if (count <= 0f)
{
IEnumerator KeepWaiting()
{
spawnBalls = false;
count = 10f;
yield return new WaitForSeconds(1f);
StartCoroutine(WaitDestroy());
}
StartCoroutine(KeepWaiting());
}
break;
Answer by metalted · Mar 15, 2020 at 08:20 PM
If you only want to add force to the last object and not all of them, couldn't you change:
foreach (GameObject clone in sphereClones)
{
clone.transform.GetComponent<Rigidbody>().AddRelativeForce(transPos.transform.forward.x * transPX, transform.position.y * transPY, transform.forward.z * 100f);
}
Into this:
sphereClones[sphereClones.Count - 1].transform.GetComponent<Rigidbody>().AddRelativeForce(transPos.transform.forward.x * transPX, transform.position.y * transPY, transform.forward.z * 100f);
}
So instead of applying it to all, apply it to the last.
Your answer
![](https://koobas.hobune.stream/wayback/20220612225021im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to put gameObjects to the list? 4 Answers
A node in a childnode? 1 Answer
cant get characters to load 1 Answer
Instantiate random from a list gives error: "Reference not set to an instance" 1 Answer
Destroy a gameobject from an index of a list, destroy all same gameobjects right after it, why ? 2 Answers