- Home /
GameObject invisible for given time
Hi all I have set a collision between 2 objects. So when they collide, i want to temporarily make one of them invisible. I am using OnTrigger and renderer.Enabled = false. I am stuck about the time component
if i say
if(Time.time > 3.0f)
{
somemodel.renderer.enabled = false;
}
somemodel.renderer.enabled = true;
the visibility sets back to true, before even i know it :) . I am against using While on Updates. So suggest me a way?
Answer by Extrakun · Aug 04, 2010 at 10:39 AM
You can try accumulate Time.deltaTime instead, as Time.time is the absolute time elapsed since the application has run. Edit: The preceding sentence is wrong, Time.time is the amount of time elapsed since start of frame, hence the original code should have work if not for the missing else clause.
Untested code below
private var elapsedTime; private var invisible:boolean;
public function Update() { if (invisible) { if ( elapsedTime <= 3.0) { elapsedTime += elapsedTime else { invisible = false; elapsedTime = 0; gameObject.renderer.enabled=true; }
} }
public function SetInvisibleForAWhile() { invisible = true; gameObject.renderer.enabled = false; }
Or, you can store the starting Time.time, and get the current Time.time, and subtract it to see if it is 3.0.
Whoa whoa let me thank you first for the fastest reply. I m gonna try that now and let you know. Thanks again!
I made a mistake about Time.time and have edited my answer accordingly
No, Time.time is not the amount of time since the start of the frame. It's the time in seconds since the app started. The original code will not work since "Time.time > 3.0" will always be true once the app has been running for at least 3 seconds.
Answer by AliAzin · Aug 04, 2010 at 10:39 AM
you can simply do that on java script. it should be something like this:
function OnTriggerEnter(){
somemodel.renderer.enabled = false;
yield WaitForSeconds(3);
somemodel.renderer.enabled = true;
}
if you are writing your script in c#, the yield structure is different.
Answer by Wolfram · Aug 04, 2010 at 04:35 PM
While AliAzin's answer is very good, the main problem in your method is, that the ...=true part is always called, even if time>3. So the first thing to fix would be:
if(Time.time > 3.0f)
{
somemodel.renderer.enabled = false;
}else{
somemodel.renderer.enabled = true;
}