Quantcast

Jump to content

» «
Photo

C# Best practice for a timer

1 reply to this topic
VDH-SOFT
  • VDH-SOFT

    VDH-GTAMD

  • Members
  • Joined: 04 May 2013

#1

Posted 5 days ago

Hi,

 

I have seen multiple older topics about using Timers in a C# code. But it doesn't work well for me. When I debug my code the null reference exception occurs. 

 

I don't know what the best practice is for setting a timer in the code, everyone have different solutions. What I try to do is the next:

 

I have a mod menu (nativeUI). When I save my settings from the menu another method from another static class will be called AmbientManager.EnableAmbients(); 

 

This method needs to set the timer to start and excecute another void. Sometimes it works and the game spawns over 1000 of cars in a second, but I have the timer set to 5 seconds per spwaning vehicle.. 

 

Next code I have at the moment:

 

static System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();

        public AmbientManager()
        {
 
            t.Interval = 5000;
            t.Tick += new EventHandler(SearchForPoliceCars);
            t.Tick += SearchForPoliceCars;
        }
 
        private void SearchForPoliceCars(object sender, EventArgs e)
        {
             Vehicle test = World.CreateVehicle("NINEF", new GTA.Math.Vector3(Game.Player.Character.Position.X, Game.Player.Character.Position.Y, Game.Player.Character.Position.Z));
 
        }
 
Now it says the object null reference exception, on the Vehicle. But I think it's the timer that causes the error becasue on a keydown the vehicle will spawn. 
 
In another topic I saw that t.Tick was only Tick without the "t." -> When I do that, the game will crash and spawn over 1000 of cars in a second.. 

 


Jitnaught
  • Jitnaught

    Grass tastes bad

  • Members
  • Joined: 24 Aug 2013
  • United-States

#2

Posted 5 days ago

It's best to keep all GTA-related code within the Tick, KeyDown, and KeyUp events. There's two ways you could do what you're wanting:

public AmbientManager()
{
	Interval = 5000;
	Tick += SearchForPoliceCars;
}

private void SearchForPoliceCars(object sender, EventArgs e) //all code will be called every 5 seconds
{
	 Vehicle test = World.CreateVehicle("NINEF", new GTA.Math.Vector3(Game.Player.Character.Position.X, Game.Player.Character.Position.Y, Game.Player.Character.Position.Z));
}

or

public AmbientManager()
{
	Interval = 100;
	Tick += SearchForPoliceCars;
}

int lastTime = 0;

private void SearchForPoliceCars(object sender, EventArgs e)
{
	if (Game.GameTime > lastTime + 5000) //only some code will be called every 5 seconds. you can still  have other code that's run faster
	{
	 	Vehicle test = World.CreateVehicle("NINEF", new GTA.Math.Vector3(Game.Player.Character.Position.X, Game.Player.Character.Position.Y, Game.Player.Character.Position.Z));
		lastTime = Game.GameTime;
	}
}
  • nm710 and Bob_74 like this




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users