I am trying to make a +1 life object and corresponding functions. I can make it appear where and when I want to. What I am having trouble with is that using this code:
When I use this it creates endless clones. By having a destroy script I am able to keep the clones to a manageable number, but the lowest number of clones I can get down to is two. Ideally, I would only like to have only one object spawn in my world, but I can’t figure out how to do it.
Are you creating the instance inside a an update function?
If so you need to only allow the creation once.
There are different ways to do this, the simplest would be to create a boolean and only create it if the boolean is true.
Something like:
var isCreated: boolean;
function Update(){
if(!isCreated){
Instantiate(PlusOneLifePreFab,Vector3(0,2.5,75.6),Quaternion.identity);
isCreated = true;
}
}
For JavaScript anyway. There are other methods as well, such as using the Awake() function.
I bet you are doing this in an Update function right? Don’t do that. Or have a variable you set when you create one, and check it before you make it (again)
You have said in a comment that your Instantiate function is nested with a switch case statement, right?
It looks like you have forgot to have a “do nothing” case in your switch case statement
int option = -1;
Update()
{
switch (option)
{
case -1:
break;
case 0:
Instantiate( ... )
option = -1;
break;
}
}
public void DoInstantiate()
{
option = 0;
}
If you don’t have a dummy case and you don’t update the switch variable to the “do nothing” case (-1 in my example) at the end (before of the break) of an action, it will result in repeating the same action every frame, constantly, until the switch variable changes.
GameObject CityClone;
public GameObject CityPrefap;
public GameObject CityPosition;
// Start is called before the first frame update
public void Create()
{
if (CityClone == null)
{
CityClone=Instantiate(CityPrefap,CityPosition.transform.position,CityPosition.transform.rotation);
}