I have objects that I add to my list in order to stop their velocity upon a level ending. If I debug the list, Only one object reads back each time. My list is made to keep track of objects that are cloned so that I may stop their velocity upon a condition being met. The script is as follows :
Variables (These are variables I am using the try and create my list)
#region MULTIBALL VARIABLES
Ball[] balls;
Ball ball;
public List<Ball> _listOfClones = new List<Ball>();
#endregion
Function with list (The balls instantiate fine, but are not added to the list for some reason)
From a quick read, your “Destroy(gameObject)” destroys the gameObject that is currently parsing the balls. I’m not sure Unity actually destroys the object immediately before finishing it’s for loop but this is probably not what you want anyway.
I’m also confused by the line “ball = FindObjectOfType();”.
You use the variable ball to find a Ball object currently in the scene, then you replace with a reference to a new instance.
Calling Destroy will only destroy on the end of frame, you can call DestroyImmediate - but it should generally be avoided for reasons (I only use it on editor scripts)
I don’t understand what the else case in the StopAllClones function is trying to do.
If the ball isn’t null stop it - fine
else Destroy(gameObject) - destroys the object this script lives on, is this what you intend?
gameObject is a shorthand for the gameObject the monobehavior lives on.
I’ve removed the Destroy line, which I see is unnecessary now and this has helped a bit. Although, the cloned objects are not being stopped still.
The StopAllClones function is made to halt all of the gameObjects containing the “Ball” monobehavior, but is only stopping the original “Ball” gameObject. Ideally, I’m trying to keep track of every object that has this class on it and stop them when the conditions for the level completion are met.
Without this line the gameObject that triggers the cloning of the gameObject “Ball” throws an error saying “The object you want to instantiate is null.” So I was using this to give Unity a reference to my gameObject. I’m following along to a course and this section doesn’t give much guidance to this area, so I’m open to any suggestions on how to do it. Even just pointing me into a direction of what to read, because I feel so stuck on this script.
So playing around a bit you ended up leading me to the answer. At some point I ended up creating an object to manage the list, but my gameObject that I was cloning also contained the same list. I ended up removing the script from the gameObject being cloned and it seems to work fine now. Ty for the help!