I’m trying to make an object that’ll duplicate itself in random positions, but when I duplicate it, it also duplicates the code. The clone then starts the code which makes another code, exponentially killing my computer. Is there a way to fix this?
public class CloneMe : MonoBehaviour
{
// Start is called before the first frame update
public GameObject self;
void Start()
{
int amountOfClones = Random.Range(10, 15);
for (int i = 0; i < 1; i++)
{
transform.position = new Vector2(Random.Range(0, 7), Random.Range(0, 7));
Instantiate(self);
}
}
}
There’s no errors showing up from Unity, just insane lag that makes me have to unplug my computer.
Hey there,
what you can do is to add a “cloneThis” flag to your script. Then you only run the clone code in Start if cloneThis == true.
Then in your clone code you can add this instead of line 11:
var newObj = Instantiate(self);
newObj.GetComponent<CloneMe>().cloneThis = false;
This should work as Start only is executed on the next frame. So you have time to directly set that flag to prohibit further cloning of that object.
Use singleton
static GameObject sin;
Start(){
If(sin == null){
sin = this;
}
if(sin == this){
Instantiate (self);
}
}
Move you cloning logic into the start Method of another GameObject i.e. put it somewhere you only call once i.e. a game manager for example.
Or in a method that you can call i.e. a factory or factory method.
https://www.youtube.com/watch?v=v-GiuMmsXj4
To explain whats happening:
Start is called on the frame when a script is enabled just before any of the Update methods are called the first time.
Source:
This means you are instantiating an object that when it gets created will instantiate another one which will create another one. Without any bounds what exactly is going to tell it to stop?
Digital systems hate infinite recursion because we have limited resources and that can very quickly be eaten up, especially when you have an exponential infinite recursion as you do here.
While you can use a bool I wouldn’t suggest it personally as it seems a little bit of a clunky way to write the code i.e. not massively extendible. Say for example you want to be able to create different configurations of the instantiations or generalise it across multiple different gameobjects, you would end up with a lot of duplicated or spaghetti code.