Create only one Instantiated Object
Okay guys - I can't figure this one out. I have a day night cycle going by the rotation of the directional light, and at night I need a fire particle system prefab I have to start up, and during the day I need it to go away. How I have it set up right now, it creates to many instances and possibly would kill the game object rather than the instance? I need this Day- No fire/ Night - Fire cycle to continue for an infinite amount of time. Here is the scripts I have
This one is for the rotation of the light and to tell something that the rotation is correct for Day time or Night time
#pragma strict
public static var TimeOfDay : float = 0.0;
public static var LightRotation : float = 0.0;
function Update()
{
transform.Rotate(Vector3.right / 3.0);
LightRotation = transform.eulerAngles.x;
if (LightRotation <= 150) {
TimeOfDay = 0.0;
BroadcastMessage("KillFire");
Debug.Log(TimeOfDay);
}
else if (LightRotation >= 150) {
TimeOfDay = 1.0;
BroadcastMessage("StartFire");
Debug.Log(TimeOfDay);
}
}
This is what I have on the empty object to create the fire instance
#pragma strict
public var prefab : GameObject;;
function KillFire(){
Destroy(prefab);
}
function StartFire(){
Instantiate(prefab,transform.position, Quaternion.identity);
}
Any and all help would be greatly appreciated. Thank you!
Answer by DiegoSLTS · Aug 25, 2016 at 12:34 PM
First, you're destroying the prefab, not the instance, that KillFire won't work as expected. You have to keep a referente to the instance of the fire and destroy that reference.
That also works for your actual question. You're calling StartFire every frame if LightRotation is greater than 150, so you're creating an instance every frame. Keeping a reference to the instance you can check if it's null before doing the Instantiate code.
Anyway, a cleaner approach would be to only broadcast the messages if LightRotation passed 150 in that same frame. SendMessage and BroadcastMessage are expensive and shouldn't be called if will be ignored by the receiver.
Your answer
Follow this Question
Related Questions
Performance of instantiate and destroy for bullets 2 Answers
Cannot destroy the SphereCollider on Instantiated Objects 1 Answer
I need help with this script. Can't figure out my it isn't working.,Can't get this script to work 0 Answers
Trying to replace 2 objects. Destroying assets is not permitted to avoid data loss. 0 Answers