- Home /
bool value does not change
Hello everyone! I have a simple code here that's causing me problems. I want to create my prefab once, so that I have my boolean here to check, I can't put my code in a Start function because I might call a function CreateNext() to change the bool value to true, so that the update funciton waits until I tell(call function CreateNext) it to create an another prefab.
private var create = true;
function Update()
{
if(create)
{
var prefab:GameObject = Instantiate(myPrefab,gameObject.transform.position,Quaternion.identity);
prefab.transform.parent = transform;
create = false;
}
}
public function CreateNext()
{
create = true;
}
but as i run the game, a prefab is created non-stop that means the boolean setting to false didn't work. any ideas where's might be my mistake?
I'd suggest you have all the instantiation code in CreateNext(), then you don't have to use a boolean.
Answer by DocteurCox · May 30, 2012 at 03:03 PM
Wouldn't it be easier to use the Singleton pattern ?
Instead of having a boolean that defines whether or not your prefabs has been created, put the instance of your prefab in a static variables. Then to know if your prefab has already been created, just check if your static variable already exist. For example :
private static Instance = null;
void Update()
{
if(Instance == null)
{
// Create instance of your object here
}
}
That method works with C#, don't know if it works with other language.
Hoped it helped ;)
Thanks, But I need to control that! as you see in my code, I have a public function CreateNext which can change the value of the boolean. So I need it to be created once as the game starts, but not once for the whole game! thx btw
Well, this isn't completely incompatible with my method. Let's assume you want to switch to next prefab like you would have done with CreateNext, you would just have to set Instance to null. :)
Your answer
Follow this Question
Related Questions
Start, Awake, Update. Any other ways to call functions from an empty GameObject? 3 Answers
Detecting Input in the Start function (C#) 1 Answer
Script initialization when instancing a game object 0 Answers
Rigidbody.AddForceAtPosition & functions 1 Answer
Im a bit confused on a simple script 1 Answer