in the following script the objects visibility isnt toggled and it seems like cancelInvoke is cancelling in the first run through instead of subtracting from the counter and toggling the visibility then canceling when the counter has reached 0.
if i remove the CancelInvoke the objects visibility toggles on and off like i would expect
i think i am using it incorrectly but for the life of me i cannot figure whats up with the script
any ideas? on how to get this to work
i know i can do it otherways but i would like to get the invoke repeating to work, so that i understand how it should be used etc.
thanks
var counter:int=4;
private var hidden:boolean=false;
function Update()
{
if(Input.GetButton("Jump"))
{
Input.ResetInputAxes();
counter = 4;
InvokeRepeating("toggleVisibilty", 0, .3);
Debug.Log("Finished flashing");
}
}
function toggleVisibilty()
{
GameObject.Find("Roach_Sprite").GetComponent(MeshRenderer).enabled = hidden; // stop rendering the player.
hidden = !hidden;
Debug.Log(counter);
Debug.Log(hidden);
counter --;
if (counter == 0)
CancelInvoke("toggleVisibilty");
}
I dont think having invoke call GameObject.Find is a very good idea performance wise ^^.
anyway I will prefer have this script on your object that need to toggle it visibility then just enable the script
so something like that maybe (sorry C# )
public float toggleTime = 0.3f;
public int counter = 4;
//private
int storedCounter;
void Awake()
{
//I assume the script may be off when you start.
enabled = false;
storedCounter = counter;
}
void OnEnable()
{
counter = storedCounter;
InvokeRepeating("ToggleVisibility",0.01f, toggleTime);
}
public void ToggleVisibility()
{
//check that you have renderer component on this object (just defensive programming ,
//you can get rid of that if later )
if(!renderer)
{
enabled = false;
return;
}
//Do your toggle---------
else if(counter > 0)
{
renderer.enabled = !renderer.enabled;
counter --;
}
else
enabled = false;
}
void OnDisable()
{
CancelInvoke("ToggleVisibility");
}
Doing so you just fire you script form somewhere when you need
hope that help
oh by the way you could then just fire this script when your button is pressed then
hmm anyway if what you wanted to do is hide the player for X time once then show it again in that case use coroutine and yield instead.
My anser was based on a flash toggle like old skool game when you get back in game and stay invincible for a little bit of time…
If you don’t add the “f” to the number in C#, then the compiler assumes you want the number to be a double rather than a float. Unity uses floats for most things in the interests of performance.
by the way i realize ( if you didn’t before me ) that you better to move the check for renderer in OnEnable(), rather to check for it every repeat XD…my bad ^^