Is it possible to create new Threads inside a GTA5 script?
-
Or is there some other approach to doing synchronous stuff?
-
For Script Hook V .NET: create another class that inherits GTA.Script and use that as your thread.
For RagePluginHook: I'm not too familiar, but I believe you can create multiple GameFiber's for use as threads.
For Script Hook V: use _beginthreadex
-
@Jitnaught
Does_beginthreadex
allow natives to be called inside it?
-
@ikt
Yes https://gitlab.com/Jitnaught/RealWeather-GTA5/-/blob/master/RealWeather/script.cpp#L267 (the notify function in getWeather uses natives)
-
This is amazing info, thanks so much
-
@Jitnaught said in Is it possible to create new Threads inside a GTA5 script?:
For Script Hook V .NET: create another class that inherits GTA.Script and use that as your thread.
Does anyone have a good example of this in practice? Bit of a C# noob here
-
Just create another .cs file and inherit Script, just like normal.
Example:
This .cs file handles the main script: https://gitlab.com/Jitnaught/ropecreator-gta5/-/blob/master/RopeCreator/RopeCreator.cs
This .cs file handles the menu: https://gitlab.com/Jitnaught/ropecreator-gta5/-/blob/master/RopeCreator/Menu.cs
-
I tried the following:
// this prevents it from creating an instance of the object [ScriptAttributes(NoDefaultInstance = true)] public class ExThread : Script { public ExThread() { GTA.UI.Screen.ShowSubtitle("exthread constructed"); } // Non-static method public void mythread1() { for (int z = 0; z < 3; z++) { GTA.UI.Screen.ShowSubtitle("testing mythread..."); } } } namespace Testing { public class Test : Script { public Test() { this.Tick += onTick; this.KeyDown += onKeyDown; } private void onTick(object sender, EventArgs e) { } private void onKeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.NumPad9) { ExThread test = new ExThread(); test.mythread1(); // Creating object of ExThread class ExThread obj = new ExThread(); Thread thr = new Thread(new ThreadStart(obj.mythread1)); thr.Start(); } } } }
Which throws an unhandled exception error/null reference
System.NullReferenceException: Object reference not set to an instance of an object.
at GTA.Script..ctor()
at ExThread..ctor()
at Testing.Test.onKeyDown(Object sender, KeyEventArgs e)
at SHVDN.Script.MainLoop()
[18:46:01] [ERROR] The exception was thrown while executing the script Testing.Test.Any ideas?
-
If you want to do it that way, use this example: https://github.com/crosire/scripthookvdotnet/blob/main/examples/ScriptInstance.cs
I've always just had two classes that inherit Script though (without NoDefaultInstance attribute). Both classes are run at the start of the game. To share stuff between them just make the variable/function static. The example in my last post uses this method.
-
Ah yes finally, got it to work thanks to you. I think the problem was that I didn't have an ontick etc in my script instance since I did it the other way. I appreciate your help